diff --git "a/test.tsv" "b/test.tsv" deleted file mode 100644--- "a/test.tsv" +++ /dev/null @@ -1,7550 +0,0 @@ -39424767 0 android studio emulator: WARNING: Increasing RAM size to 1024MB
I am trying to build my first android application in Android Studio, following the tutorial https://developer.android.com/training/basics/firstapp/creating-project.html, using AndroidStudio 2.1.2.
Whenever I run the emulator, I get this error message:
Android Emulator could not allocate 1.0 GB of memory for the current AVD configuration. Consider adjusting the RAM size of your AVD in the AVD Manager. Error detail: QEMU 'pc.ram': Cannot allocate memory
Decreasing the size of the memory on the Nexus5x emulator has no effect, so the error message still says "could not allocate 1.0 GB", even when I adjust the memory of the AVD to 256MB. The app needs to run on Android 6.0, with a Nexus5x emulator, so I can't try with a different emulator. Any help would be much appreciated :)
-6499962 0I would do a loop. Keep adding days until you hit a day that works.
-8978532 0 NSView subclass over another NSView subclass?I'm trying to create an Cocoa-AppleScript Application with some basic functions, and I want to display a background image for the window and then display a color box above it.
I finally figured out how to set the background image via this guide (http://www.mere-mortal-software.com/blog/details.php?d=2007-01-08), but I don't know how to set a color box above it. The basic layout I'm trying to achieve is this:

The window view has a class of ViewBackground which is a subclass of NSView. The ViewBackground.m file looks like this:
-(void)drawRect:(NSRect)rect { NSImage *anImage = [NSImage imageNamed:@"repeat"]; [[NSColor colorWithPatternImage:anImage] set]; NSRectFill([self bounds]); } Like I said, that works fine. The problem is when I try to put the box with the background color white above it. I thought I would be able to do this by making a new subclass of NSView, ContentBackground. The ContentBackground.m file looks like this:
-(void)drawRect:(NSRect)rect { [[NSColor whiteColor] set]; NSRectFill(rect); } The hierarchy of my windows looks like this:

Now this sometimes works, but usually produces this result in the debugger:
int main(int argc, char *argv[]) { [[NSBundle mainBundle] loadAppleScriptObjectiveCScripts]; return NSApplicationMain(argc, (const char **)argv); Thread 1: Stopped at breakpoint 1 } What am I doing wrong and how can I fix this?
Also, the content (buttons, etc..) will go on top of the ContentBackground box.
In Private Sub DetailsView1_ItemInserting event I changed
Dim txtYearPlant As TextBox = DirectCast(DirectCast(sender, DetailsView).FindControl("YearPlant"), TextBox)
TO
Dim txtYearPlant As TextBox = TryCast(view.FindControl("YearPlant"), TextBox) e.Values.Add("YearPlant", txtYearPlant.Text)
So now the value in the PlantYear textbox is saved to the record.
-33778234 0 Telegram Bot API: How to avoid Integer overflow in updates id?Telegram bot api get updates function takes last update id as offest parameter. But update id is signed 32bit integer, so it is just 2147483647. Currently my bot receiving update id 348691972. 2147483647 is a small number, for example current China and India population is more then int 32.
What will happen when update id will overflow and how to avoid it? Is it some kind of problem 2000?
In .NET, what's the best way to prevent multiple instances of an app from running at the same time? And if there's no "best" technique, what are some of the caveats to consider with each solution?
-33894262 0Take a look at the OpenCV doc:
For Canny:
apertureSize: aperture size for the Sobel operator.
And for Sobel:
ksize: size of the extended Sobel kernel; it must be 1, 3, 5, or 7.
So the aperture size in Canny is limited by the Sobel kernel size.
This is verified in the source code :
if ((aperture_size & 1) == 0 || (aperture_size != -1 && (aperture_size < 3 || aperture_size > 7))) CV_Error(CV_StsBadFlag, "Aperture size should be odd"); So, unless you rewrite yourself some code, there's no way to use Canny with a larger aperture size. You can apply your custom large sobel filter with filter2d, and then code the Canny non maxima suppression.
However, Sobel with mask larger then 3x3 is rarely used in practice.
-20086791 0 How can I send an email with a layoutI am using grails mail plugin. When I submit my form, it will send an email from aaa@example.com to textField name="email successfully but how can I send an email with a layout...not blank like this picture http://www.4shared.com/photo/uT2YUCfo/Capture__2_.html or maybe some CSS..
FORM
<g:form action="send"> <table style="width:500px"> <tbody> <tr> <td>Your Email Address </td> <td><g:textField style="width:250px" name = "email"/></td> </tr> <tr> <td>Your Name</td> <td><g:textField style="width:250px" name = "user"/></td> </tr> <tr> <td><input type="submit"/></td> </tr> </tbody> </table> </g:form> MAIL CLOSURE
def send = { sendMail { to params.email from "aaa@yahoo.com" subject "Test Reset Password" body(view:"/user/layoutmail",model:[name:params.user]) } render "Email Terkirim" }
-30733824 0 Yes. The code is executed in serial.
-33529333 0Yes, validators are only run if the path is changed, and they also only run if they're not undefined. Except the Required validator, which runs in both cases.
You can use boolean removeAll(Collection<?> c) method.
Just note that this method modifies the List on which you invoke it. In case you to keep the original List intact then you would have to make a copy of the list first and then the method on the copy.
e.g.
List<Employee> additionalDataInListA = new ArrayList<Employee>(listA); additionalDataInListA.removeAll(listB);
-33362460 0 Does every view have its own canvas/bitmap to draw on? I have a relativelayout with three full screen child views of the same custom view class. I am wondering whether I should be worried about memory. Judging by this answer: Understanding Canvas and Surface concepts
All views get passed the same canvas with underlying bitmap to draw on so that the memory is not tripled. Can anyone confirm? It would make sense, otherwise a full screen textview would be very inefficient.
Bonus: is the purpose of canvas to define a drawable area of a bitmap and translating the view coordinates to bitmap coordinates?
-7438401 0 MySQL REPLACE rows WHERE field a equals x and field b equals yI'm trying to construct a 'new comments' feature where the user is shown the number of new comments since the last visit. I've constructed a 'Views' table that contains the topic id, the user id and a timestamp. What's the best way of updating the timestamp every time the user visits that topic or inserting a fresh row if one doesn't exist? At the moment I have:
REPLACE INTO Views (MemberID, TopicID, Visited) SET ('$_SESSION[SESS_MEMBER_ID]', '$threadid', '$t') WHERE MemberID = $_SESSION[SESS_MEMBER_ID] AND TopicID = $threadid However, this does not work. Is it possible to do this in one query?
-3074100 0solved:
remove margin-bottom:10px; from your
.itemsWrapper { margin-bottom:10px; overflow:auto; width:100%; background: green; }
-40416451 0 Query returing no results codename one Query showing no results and not giving any error .control not entering inside the if block help me out that where is the mistake i am doing ? i have tried many ways to get the result but all in vain. When i tried the following before the if statement
int column=cur.getColumnCount(); Row row=cur.getRow(); row.getString(0); then i got the resultset closed exception
Database db=null; Cursor cur=null; System.out.print("Printing from accounts class "+Email+Password); String [] param={Email,Password}; System.out.print(param[0]+param[1]); try{ db=Display.getInstance().openOrCreate("UserAccountsDB.db"); cur= db.executeQuery("select * from APPUserInfo WHERE Email=? AND Password=?",(String [])param); int columns=cur.getColumnCount(); if(columns > 0) { boolean next = cur.next(); while(next) { Row currentRow = cur.getRow(); String LoggedUserName=currentRow.getString(0); String LoggedUserPassword=currentRow.getString(1); System.out.println(LoggedUserName); next = cur.next(); } } }catch(IOException ex) { Util.cleanup(db); Util.cleanup(cur); Log.e(ex); } finally{ Util.cleanup(db); Util.cleanup(cur); }
-15531622 0 It would be better if you sorted the objects you are populating richtextbox1 with instead of trying to split and parse the text of richtextbox1.
Lets say you have a list with students
List<Student> studentList = new List<Student>(); That list could be sorted by using something similar to this:
StringBuilder sb = new StringBuilder(); studentList.OrderByDescending(x=>x.Average) .ToList() .ForEach(x=> sb.Append(String.Format("{0} {1} {2} {3} {4}" + Environment.NewLine,x.Id,x.Name,x.Sname,x.DOB,x.Average))); richTextBox2.Text = sb.ToString();
-5745113 0 If I understood your question, you want the duplicated row of selects to reset their values.
In this case you can just remove this:
dropdownclone.find('select').each(function(index, item) { //set new select to value of old select $(item).val( $dropdownSelects.eq(index).val() ); }); and replace it with:
dropdownclone.find('option').attr('selected', false);
-38242048 0 Expect not accepting negative values I am trying to run expect with negative values. But I'm getting bad flag error.
Test File:
echo "Enter Number:" read num echo $num Expect File:
spawn sh test.sh expect -- "Enter Number:" {send "-342345"} I even tried to escape negative values with \ option still it's not working.
This will definitely do the task for you.
tTable = {} OldIDX, OldIDX2, bSwitched, bSwitched2 = 0, 0, false, false for str in io.lines("txt.txt") do local _, _, iDx, iDex, sIdx, sVal = str:find( "^%| ([%d|%s]?) %| ([%d|%s]?) %| (%S?) %| (%S?) %|$" ) if not tonumber(iDx) then iDx, bSwitched = OldIDX, true end if not tonumber(iDex) then iDex, bSwitched2 = OldIDX2, true end OldIDX, OldIDX2 = iDx, iDex if not bSwitched then tTable[iDx] = {} end if not bSwitched2 then tTable[iDx][iDex] = {} end bSwitched, bSwitched2 = false, false tTable[iDx][iDex][sIdx] = sVal end The only thing you can change in the code is the name of the file. :)
Seems like I was wrong, you did need some changes. Made them too.
-20801157 0Normally it can't. It will complain about libc being too old, for one.
If you statically link with libstdc++ and carefully avoid newer glibc features, you may be able to get away with it. The latter is not always possible though. Static linking with libc is not officially supported and may work or not work for you.
-19292671 0Try this:
textarea { overflow-x: vertical; }
-21975919 0 That error means that Laravel is trying to write data to your storage/view file, but it doesn't have permissions (write access). Storage/view is a folder for caching view files.It is default Laravel behaviour, so change permissions on whole storage folder, becuse there is more files inside, that Laravel will try to use for other purposes. For example, services.json is used when you add new service provider, and if it is locked, Laravel will complain.
-40684641 0Maybe an idea which might work for you:
To ban a user, create an entry in your database to the user to flag the user as banned with a timestamp NOW + X
{ "users" : { "bad_user" : { "banned" : { "until" : 123456 // timestamp NOW + X } } } } Now whenever the user logs in afterwards, you check wether the user is banned and immediately try to delete that entries. If it fails, penalty time is still running. If it succeeds, well then the user can use your app :)
The trick is to use firebase rules to restrict possible changes.
something like:
{ "rules" : { "users" : { "$uid" : { // ... "banned" : { .write : "(!newData && now < data.child('until').val() )" .... Please note - these are not working rules, but should help to figure it out.
-35160200 0 Express & Passport with multiple subdomainsI'm merging two little apps into one, that is supposed to be accessed via two subdomains. To do so I'm using the module "express-subdomain". I'm trying to use Passport so when a user logs in in the first app, he is logged in in both apps. However using req.isAuthenticated() I can indeed login in the "first" app, but then I'm not in the "second" one.
I'm searching for any solution to have a passport authentification in the first subdomain and being logged in in the second one, including keeping two disctinct apps if needed.
Assuming that passport is correctly configured for a local strategy, as well as the routers and the rest of the app. Here is what it looks like :
app.js
// <- requires etc var passport = require('./configurePassport.js')(require('passport')); var app = express(); app.use(cookieParser()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); app.use(expressSession({ secret: 'bestSecretEver', resave: false, saveUninitialized: false })); app.use(passport.initialize()); app.use(passport.session()); // and others var firstRouter = express.Router(); firstRouter.use('/public', express.static(__dirname + '/first/public')); firstRouter.use(favicon(__dirname + '/first/public/favicon.ico')); // <- setting first router's GET, POST etc app.use(subdomain('sub1', firstRouter)); // for sub1.example.com var secondRouter = express.Router(); secondRouter.use('/public', express.static(__dirname + '/second/public')); secondRouter.use(favicon(__dirname + '/second/public/favicon.ico')); // <- setting second router's GET, POST etc app.use(subdomain('sub2', secondRouter)); // for sub2.example.com Any idea ?
-7020453 0There is an equation given here (the last one).
By looping over all the x and y coordinates, and checking that the output of this equation is less than zero, you can determine which points are 'inside' and colour them appropraitely.
-30061259 0To allow nice zooming you should add this line to the two you show:
chart1.ChartAreas["ChartArea1"].AxisX.ScaleView.Zoomable = true; Here is a function to calculate an average of the visible points' 1st YValues:
private void chart1_AxisViewChanged(object sender, ViewEventArgs e) { // for a test the result is shown in the Form's title Text = "AVG:" + GetAverage(chart1, chart1.Series[0], e); } double GetAverage(Chart chart, Series series, ViewEventArgs e) { ChartArea CA = e.ChartArea; // short.. Series S = series; // references DataPoint pt0 = S.Points.Select(x => x) .Where(x => x.XValue >= CA.AxisX.ScaleView.ViewMinimum) .DefaultIfEmpty(S.Points.First()).First(); DataPoint pt1 = S.Points.Select(x => x) .Where(x => x.XValue <= CA.AxisX.ScaleView.ViewMaximum) .DefaultIfEmpty(S.Points.Last()).Last(); double sum = 0; for (int i = S.Points.IndexOf(pt0); i < S.Points.IndexOf(pt1); i++) sum += S.Points[i].YValues[0]; return sum / (S.Points.IndexOf(pt1) - S.Points.IndexOf(pt0) + 1); } Note that the ViewEventArgs parameter is providing the values of the position and size of the View, but these are just the XValues of the datapoints and not their indices; so we need to search the Points from the left for the 1st and from right for the last point.
Update Sometimes the zooming runs into a special problem: When the data are more finely grained than the default CursorX.IntervalType it just won't let you zoom. In such a case you simply have to adapt to the scale of your data, e.g. like this: CA.CursorX.IntervalType = DateTimeIntervalType.Milliseconds;
A and B are integers.
Is it certain, with all the complexities of rounding errors in JavaScript, that:
(A/(A+B))*(A+B) === A
This is to say that if the user enters 10, and 20 for A and B respectively, can I store the summed total (30) with A = .33333333 and B = .66666666 and later multiply the sum by these decimals to get back to the value of 10 (with no rounding error)?
-25184607 1 Sort a dictionary of arrays in python with a tuple as the keyI a dictionary with a string tuple as the key and an array as the value:
some_dict = {} some_dict[(A,A)] = [1234, 123] some_dict[(A,B)] = [1235, 13] some_dict[(A,C)] = [12, 12] some_dict[(B,B)] = [12621, 1] ... I am writing this to a csv file:
for k,v in some_dict.iteritems(): outf.write(k[0]+","+k[1]+","+str(v[0])+","str(v[1])+"\n") output:
A,A,1234,123 A,B,1235,13 A,C,12,12 B,B,12621,1 I'd like to sort it based on the first number "column" before writing to a file (or after and just rewrite?) so the output should be like:
B,B,12621,1 A,B,1235,13 A,A,1234,123 A,C,12,12 ^ Sorted on this 'column' How do I do this? The file is very large, so doing it before writing would be better I think.
-17990096 0Focus movement is based on an algorithm which finds the nearest neighbor in a given direction. In rare cases, the default algorithm may not match the intended behavior of the developer.
Change default behaviour of directional navigation by using following XML attributes:
android:nextFocusDown="@+id/.." android:nextFocusLeft="@+id/.." android:nextFocusRight="@+id/.." android:nextFocusUp="@+id/.." Besides directional navigation you can use tab navigation. For this you need to use
android:nextFocusForward="@+id/.." To get a particular view to take focus, call
view.requestFocus() To listen to certain changing focus events use a View.OnFocusChangeListener
You can use android:imeOptions for handling that extra button on your keyboard.
Additional features you can enable in an IME associated with an editor to improve the integration with your application. The constants here correspond to those defined by imeOptions.
The constants of imeOptions includes a variety of actions and flags, see the link above for their values.
Value example
the action key performs a "next" operation, taking the user to the next field that will accept text.
the action key performs a "done" operation, typically meaning there is nothing more to input and the IME will be closed.
Code example:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="32dp" android:layout_marginTop="16dp" android:imeOptions="actionNext" android:singleLine="true" android:ems="10" > <requestFocus /> </EditText> <EditText android:id="@+id/editText2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editText1" android:layout_below="@+id/editText1" android:layout_marginTop="24dp" android:imeOptions="actionDone" android:singleLine="true" android:ems="10" /> </RelativeLayout> If you want to listen to imeoptions events use a TextView.OnEditorActionListener.
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEARCH) { performSearch(); return true; } return false; } }); <div id = "container"> <div id="header"></div> <div id="content"></div> <div id="footer"></div> </div> #container {min-width:620px;} See example: http://jsfiddle.net/calder12/xN2PV/3/
Point to note. min-width is not supported in IE6. I doubt this matters, if it does you'll need a different solution.
-20846012 0This should work for you. Check out the in-line comments.
# 1. Let's assume the folder c:\test contains a bunch of plain text files # and we want to find only the ones containing 'foo' AND 'bar' $ItemList = Get-ChildItem -Path c:\test -Filter *.txt -Recurse; # 2. Define the search terms $Search1 = 'foo'; $Search2 = 'bar'; # 3. For each item returned in step 1, check to see if it matches both strings foreach ($Item in $ItemList) { $Content = $null = Get-Content -Path $Item.FullName -Raw; if ($Content -match $Search1 -and $Content -match $Search2) { Write-Host -Object ('File ({0}) matched both search terms' -f $Item.FullName); } } After creating several test files, my output looks like the following:
File (C:\test\test1.txt) matched both search terms
-16607326 0 480 * 800 is a mdpi device. You can can put these image resources in drawable-mdpi if you want the device to auto adjust for smaller and larger screen sizes. If you want these images to be of maximum size you can put it in drawable-xhdpi. If not i.e. if you want same image to be used in all the screen sizes then you can simply put in drawable folder in resource.
For more information you can check this :developer link
-8830512 0 how create simple side menu with jquery?i have menu in side location and that code is :
<ul> <li> <span class="arz"> first menu </span> <ul id="arz"> <li> first submenu </li> <li> second submenu </li> <li> third submenu </li> </ul> </li> <li class="words"> two menu <ul id="words"> <li> first submenu </li> <li> second submenu </li> </ul> </li> and jquery code is :
$(document).ready(function(){ $(".submenu").click(function(){ $(this).children(this).slideToggle("slow"); }); }); but i want by clicking on first menu ul element with id="arz" usingslideToggle,slideToggle`. by thanks
this code do it but when i click on every submenu item corresponding ul use
aya
You can simply overload the enqueue class to take both Dates and Integers. In either case, it sounds like you need a method getValue() in CInteger that lets you access the int value.
public class CInteger { //constructors, data public void getValue() { return i; } } and then you can have two enqueue() methods in your other class:
public void enqueue(Date d) { add(tailIndex, d); } public void enqueue(CInteger i) { add(tailIndex, new Integer(i.getValue()); //access the int value and cast to Integer object } And Java will know which one you are calling automatically based on the parameters.
-17439523 0$('#element').keyUp(function(e){ var max = 2; var text = $(e.currentTarget).text().substring(0,max); $(e.currentTarget).text(text); });
-1502685 0 You can open an interactive shell by right-clicking on the project, selecting Scala-> Create interpreter in XYZ.
-33129705 0You may try below query
SELECT DATEADD(MINUTE,(LEFT(@hour,2)*60+RIGHT(@hour,2)),@conductor_date)
-8551762 0 Bind a popup to another draggable popup relatively I use a jQuery UI dialog in which there is another pop-up.
$("#dialog").dialog({ autoOpen: false, show: "blind", hide: "explode" }); $("#opener").click(function() { $("#dialog").dialog("open"); return false; }); // BUTTONS $('.fg-button').hover(function() { $(this).removeClass('ui-state-default').addClass('ui-state-focus'); }, function() { $(this).removeClass('ui-state-focus').addClass('ui-state-default'); }); // MENUS $('#hierarchybreadcrumb').menu({ content: $('#hierarchybreadcrumb').next().html(), backLink: false }); See here the live version: http://jsfiddle.net/nrWug/1
If I open the iPod menu and than drag the dialog, the iPod menu is displaced. How can I bind these two to make the dialog draggable and resizable?
-1905416 0You can use spring with hibernate. You just need to make a bean for your hibernate configuration and load it using aop or bean name into your application startup.
Here is a tutorial : http://www.roseindia.net/struts/hibernate-spring/spring-context.shtml and another one : http://www.ibm.com/developerworks/web/library/wa-spring2/
-29054976 0 Download in .zip file works with website image but not image from Amazon S3 with signed UrlI have an object with signed Urls to images on Amazon S3. My example is simplified to one image and my goal is to download a zip file with that image.
This image works with my code in the variable $fileUrl
But not this (in variable $fileUrl), I get a corrupt .zip file. I can open the image in the browser with the signed url.
$zipName = 'zipfile.zip'; # create new zip opbject $zip = new ZipArchive(); $fileUrl = 'https://mybucketname.s3.amazonaws.com/94c70e8a-61f6-4f58-a4b7-1679df5a7c1f.jpg?response-content-disposition=attachment%3B%20filename%3D94c70e8a-61f6-4f58-a4b7-1679df5a7c1f.jpg&AWSAccessKeyId=AKIAJNY3GPOFFLQ&Expires=1426371544&Signature=HDNhGKHDsjEgqkMreN3tbozkfzo%3D'; # create a temp file & open it $tmp_file = tempnam('.',''); $zip->open($tmp_file, ZipArchive::CREATE); # download file $download_file = file_get_contents($fileUrl); #add it to the zip $zip->addFromString(basename($fileUrl),$download_file); # close zip $zip->close(); # send the file to the browser as a download header('Content-type: application/zip'); header('Content-disposition: attachment; filename='.$zipName); header('Content-Length: ' . filesize($tmp_file)); readfile($tmp_file);
-1769169 0 Toy can try something like this
declare @t table (i int, d datetime) insert into @t (i, d) select 1, '17-Nov-2009 07:22:13' union select 2, '18-Nov-2009 07:22:14' union select 3, '17-Nov-2009 07:23:15' union select 4, '20-Nov-2009 07:22:18' union select 5, '17-Nov-2009 07:22:17' union select 6, '20-Nov-2009 07:22:18' union select 7, '21-Nov-2009 07:22:19' --order that I want select * from @t order by d desc, i declare @currentId int; set @currentId = 4 SELECT TOP 1 t.* FROM @t t INNER JOIN ( SELECT d CurrentDateVal FROM @t WHERE i = @currentId ) currentDate ON t.d <= currentDate.CurrentDateVal AND t.i != @currentId ORDER BY t.d DESC SELECT t.* FROM @t t INNER JOIN ( SELECT d CurrentDateVal FROM @t WHERE i = @currentId ) currentDate ON t.d >= currentDate.CurrentDateVal AND t.i != @currentId ORDER BY t.d You must be carefull, it can seem that 6 should be both prev and next.
-11335888 0Apple users can download your .apk file, however they cannot run it. It is a different file format than iPhone apps (.ipa)
-3263295 0This has worked for me
$(window).bind("resize", function(e){ // do something }); You are also missing the closing bracket for the resize function;
-27848102 0In the usual case destructor is not caused for objects created in main(). But there is a good & elegant solution - you can put your code into the extra parentheses, and then the destructor will be invoked:
int main() { { myApp app; app.run(); getchar(); } // At this point, the object's destructor is invoked }
-18447107 0 How do I tell solr where my document collection is? My sysadmin installed solr here: /software/packages/solr-4.3.1/ I followed the tutorial (using Jetty) successfully. We have a working installation and things work as expected. I also, using Solarium, can query the example/collection1 document set from my website.
Now I want to create my own document set that will live outsite of /software/packages/solr-4.3.1/ but still use the instance of solr that lives in /software/packages/solr-4.3.1/. I copied over the example directory to /path/to/mydocs. I tried to go through the tutorial again from the new location. No dice. How do I tell solr where my document collection is?
I'm relatively new to code and have been building a little project called http://keyboardcalculator.com/ to improve my jQuery.
I'm trying to add some more features to improve some things - and I've coded them! - but I want to add a button at the bottom of the page that displays a div to tell people what they are.
I don't want to tarnish the user flow when the button is clicked - and a big part of that for me is that I don't want the user to have to click back into one of the text-input boxes to keep doing calculations.
I want the focus to go back onto the last text-input that the user had focus on. This is my attempt to get it working on the #ansinput text-input field (the big one with the answer in):
if ($('#ansinput').is(':focus')) { $('#more-commands-button').click(function() { alert('hello') }); } But I'm not getting my alert.
Any help as where to go from here would be fantastic!
Thank you very much StackOverflow!
-34508804 1 Count number of foreign keys in DjangoI've read the documentation and all the other answers on here but I can't seem to get my head around it.
I need to count the number of foreign keys in an other table connected by a foreign key to a row from a queryset.
class PartReference(models.Model): name = models.CharField(max_length=10) code = models.IntegerField() class Part(models.Model): code = models.ForeignKey(PartReference) serial_number = models.IntegerField() I'll do something like:
results = PartReference.objects.all() But I want a variable containing the count of the number of parts like any other field, something like:
results[0].count to ultimately do something like:
print(results[0].name, results[0].code, results[0].count) I can't wrap my head around the Django documentation- There is a some stuff going on with entry_set in the example, but doesn't explain where entry came from or how it was defined.
I am developing a game which is saving opponents ID. So I wanted to know how can I get user's name and and profile pic from the id here is what goes in for the parameter in
[facebook requestWithGraphPath:@"_______" andDelegate:self]; thanks
-35956230 0Oke i have a (ugly?) temporary Fix... What works till now What the working method is for now:
class class1(): ... init etc... def function1(inputs): do something return(output1) def function2(inputs): temp = class1(some inputs) returnval = temp.function1() do something else return(output2) In my opinion it is a ugly solution so if somebody knows a better one!! comment please!!
-40465194 0 How to run a infinite angular forEach loop in angularjs?InstitutionStructure.teamHierarchy().then(function(response) { $scope.hierarchyList = response.data; $scope.hierarchyListsData = _.where($scope.hierarchyList, {reportingMemberId: null}); angular.forEach($scope.hierarchyListsData, function(value1, key1) { value1.teamMember = []; angular.forEach($scope.hierarchyList, function(value2, key2) { if(value1.teamMemberId === value2.reportingMemberId) { value1.teamMember.push(value2); } }) }) From the above code I have loaded my hierarchyListsData continuously and I have to fetch list that corresponds to have teamMemberId which is equal to reportingMemberId till the object has no other corresponding values. Please help to find the solution.
-984887 0C compiles down to machine code and doesn't require any runtime support for the language itself. This means that it's possible to write code that can run before things like filesystems, virtual memory, processes, and anything else but registers and RAM exist.
-2359493 0 Starting multiple gui (WinForms) threads so they can work separetly from one main gui in C#?I've one MainForm window and from that user can press 3 buttons. Each of the button starts new Form in which user can do anything he likes (like time consuming database calls etc). So i decided to put each of the forms in it's own threads:
private Thread subThreadForRaportyKlienta; private Thread subThreadForGeneratorPrzelewow; private Thread subThreadForRaporty; private void pokazOplatyGlobalne() { ZarzadzajOplatamiGlobalneDzp varGui = new ZarzadzajOplatamiGlobalneDzp(); varGui.ShowDialog(); } private void pokazRaportyKlienta() { RaportyDzpKlient varGui = new RaportyDzpKlient(); varGui.ShowDialog(); } private void pokazRaportyWewnetrzne() { RaportyDzp varGui = new RaportyDzp(); varGui.ShowDialog(); } private void pokazGeneratorPrzelewow() { ZarzadzajPrzelewamiDzp varGui = new ZarzadzajPrzelewamiDzp(); varGui.ShowDialog(); } private void toolStripMenuGeneratorPrzelewow_Click(object sender, EventArgs e) { if (subThreadForGeneratorPrzelewow == null || subThreadForGeneratorPrzelewow.IsAlive == false) { subThreadForGeneratorPrzelewow = new Thread(pokazGeneratorPrzelewow); subThreadForGeneratorPrzelewow.Start(); } else { } } private void toolStripMenuGeneratorRaportow_Click(object sender, EventArgs e) { if (subThreadForRaporty == null || subThreadForRaporty.IsAlive == false) { subThreadForRaporty = new Thread(pokazRaportyWewnetrzne); subThreadForRaporty.Start(); } else { } } private void toolStripMenuGeneratorRaportowDlaKlienta_Click(object sender, EventArgs e) { if (subThreadForRaportyKlienta == null || subThreadForRaportyKlienta.IsAlive == false) { subThreadForRaportyKlienta = new Thread(pokazRaportyKlienta); subThreadForRaportyKlienta.Start(); } else { } } I've got couple of questions and i hope someone could explain them:
Show() instead of ShowDialog() the windows just blink for a second and never shows. What's the actual difference between those two and why it happens?ShowDialog everything seems normal but i noticed not everything gets filled properly in one of the gui's (one listView stays blank even thou there are 3 simple add items in Form_Load(). I noticed this only in one GUI even thou on first sight everything works fine in two other gui's and i can execute multiple tasks inside those Forms updating those forms in background too (from inside the forms methods). Why would this one be diffrent?Panel div = new Panel(); Panel innerdiv = new Panel(); TextBox txt = new TextBox(); innerdiv.Controls.Add(txt); div.Controls.Add(innerdiv); CustomAttributes.Controls.Add(div); Your CustomAttributes holds Panel. Try this :
var textboxes = CustomAttributes.Controls.OfType<Panel>() .Select(p => p.Controls.OfType<Panel>().First()) .Select(p => p.Controls.OfType<TextBox>().First())
-27319280 0 while(token != NULL){ printf("%s\n", token); token = strtok(NULL, space); } The while loop will fail when the token is NULL. At this time you are trying to print this pointer using your second printf() in the while loop which will lead to undefined behavior.
Get rid of your second printf()
MSIs can be authored per-user or per-machine. Per-user installs won't ask for elevation by default. Per-machine installs will ask for elevation once they hit the InstallExecuteSequence.
-32058029 0 Function returning REF CURSORI have package like this:
CREATE OR REPLACE PACKAGE product_package AS TYPE t_ref_cursor to IS REF CURSOR; FUNCTION get_products_ref_cursor RETURN t_ref_cursor; END product_package; CREATE OR REPLACE PACKAGE BODY product_package AS FUNCTION get_products_ref_cursor is RETURN t_ref_cursor IS products_ref_cursor t_ref_cursor; BEGIN OPEN products_ref_cursor FOR SELECT product_id, name, price FROM Products; RETURN products_ref_cursor; END get_products_ref_cursor; END product_package; My question is, how can I use function get_products_ref_cursor (ref cursor) to get list of products?
-3663001 0Check out this book, The Elements of Computing Systems: Building a Modern Computer from First Principles it takes you step by step through several aspects of designing a computer language, a compiler, a vm, the assembler, and the computer. I think this could help you answer some of your questions.
-22267605 0if you want to remove the grey color in active buttons, just override it as follows:
.active{ background-color:white !important; } note:
And can you please let me know how I can get rid of the darker grey at the Top of the active class?
well, if you are reffering to the highlighted button in the second image, it doesn't have active class, it's a non-active class. by setting all buttons as active initially,on first click it simply becomes inactive. You might want to think about what you are doing.
Update if you want to change the grey color you can do so by adding another class and toggling it as follows:
.select{ background-color:white !important; } $("div").children().click(function () { $(this).toggleClass("select"); }); working fiddle
-15785466 0You do not need jQuery for this. In cases where jQuery really isn't needed, I don't really suggest it. At that point it's just kind of pointless. Use regular JS where possible, use jQuery where needed.
for (var i = 0; i < pieData2.length; i++) { alert(pieData2[i].label + ' : ' + pieData2[i].value); } If you really want to use jQuery, since $.each can iterate over arrays AND objects, you can just use it to iterate over the array and alert each.
This will iterate over each object in the array and alert each key, value pair...
$.each(pieData2, function (key, obj) { alert(obj.label + ' : ' + obj.value); }); If you need to iterate over the array and over each object (if you do not know the length), then you can do:
for (var i = 0; i < pieData2.length; i++) { for (var prop in pieData2[i]) { if (pieData2[i].hasOwnProperty(prop)) { alert(prop + ' : ' + pieData2[i][prop]); } } } or
$.each(pieData2, function(obj) { $.each(pieData2[obj], function(key, value) { alert(key + ' : ' + value); }); });
-36029791 0 Try
Dim data As Range Set data = Intersect(Sheet2.Columns("O"), Sheet2.UsedRange) data.NumberFormat = "mm/dd/yyyy"
-15988549 0 You're trying to ceil an array, you can do it on a numeric value.
Try editing your query like this:
$query = "SELECT COUNT(id) AS tot FROM actiongame"; And then your PHP code like this:
$total_records = $row['tot'];
-3323900 0 Passing double types to ceil results in different values for different optimization levels in GCC Below, the result1 and result2 variable values are reporting different values depending upon whether or not you compile the code with -g or with -O on GCC 4.2.1 and on GCC 3.2.0 (and I have not tried more recent GCC versions):
double double_identity(double in_double) { return in_double; } ... double result1 = ceil(log(32.0) / log(2.0)); std::cout << __FILE__ << ":" << __LINE__ << ":" << "result1==" << result1 << std::endl; double result2 = ceil(double_identity(log(32.0) / log(2.0))); std::cout << __FILE__ << ":" << __LINE__ << ":" << "result2==" << result2 << std::endl; result1 and result2 == 5 only when compiling using -g, but if instead I compile with -O I get result1 == 6 and result2 == 5.
This seems like a difference in how optimization is being done by the compiler, or something to do with IEEE floating point representation internally, but I am curious as to exactly how this difference occurs. I'm hoping to avoid looking at the assembler if at all possible.
The above was compiled in C++, but I presume the same would hold if it was converted to ANSI-C code using printfs.
The above discrepancy occurs on 32-bit Linux, but not on 64-bit Linux.
Thanks bg
-6884628 0 C with assembly tutorialsPlease, advice me manuals or tutorials by joint usage C language with assembly in Unix systems.
Thank you.
-3543373 0The Base.cs file looks like this.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Agatha.Common; public abstract class BaseRequest :Request { public string UserName { get; set; } public string UserDomainName { get; set; } public string ClientLanguageCode { get; set; } public DateTime ClientCreated { get; set; } public DateTime ClientSent { get; set; } public DateTime ServerReceived { get; set; } public DateTime ServerProcessed { get; set; } public void BeforeSend(IUserContext context) { ClientSent = DateTime.UtcNow; UserName = context.UserName; UserDomainName = context.UserDomainName; ClientLanguageCode = context.LanguageCode; } } public abstract class BaseResponse : Response { public DateTime ServerCreated { get; set; } public DateTime ServerProcessed { get; set; } public string[] ValidationErrors { get; set; } public bool IsValid { get { return Exception == null & !ValidationErrors.Any(); } } }
-19306013 0 The garbage-collector does not identify and examine garbage, except perhaps when processing the Large Object Heap. Instead, its behavior is like a that of a bowling-alley pinsetter removing deadwood between throws: the pinsetter grabs all the pins that are still standing, lifts them off the surface of the lane, and then runs the sweeper bar across the lane without regard for how many pins are on that surface. Sweeping out memory wholesale is much faster than identifying individual objects to be deleted. If 1% of objects have finalizers (the real number's probably even less), then it would be necessary to examine 100 object headers to find each finalizable object. Having a separate list of objects which have finalizers makes it unnecessary for the GC to even look at any garbage objects that don't.
-26357528 0window.attachEvent("onmouseout", popUp); you lost 'on'
-2767749 0If you have control over both domains, you can try a cross-domain scripting library like EasyXDM, which wrap cross-browser quirks and provide an easy-to-use API for communicating in client script between different domains using the best available mechanism for that browser (e.g. postMessage if available, other mechanisms if not).
Caveat: you need to have control over both domains in order to make it work (where "control" means you can place static files on both of them). But you don't need any server-side code changes.
In your case, you'd add javascript into one or both of your pages to look at the location.href, and you'd use the library to call from script in one page into script in the other.
Another Caveat: there are security implications here-- make sure you trust the other domain's script!
-411660 0 Enterprise Library Unity vs Other IoC ContainersWhat's pros and cons of using Enterprise Library Unity vs other IoC containers (Windsor, Spring.Net, Autofac ..)?
-34653126 0If SaveChanges fails, then you will need to rollback your entity's values back to what they originally were.
In your DbContext class, you can add a method called Rollback, it'll look something like this:
public class MyDbContext : DbContext { //DataSets and what not. //... public void Rollback() { //Get all entities var entries = this.ChangeTracker.Entries().ToList(); var changed = entries.Where(x => x.State != EntityState.Unchanged).ToList(); var modified = changed.Where(x => x.State == EntityState.Modified).ToList(); var added = changed.Where(x => x.State == EntityState.Added).ToList(); var deleted = changed.Where(x => x.State == EntityState.Deleted).ToList(); //Reset values for modified entries foreach (var entry in modified) { entry.CurrentValues.SetValues(entry.OriginalValues); entry.State = EntityState.Unchanged; } //Remove any added entries foreach (var entry in added) entry.State = EntityState.Detached; //Undo any deleted entries foreach (var entry in deleted) entry.State = EntityState.Unchanged; } } You can simply call this method in your catch:
try { dataEntities.SaveChanges(); } catch (Exception oops) { //Rollback all changes dataEntities.Rollback(); } Note that INotifyPropertyChanged will need to be implemented on properties that are bound to the view, this will ensure that any changes that the rollback performs will be pushed back to the view.
How large of a deployment is this? It might be better to execute the deployment of .net 3.5 as a previous enterprise deployment. And then follow up with your application. For enterprise wide deployments there are tools like Zenworks, and others that deploy applications and other file sets "invisibly" to the user.
Have you confirmed that your application will not function with .net 2.0?
If your application is only files, and does not have registry settings, etc. you may be able to copy the files to the users' computers, and copy a shortcut to their desktop, or startmenu certainly without their intervention, and probably with out their knowledge. If you have admin level credentials that apply to all your PCs and can get a list of all you r PCs' network names, you could "push" the files out through the C$ share, or if they log in to a domain you can have them "pull" them via a login-script.
There are actually lots of ways to do this. If you have server admins, they can help you with this.
-30567208 0 C# How to Determine if Netwokr Path Exists w/o new ProcessI want to check if a certain network drive is accessible and exit my addin if not. It's an Outlook 2013 addin in VSTO. Anyway, I would like to search for it by UNC if possible as \192.168.0.2\WAN\ or I could use the drive letter as a last last resort, but not everyone uses the same letter for that drive in our company.
Anyway if I do Directory.Exists("path with correct drive letter"); it hangs. I want to just see if its there or not.
Can someone provide assistance and also give me a small example?
Oh and by the way, there is an answer where a process is spawned to do net use. I wanted to do it without spawning a new process wanted to know if it was possible.
Thanks a ton
-40632194 0Within the standard language, the approach was typically to set aside storage in an array that was larger than likely needed, but still within the constraints of the platform running the program, then manually parcel that storage out as required. The language had features, such as sequence association, storage association, and adjustable arrays, that helped with this parcelling.
Use of language extensions for dynamic memory management was also common.
The capabilities of Fortran 77 and earlier need to be considered in the context of the capabilities of the platforms of the time.
-18915280 0 Consequences of including an external script file in a GTM tagIn GTM, lets say that I have a "custom HTML" tag, and in it include an external script file like
<script type="text/javascript" src="http://externalsite.com/file.js"></script>
How is this file loaded? Does it affect the loading time of the page?
I know that the GTM script is loaded asynchronously along with the tags, but I can't really imagine what happens in this case.
-2028626 0No, an iPhone application can only change stuff within its own little sandbox. (And even there there are things that you can't change on the fly.)
Your best bet is probably to use the servers IP address rather than hostname. Slightly harder, but not that hard if you just need to resolve a single address, would be to put a DNS server on your Mac and configure your iPhone to use that.
-7780691 0this.x and this.y are functional from the scope of your checkers pieces object; however, if you're accessing a piece outside of their scope, you must use a piece's instance name. Although not optimal, you could loop through children DisplayObjects.
// create a collection of your checker pieces var checkers:Array = []; // create a checker piece, whatever your DisplayObject class is. var checker:Checker; checkers.push(checker); // add it to the stage, probably your game board addChild(checker); checker.x = 100; checker.y = 100; // loop through the children (from your game board) for (var i:uint = 0; i < numChildren; i++) { var checker:DisplayObject = getChildAt(i); trace(checker.x); trace(checker.y); } Using coordinates to reference a piece may not be optimal for game play. You might want to consider a row / column or approach it from how your game board works.
If this is not clear, you should specify some code or expand your question with more detail.
-11385801 0 Sort by Double Value and not String ValueI'm currently pulling info from an sql DB where the 'cachedDist' column is set as a double. However when I pull it into my app and create my array I turn it into an String and the sort will obviously be off, 18.15 will come before 2.15. How do I fix that in my code so it will sort distance as a Double and not a String?
In Bar object.
NSString *cachedDist @property(nonatomic,copy) NSString *cachedDist; @synthesize cachedDist; My while loop in the View Controller.
while (sqlite3_step(sqlStatement)==SQLITE_ROW) { Bar * bar = [[Bar alloc] init]; bar.barName = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)]; bar.barAddress = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)]; bar.barCity = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 3)]; bar.barState = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 4)]; bar.barZip = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 5)]; bar.barLat = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 8)]; bar.barLong = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 9)]; if (currentLoc == nil) { NSLog(@"current location is nil %@", currentLoc); }else{ CLLocation *barLocation = [[CLLocation alloc] initWithLatitude:[bar.barLat doubleValue] longitude:[bar.barLong doubleValue]]; bar.cachedDist = [NSNumber numberWithDouble:[currentLoc distanceFromLocation: barLocation]/1000]; [thebars addObject:bar]; } My sorting
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"cachedDist" ascending:YES]; sortedArray = [thebars sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]]; return sortedArray;
-11958008 0 Do you mean words or characters? If you want to count words, a very naïve approach is splitting by whitespace and check the length of the resulting array:
if ($("#et_newpost_content").text().split(/\s+/).length < 250) { alert('Message must be at least 250 words.') } If you mean characters, then it's much easier:
if ($("#et_newpost_content").text().length < 250) { alert('Message must be at least 250 characters.') }
-37804485 0 Check below code and comment:
import java.util.Arrays; public class SortString { public static void main(String[] args) { String str = "11,22,13,31,21,12"; StringBuffer strB = new StringBuffer(); String[] arr = str.split(","); // Split string save in array Arrays.sort(arr); // sort array for (int i = 0; i < arr.length; i++) { //add array in stringbuffer if (i != arr.length - 1) { strB.append(arr[i] + ","); } else { strB.append(arr[i]); } } String str2 = strB.toString(); System.out.println(str2); } }
-14295380 0 SmartGWT has extensive built-in support for Selenium. Read about it here:
http://www.smartclient.com/smartgwtee-latest/javadoc/com/smartgwt/client/docs/UsingSelenium.html
Do not attempt to set your own DOM identifiers. This is unnecessary, and is the wrong approach.
-35769329 0 Replace month number with month name using current phone formatI'm using joda-time to process DateTime. I got date format of phone using this:
SimpleDateFormat dateFormat = (SimpleDateFormat) DateFormat.getDateFormat(context); String datePattern = dateFormat.toPattern(); And then I format a DateTime to String using this:
DateTimeFormatter dateFormatter = DateTimeFormat.forPattern(datePattern); dateFormatter.print(dateTime) Example, it will show DateTime as String:
3/1/2016
But i want it displays:
March/1/2016
or
Mar/1/2016
How can i do that?
-16019599 0@Saurabh Nanda: Similar to what you posted, you can also create a simple function to convert your varchar array to lowercase as follows:
CREATE OR REPLACE FUNCTION array_lowercase(varchar[]) RETURNS varchar[] AS $BODY$ SELECT array_agg(q.tag) FROM ( SELECT btrim(lower(unnest($1)))::varchar AS tag ) AS q; $BODY$ language sql IMMUTABLE; Note that I'm also trimming the tags of spaces. This might not be necessary for you but I usually do for consistency.
Testing:
SELECT array_lowercase(array['Hello','WOrLD']); array_lowercase ----------------- {hello,world} (1 row) As noted by Saurabh, you can then create a GIN index:
CREATE INDEX ix_tags ON tagtable USING GIN(array_lowercase(tags)); And query:
SELECT * FROM tagtable WHERE ARRAY['mytag'::varchar] && array_lowercase(tags); UPDATE: Performance of WHILE vs array_agg/unnest
I created table of 100K 10 element text[] arrays (12 character random mixed case strings) and tested each function.
The array_agg/unnest function returned:
EXPLAIN ANALYZE VERBOSE SELECT array_lowercase(data) FROM test; QUERY PLAN ------------------------------------------------------------------------------------------------------------------------ Seq Scan on public.test (cost=0.00..28703.00 rows=100000 width=184) (actual time=0.320..3041.292 rows=100000 loops=1) Output: array_lowercase((data)::character varying[]) Total runtime: 3174.690 ms (3 rows) The WHILE function returned:
EXPLAIN ANALYZE VERBOSE SELECT array_lowercase_while(data) FROM test; QUERY PLAN ------------------------------------------------------------------------------------------------------------------------ Seq Scan on public.test (cost=0.00..28703.00 rows=100000 width=184) (actual time=5.128..4356.647 rows=100000 loops=1) Output: array_lowercase_while((data)::character varying[]) Total runtime: 4485.226 ms (3 rows) UPDATE 2: FOREACH vs. WHILE As a final experiment, I changed the WHILE function to use FOREACH:
CREATE OR REPLACE FUNCTION array_lowercase_foreach(p_input varchar[]) RETURNS varchar[] AS $BODY$ DECLARE el text; r varchar[]; BEGIN FOREACH el IN ARRAY p_input LOOP r := r || btrim(lower(el))::varchar; END LOOP; RETURN r; END; $BODY$ language 'plpgsql' Results appeared to be similar to WHILE:
EXPLAIN ANALYZE VERBOSE SELECT array_lowercase_foreach(data) FROM test; QUERY PLAN ------------------------------------------------------------------------------------------------------------------------ Seq Scan on public.test (cost=0.00..28703.00 rows=100000 width=184) (actual time=0.707..4106.867 rows=100000 loops=1) Output: array_lowercase_foreach((data)::character varying[]) Total runtime: 4239.958 ms (3 rows) Though my tests are not by any means rigorous, I did run each version a number of times and found the numbers to be representative, suggesting that the SQL method (array_agg/unnest) is the fastest.
-16388764 0 How to disable function executing in bind method?I've three simple functions
var loadPoints = function(successCallback, errorCallback) { $.ajax({ method: 'get', url: '/admin/graph/get-points', dataType: 'json', success: successCallback, error: errorCallback }); } var successLoadPoints = function(points){ console.log('load ok'); //console.log(points); // $.each(points,function(i, item){ // console.log(points[i]); // // }); } var errorLoadPoints = function () { console.log('error with loading points'); } I bind function loadPoints to click event on button
$("button#viewPoints").bind( 'click', loadPoints(successLoadPoints,errorLoadPoints) ); But function loadPoints is been executed without click event. Why? How to resolve this problem ?
-33427601 0When the mouse is dragging a div element over a droppable area, pressing the ESC key should drag the element to an area that is not droppable
I´ve created a demo of a possible solution that you can check in plunker.
As stated by @ioneyed, you can select the dragged element directly using the selector .ui-draggable-dragging, which should be more efficient if you have lots of draggable elements.
The code used is the following, however, apparently it's not working in the snippet section. Use the fullscreen feature on the plunker or reproduce it locally.
var CANCELLED_CLASS = 'cancelled'; $(function() { $(".draggable").draggable({ revert: function() { // if element has the flag, remove the flag and revert the drop if (this.hasClass(CANCELLED_CLASS)) { this.removeClass(CANCELLED_CLASS); return true; } return false; } }); $("#droppable").droppable(); }); function cancelDrag(e) { if (e.keyCode != 27) return; // ESC = 27 $('.draggable') // get all draggable elements .filter('.ui-draggable-dragging') // filter to remove the ones not being dragged .addClass(CANCELLED_CLASS) // flag the element for a revert .trigger('mouseup'); // trigger the mouseup to emulate the drop & force the revert } $(document).on('keyup', cancelDrag); .draggable { padding: 10px; margin: 10px; display: inline-block; } #droppable { padding: 25px; margin: 10px; display: inline-block; } <div id="droppable" class="ui-widget-header"> <p>droppable</p> </div> <div class="ui-widget-content draggable"> <p>draggable</p> </div> <div class="ui-widget-content draggable"> <p>draggable</p> </div> <div class="ui-widget-content draggable"> <p>draggable</p> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.css"> If you want to maintain your own version of LibraryB you have a few options:
You can make LibraryB inherent part of your project: just remove or comment out [remote "LibraryB"] section in the config file, and make changes to LibraryB inside your project.
The disadvantage is that it would be harder to send patches for canonical (third-party) version of LibraryB
You can continue using 'subtree' merge, but not from the canonical version of LibraryB, but from your own clone (fork) of this library. You would change remote.LibraryB.url to point to your local version, and your local version would be clone of original LibraryB. Note that you should merge your own branch, and not remote-tracking branch of canonical LibraryB.
The disadvantage is that you have to maintain separate clone, and to remember that your own changes (well, at least those generic) to LibraryB have to be made in the fork of LibraryB, and not directly inside ProjectA.
You might want to move from 'subtree' merge which interweaves history of ProjectA and LibraryB, to having more separation that can be achieved using submodule (tutorial). In this case you would have separate repository (fork) of LibraryB, but it would be inside working area of ProjectA; the commit in ProjectA would have instead of having tree of LibraryB as subtree, pointer to commit in LibraryB repository. Then if you do not want to follow LibraryB development, it would be enough to simply not use 'git submodule update' (and perhaps just in case comment out or remove link to canonical version of LibraryB).
This has the advantage of making it easy to send your improvements to canonical LibraryB, and the advantage that you make changes inside working area of ProjectA. It has disadvantage of having to learn slightly different workflow.
Additionally there is also an issue of how to go from 'subtree' merge to submodules. You can either:
I hope that this version solve your problem.
Disclaimer: I have used neither subtree merge, nor submodules, nor git-filter-branch personally.
-28823526 0 How to debug android studio gradle files and tasks?I've leveraged TWiStErRob's solution to auto-increment android versionNumber and I have expanded on this to add more capability, however lately when I add the "apply from" statement in my build.gradle to include the auto-version.gradle file and let Gradle sync, my build.gradle gets inexplicably corrupted and loses all formatting using Android Studio 1.1.
Is there any way to debug or step through gradle scripts in Android studio?
-15561669 0 Placing multiple Divs (side by side) within a parent DivMy goal is to place four divs within a single "container" div. Here's my code so far:
HTML
<body> <div id="navBar"> <div id="subDiv1"> </div> <div id="subDiv2"> </div> <div id="subDiv3"> </div> <div id="subDiv4"> </div> </div> </body> CSS
#navBar { width: 75%; height: 75px; margin-left: 25%; margin-right: auto; margin-top: 2%; border-width: 1px; border-style: solid; border-radius: 10px; border-color: #008040; overflow: hidden; } #subDiv1, #subDiv2, #subDiv3, #subDiv4 { width: 25%; height: 75px; border-width: 1px; border-color: #000; border-style: solid; } #subDiv1 { border-top-left-radius: 10px; border-bottom-left-radius: 10px; float: left; margin-left: 0%; } #subDiv2 { float: left; margin-left: 25%; } #subDiv3 { float: left; margin-left: 50%; } #subDiv4 { border-top-right-radius: 10px; border-bottom-right-radius: 10px; float: left; margin-left: 75%; } As far as I know this is the only part of my code that's relevant to my question so I left some other parts out.. Don't mind the width and margin of the navBar, because it's actually within another container as well.
P.S I searched Google and StackOverFlow and I could not find an answer that was helpful. There were many questions about placing two divs within a single div, but none for aligning multiple divs within a single div.
Thanks for any help in advance!
-21055710 0 What is the difference between JavaFX scripting and Using Regular java Syntax while programming JavaFX ApplicationsI am looking for a detail explanation to the following question.
Can I use regular java syntax to develop JavaFX application? And if so why is the JavaFX scripting so important?
-7592838 0 Correct way to get beans from applicationContext SpringI have a factory that creates instances:
public class myFactory { public static getInstace() { switch(someInt) { case 1: return new MySpringBean(); case 2: return new MyOtherSpringBean(); } } } I need to return a new instance of the beans that are "managed" by Spring bc they have Transactional business logic methods. I have read in many posts here that I should not use getBean method to get a singleton or a new instance from the applicationContext. But I cannot find the proper way to do it for my case. I have used @Resource and it seems to work but it doesn't support static fields. Thanx
-7777487 0If the file is not opened, the line file = open(filePath, 'w') fails, so nothing gets assigned to file.
Then, the except clause runs, but nothing is in file, so file.close() fails.
The finally clause always runs, even if there was an exception. And since file is still None you get another exception.
You want an else clause instead of finally for things that only happen if there was no exception.
try: file = open(filePath, 'w') except IOError: msg = "Unable to create file on disk." return else: file.write("Hello World!") file.close() Why the else? The Python docs say:
The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try ... except statement.
In other words, this won't catch an IOError from the write or close calls. Which is good, because then reason woudn't have been “Unable to create file on disk.” – it would have been a different error, one that your code wasn't prepared for. It's a good idea not to try to handle such errors.
Basically:
#info is used to discover information about a XMPP entity.#item is used to discover items associated with a XMPP entity.#info query results will show you amongst others the supported features of a XMPP entity (e.g. XHTML-IM support).
#item query results will show the available items of a XMPP entity. For example the XEP-0045 MUC component of a XMPP service. But any other available service/component could show up here.
One could also say that #info is used to query the features of this particular entity, while #items is used to query for "sub-components" of that entity, which itself are usually be queried with #info for their features.
One of the ways to do this could be create "anchor" table from all possible data from all three tables and then use left outer join:
select A.column2, B.column2, C.column2 from ( select distinct month from table1 union select distinct month from table2 union select distinct month from table3 ) as X left outer join table1 as A on A.month = X.month left outer join table2 as B on B.month = X.month left outer join table3 as C on C.month = X.month
-21263350 0 On Heroku, gems are installed within the vendor/bundle/ruby/<version>/gems directory. I just checked my Heroku instance and confirmed this.
I'm using PHP Simple HTML DOM Parser to scrape some data of a webshop (also running XAMPP 1.7.2 with PHP5.3.0), and I'm running into problems with <tbody> tag. The structure of the table is, essentialy (details aren't really that important):
<table> <thead> <!--text here--> </thead> <tbody> <!--text here--> </tbody> </table> Now, I'm trying to get to the <tbody> section by using code:
$element = $html->find('tbody',0)->innertext; It doesn't throw any errors, it just prints nothing out when I try to echo it. I've tested the code on other elements, <thead>, <table>, even something like <span class="price"> and they all work fine (ofcourse, removing ",0" fails the code). They all give their correct sections. Outertext ditto. But it all fails on <tbody>.
Now, I've skimmed through the Parser, but I'm not sure I can figure it out. I've noticed that <thead> isn't even mentioned, but it works fine. shrug
I guess I could try and do child navigation, but that seems to glitch as well. I've just tried running:
$el = $html->find('table',0); $el2 = $el->children(2); echo $el2->outertext; and no dice. Tried replacing children with first_child and 2 with 1, and still no dice. Funny, though, if I try ->find instead of children, it works perfectly.
I'm pretty confident I could find a work-around the whole thing, but this behaviour seems odd enough to post here. My curious mind is happy for all the help it can get.
-40341145 0 Can run_loop use a different identifier for resigning DeviceAgent-Runner.appSetup:
First I tried to start the calabash console on the physical phone, but because it didn't have the DeviceAgent-Runner.app app it tried to install it.
calabash-ios 0.20.3> start_test_server_in_background EXEC: xcrun simctl list devices --json EXEC: xcrun instruments -s devices DEBUG: HTTP: get http://10.57.39.140:27753/1.0/health {:retries=>1, :timeout=>0.5} DEBUG: Waiting for DeviceAgent to launch... EXEC: cd /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent EXEC: ditto -xk Frameworks.zip . EXEC: ditto -xk DeviceAgent-Runner.app.zip . EXEC: /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/bin/iOSDeviceManager install --device-id e544a153544294d3a9bcce89cecb17161d528baa --app-bundle /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/ipa/DeviceAgent-Runner.app --codesign-identity iPhone Developer: name@gmail.com (P536D9MXXX) with a timeout of 60 from /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/shell.rb:104:in `run_shell_command' from /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/ios_device_manager.rb:124:in `launch' from /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/client.rb:1233:in `launch_cbx_runner' from /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/client.rb:264:in `launch' from /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/client.rb:140:in `run' from /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop.rb:113:in `run' from /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/calabash-cucumber-0.20.3/lib/calabash-cucumber/launcher.rb:408:in `block in new_run_loop' from /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/calabash-cucumber-0.20.3/lib/calabash-cucumber/launcher.rb:406:in `times' from /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/calabash-cucumber-0.20.3/lib/calabash-cucumber/launcher.rb:406:in `new_run_loop' from /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/calabash-cucumber-0.20.3/lib/calabash-cucumber/launcher.rb:365:in `relaunch' from /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/calabash-cucumber-0.20.3/lib/calabash-cucumber/core.rb:1567:in `start_test_server_in_background' from (irb):1 from /Users/stefan/.rbenv/versions/2.2.3/bin/irb:11:in `<main>' As you can see it fails to install the DeviceAgent-Runner.app app with a timeout.
Then I tried to install the DeviceAgent-Runner.app manualy
MACC02MK1XBFD59:CalabashVerification stefan$ /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/bin/iOSDeviceManager install --device-id e544a153544294d3a9bcce89cecb17161d528baa --app-bundle /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/ipa/DeviceAgent-Runner.app --codesign-identity "iPhone Developer: name@gmail.com (P536D9MXXX)" objc[47805]: Class DDLog is implemented in both /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/Frameworks/FBControlCore.framework/Versions/A/Frameworks/CocoaLumberjack.framework/Versions/A/CocoaLumberjack and /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/bin/iOSDeviceManager. One of the two will be used. Which one is undefined. objc[47805]: Class DDLoggerNode is implemented in both /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/Frameworks/FBControlCore.framework/Versions/A/Frameworks/CocoaLumberjack.framework/Versions/A/CocoaLumberjack and /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/bin/iOSDeviceManager. One of the two will be used. Which one is undefined. objc[47805]: Class DDLogMessage is implemented in both /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/Frameworks/FBControlCore.framework/Versions/A/Frameworks/CocoaLumberjack.framework/Versions/A/CocoaLumberjack and /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/bin/iOSDeviceManager. One of the two will be used. Which one is undefined. objc[47805]: Class DDAbstractLogger is implemented in both /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/Frameworks/FBControlCore.framework/Versions/A/Frameworks/CocoaLumberjack.framework/Versions/A/CocoaLumberjack and /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/bin/iOSDeviceManager. One of the two will be used. Which one is undefined. objc[47805]: Class DDAbstractDatabaseLogger is implemented in both /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/Frameworks/FBControlCore.framework/Versions/A/Frameworks/CocoaLumberjack.framework/Versions/A/CocoaLumberjack and /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/bin/iOSDeviceManager. One of the two will be used. Which one is undefined. objc[47805]: Class DDTTYLogger is implemented in both /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/Frameworks/FBControlCore.framework/Versions/A/Frameworks/CocoaLumberjack.framework/Versions/A/CocoaLumberjack and /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/bin/iOSDeviceManager. One of the two will be used. Which one is undefined. objc[47805]: Class DDTTYLoggerColorProfile is implemented in both /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/Frameworks/FBControlCore.framework/Versions/A/Frameworks/CocoaLumberjack.framework/Versions/A/CocoaLumberjack and /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/bin/iOSDeviceManager. One of the two will be used. Which one is undefined. objc[47805]: Class DDLogFileManagerDefault is implemented in both /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/Frameworks/FBControlCore.framework/Versions/A/Frameworks/CocoaLumberjack.framework/Versions/A/CocoaLumberjack and /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/bin/iOSDeviceManager. One of the two will be used. Which one is undefined. objc[47805]: Class DDLogFileFormatterDefault is implemented in both /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/Frameworks/FBControlCore.framework/Versions/A/Frameworks/CocoaLumberjack.framework/Versions/A/CocoaLumberjack and /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/bin/iOSDeviceManager. One of the two will be used. Which one is undefined. objc[47805]: Class DDFileLogger is implemented in both /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/Frameworks/FBControlCore.framework/Versions/A/Frameworks/CocoaLumberjack.framework/Versions/A/CocoaLumberjack and /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/bin/iOSDeviceManager. One of the two will be used. Which one is undefined. objc[47805]: Class DDLogFileInfo is implemented in both /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/Frameworks/FBControlCore.framework/Versions/A/Frameworks/CocoaLumberjack.framework/Versions/A/CocoaLumberjack and /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/bin/iOSDeviceManager. One of the two will be used. Which one is undefined. objc[47805]: Class DDASLLogger is implemented in both /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/Frameworks/FBControlCore.framework/Versions/A/Frameworks/CocoaLumberjack.framework/Versions/A/CocoaLumberjack and /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/bin/iOSDeviceManager. One of the two will be used. Which one is undefined. 2016-10-31 12:09:12.495 iOSDeviceManager[47805:7626359] [MT] DVTPlugInManager: Required plug-in compatibility UUID DA4FDFD8-C509-4D8B-8B55-84A7B66AE701 for KSImageNamed.ideplugin (com.ksuther.KSImageNamed) not present 2016-10-31 12:09:12.638 iOSDeviceManager[47805:7626359] [MT] PluginLoading: Required plug-in compatibility UUID DA4FDFD8-C509-4D8B-8B55-84A7B66AE701 for plug-in at path '~/Library/Application Support/Developer/Shared/Xcode/Plug-ins/xcfui.xcplugin' not present in DVTPlugInCompatibilityUUIDs 2016-10-31 12:09:12.639 iOSDeviceManager[47805:7626359] [MT] PluginLoading: Required plug-in compatibility UUID DA4FDFD8-C509-4D8B-8B55-84A7B66AE701 for plug-in at path '~/Library/Application Support/Developer/Shared/Xcode/Plug-ins/RTImageAssets.xcplugin' not present in DVTPlugInCompatibilityUUIDs 2016-10-31 12:09:12.639 iOSDeviceManager[47805:7626359] [MT] PluginLoading: Required plug-in compatibility UUID DA4FDFD8-C509-4D8B-8B55-84A7B66AE701 for plug-in at path '~/Library/Application Support/Developer/Shared/Xcode/Plug-ins/PrettyPrintJSON.xcplugin' not present in DVTPlugInCompatibilityUUIDs 2016-10-31 12:09:12.640 iOSDeviceManager[47805:7626359] [MT] PluginLoading: Required plug-in compatibility UUID DA4FDFD8-C509-4D8B-8B55-84A7B66AE701 for plug-in at path '~/Library/Application Support/Developer/Shared/Xcode/Plug-ins/OMColorSense.xcplugin' not present in DVTPlugInCompatibilityUUIDs 2016-10-31 12:09:12.640 iOSDeviceManager[47805:7626359] [MT] PluginLoading: Required plug-in compatibility UUID DA4FDFD8-C509-4D8B-8B55-84A7B66AE701 for plug-in at path '~/Library/Application Support/Developer/Shared/Xcode/Plug-ins/KSImageNamed.xcplugin' not present in DVTPlugInCompatibilityUUIDs 2016-10-31 12:09:12.641 iOSDeviceManager[47805:7626359] [MT] PluginLoading: Required plug-in compatibility UUID DA4FDFD8-C509-4D8B-8B55-84A7B66AE701 for plug-in at path '~/Library/Application Support/Developer/Shared/Xcode/Plug-ins/DebugSearch.xcplugin' not present in DVTPlugInCompatibilityUUIDs 2016-10-31 12:09:12.641 iOSDeviceManager[47805:7626359] [MT] PluginLoading: Required plug-in compatibility UUID DA4FDFD8-C509-4D8B-8B55-84A7B66AE701 for plug-in at path '~/Library/Application Support/Developer/Shared/Xcode/Plug-ins/CocoaPods.xcplugin' not present in DVTPlugInCompatibilityUUIDs 2016-10-31 12:09:12.642 iOSDeviceManager[47805:7626359] [MT] PluginLoading: Required plug-in compatibility UUID DA4FDFD8-C509-4D8B-8B55-84A7B66AE701 for plug-in at path '~/Library/Application Support/Developer/Shared/Xcode/Plug-ins/Alcatraz.xcplugin' not present in DVTPlugInCompatibilityUUIDs 2016-10-31 12:09:20.201 iOSDeviceManager[47805:7626359] EXEC: /usr/bin/xcrun security find-identity -v -p codesigning 2016-10-31 12:09:50.203 iOSDeviceManager[47805:7626359] Could not find valid codesign identities with: /usr/bin/xcrun security find-identity -v -p codesigning 2016-10-31 12:09:50.203 iOSDeviceManager[47805:7626359] Command timed out after 30.0009800195694 seconds 2016-10-31 12:09:50.203 iOSDeviceManager[47805:7626359] ERROR: The signing identity you provided is not valid: iPhone Developer: name@gmail.com (P536D9MXXX) 2016-10-31 12:09:50.203 iOSDeviceManager[47805:7626359] ERROR: 2016-10-31 12:09:50.203 iOSDeviceManager[47805:7626359] ERROR: These are the valid signing identities that are available: 2016-10-31 12:09:50.203 iOSDeviceManager[47805:7626359] EXEC: /usr/bin/xcrun security find-identity -v -p codesigning 2016-10-31 12:10:20.204 iOSDeviceManager[47805:7626359] Could not find valid codesign identities with: /usr/bin/xcrun security find-identity -v -p codesigning 2016-10-31 12:10:20.204 iOSDeviceManager[47805:7626359] Command timed out after 30.00082302093506 seconds 2016-10-31 12:10:20.206 iOSDeviceManager[47805:7626359] Error creating product bundle for /var/folders/yy/vvrqrp2n6qv9b_tbssf_74n80000gn/T/59E25CB1-38F5-4269-B950-0040BACB2E00-47805-000048155108503C/DeviceAgent-Runner.app: Error Domain=com.facebook.XCTestBootstrap Code=0 "Failed to codesign /var/folders/yy/vvrqrp2n6qv9b_tbssf_74n80000gn/T/59E25CB1-38F5-4269-B950-0040BACB2E00-47805-000048155108503C/DeviceAgent-Runner.app" UserInfo={NSLocalizedDescription=Failed to codesign /var/folders/yy/vvrqrp2n6qv9b_tbssf_74n80000gn/T/59E25CB1-38F5-4269-B950-0040BACB2E00-47805-000048155108503C/DeviceAgent-Runner.app, NSUnderlyingError=0x7fbfef6127f0 {Error Domain=sh.calaba.iOSDeviceManger Code=5 "Could not resign with the given arguments" UserInfo={NSLocalizedDescription=Could not resign with the given arguments, NSLocalizedFailureReason=The device UDID and code signing identity were invalid forsome reason. Please check the logs.}}} install -u,--update-app <true-or-false> [OPTIONAL] When true, will reinstall the app if the device contains an older version than the bundle specified DEFAULT=1 -c,--codesign-identity <codesign-identity> [OPTIONAL] Identity used to codesign app bundle [device only] DEFAULT= -a,--app-bundle <path/to/app-bundle.app> Path .app bundle (for .ipas, unzip and look inside of 'Payload') -d,--device-id <device-identifier> iOS Simulator GUID or 40-digit physical device ID Which gave me at least some more info, as it said it is related to code singing. I am sure that my certificats are valid. So my open questions:
Or any other ideas how to continue from this point
Thanks!
The php code you show (which really just sends the work to convert in a shell) does not check to see if the images have alpha channels, it just takes whatever file is given and turns it on. If it already had one there would be no file change, but convert is not being asked to make any decision based on the status, just go ahead and add the channel.
-24952969 0 RadEditor is not working in IE11I am working on Telerik RadEditor control but it is not working in IE11 although it is working fine in IE8. Below tag, I am using to work with IE9 and IE10 and It works
meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" /> But, When I use IE11 then RadEditor is not showing in proper format.
Namespace="Telerik.WebControls" Assembly="RadEditor.Net2" Can someone tell me, what is the problem with IE11
Hello i am trying to build my first app with react-native. I am following this 2 tutorial: https://facebook.github.io/react-native/docs/getting-started.html#content https://facebook.github.io/react-native/docs/android-setup.html I am sure that i installed all the required things in the second link and when i try running my app with "react-native run-android" I get the following error: 
I executed this command while I am running genymotion. This is all that i have installed in android sdk.
I tried to install Android build tools 23.0.1 but i get this: 
Any help or advice I would be very grateful Thanks!
-145227 0In my opinion, almost any release number scheme can be made to work more or less sanely. The system I work on uses version numbers such as 11.50.UC3, where the U indicates 32-bit Unix, and the C3 is a minor revision (fix pack) number; other letters are used for other platform types. (I'd not recommend this scheme, but it works.)
There are a few golden rules which have not so far been stated, but which are implicit in what people have discussed.
Now, in practice, people do have to release fixes for older versions while newer versions are available -- see GCC, for example:
So, you have to build your version numbering scheme carefully.
One other point which I firmly believe in:
With SVN, you could use the SVN version number - but probably wouldn't as it changes too unpredictably.
For the stuff I work with, the version number is a purely political decision.
Incidentally, I know of software that went through releases from version 1.00 through 9.53, but that then changed to 2.80. That was a gross mistake - dictated by marketing. Granted, version 4.x of the software is/was obsolete, so it didn't immediately make for confusion, but version 5.x of the software is still in use and sold, and the revisions have already reached 3.50. I'm very worried about what my code that has to work with both the 5.x (old style) and 5.x (new style) is going to do when the inevitable conflict occurs. I guess I have to hope that they will dilly-dally on changing to 5.x until the old 5.x really is dead -- but I'm not optimistic. I also use an artificial version number, such as 9.60, to represent the 3.50 code, so that I can do sane if VERSION > 900 testing, rather than having to do: if (VERSION >= 900 || (VERSION >= 280 && VERSION < 400), where I represent version 9.00 by 900. And then there's the significant change introduced in version 3.00.xC3 -- my scheme fails to detect changes at the minor release level...grumble...grumble...
NB: Eric Raymond provides Software Release Practice HOWTO including the (linked) section on naming (numbering) releases.
-7498755 0Try cleaning the project. Also, are you using the google libraries for maps? You need to add a link to Google API.
-30202774 1 Python - remove parts of a stringI have many fill-in-the-blank sentences in strings,
e.g. "6d) We took no [pains] to hide it ."
How can I efficiently parse this string (in Python) to be
"We took no to hide it"? I also would like to be able to store the word in brackets (e.g. "pains") in a list for use later. I think the regex module could be better than Python string operations like split().
-21879242 0The unique event count for an action is the number of visits in which that action took place.
The total unique events in this report should equal the sum of unique events on all rows, not the number of rows. This is because a unique event is based on unique action-visit combinations, and each row has a different action.
In other words, if an action is repeated within a visit, the unique event count is not incremented, but otherwise it is.
So if one of the rows has 2 unique events that would mean that the event action was triggered in 2 separate visits, and both these visits would be included in the overall unique events.
In your example, the first 10 actions in your report only occurred for 1 visit each (they may even have all been the same visit - you can't tell from this report).
So I'm guessing that on the second page of your example there are two rows with 0 unique events, and the rest have 1 unique event - so that they add up to 21 unique events.
-29399590 0Yes, you can do this, but it needs to be done through a separate mechanism than the c argument. In a nutshell, use facecolors=rgb_array.
First off, let me explain what's going on. The Collection that scatter returns has two "systems" (for lack of a better term) for setting colors.
If you use the c argument, you're setting the colors through the ScalarMappable "system". This specifies that the colors should be controlled by applying a colormap to a single variable. (This is the set_array method of anything that inherits from ScalarMappable.)
In addition to the ScalarMappable system, the colors of a collection can be set independently. In that case, you'd use the facecolors kwarg.
As a quick example, these points will have randomly specified rgb colors:
import matplotlib.pyplot as plt import numpy as np x, y = np.random.random((2, 10)) rgb = np.random.random((10, 3)) fig, ax = plt.subplots() ax.scatter(x, y, s=200, facecolors=rgb) plt.show() 
struct C { A a; B b; C(double ta[2], vector<double> tb) { a = A(ta[0],ta[1]); // or a.x = ta[0]; a.y = ta[1] b = tb; } }; then you can initialize with something like
C c = C( {0.0, 0.1} , vector<double> bb(0.0,5) );
-10089327 0 One method may be to select the appropiate column range using the Visual mode (control+v)
Once selected, the search and replace can be done using (see this question)
%s/\%Vfoo/bar/g A regular expression for not test can be found here: Regular expression to match string not containing a word?
-16821194 0This could happen when the Selenium Server version that you have does not support the Firefox browser version. Try using a stable compatible combination of Firefox Browser and Selenium Server.
-2055364 0getText() is returning null, so you're writing "null" down to the server. At least, that's what I found after changing your just enough to get it to compile and run.
After changing getText() to return "hello" I got:
Server:
Server is starting... Server is listening... Client Connected... Client:
java.io.BufferedReader@7d2152e6 Text received: hello (The "BufferedReader@7d..." line is due to System.out.println(is);)
Note that after the client has disconnected, your server is going to keep trying to send "null" back to it, because you don't test for line being null in the server code.
You can implement an interface (say Printable) and use that interface as parameter type in your static method.
{ "C:\\workspace\\folder\\test\\added.txt": "synced", "C:\\workspace\\folder\\test\\pending.test": "pending" } Your JSON needs those backslashes escaped. Notice the \\
-22157411 0 Javascript drop list with imagesI found this on one of the subjects: http://jsfiddle.net/GHzfD/357/ I would like to ask how to alert(path) after choose the image from drop list.
<script> $("body select").msDropDown(); alert(???) </script>
-23975299 0 Thanks for the responses. Very helpful. I decided to go with a proxy approach for which I found a simple solution here: http://www.paulund.co.uk/make-cross-domain-ajax-calls-with-jquery-and-php
For cut and paste simplicity I've added my code here.
I created a file called crossdomain.html. Included jquery library. Created the following Javascript function:
function requestDataByProxy() { var url = "http://UrlYouWantToAcccess.html"; var data = "url=" + url + "¶meters=1¶=2"; $.ajax({ url: "our_domain_url.php", data: data, type: "POST", success: function(data, textStatus, jqXHR){ console.log('Success ' + data); $('#jsonData').html(data); }, error: function (jqXHR, textStatus, errorThrown){ console.log('Error ' + jqXHR); } }); } I also added a simple button and pre tag in HTML to load results:
<button onclick="requestDataByProxy()">Request Data By Proxy</button> <h3>Requsted Data</h3> <pre id="jsonData"></pre> And then, the PHP file our_domain_url.php which uses cURL (make sure you have this enabled!)
<?php //set POST variables $url = $_POST['url']; unset($_POST['url']); $fields_string = ""; //url-ify the data for the POST foreach($_POST as $key=>$value) { $fields_string .= $key.'='.$value.'&'; } $fields_string = rtrim($fields_string,'&'); //open connection $ch = curl_init(); //set the url, number of POST vars, POST data curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_POST,count($_POST)); curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string); //execute post $result = curl_exec($ch); //close connection curl_close($ch); ?> To me, this was a fairly straight-forward solution.
Hope this helps someone else!
Rob
-19483833 0 jQuery won't fade in spanI have some trouble fading in a span after hiding it and replacing it's contents.
Here is my html before replacing it
<span id="replace_with_editor"> <a id="edit_button" class="btn btn-success" href="thread.php">Post ny tråd</a> </span> Here is my jQuery code
replace_with_editor = $('#replace_with_editor'); $('#edit_button').click(function(e) { e.preventDefault(); replace_with_editor.hide(); replace_with_editor.html('<form role="form" method="post" action="process/submit_thread.php"><div class="form-group"><label for="Title">Tittel</label><input id="thread_title" name="thread_title" type="text" class="form-control" placeholder="Skriv en tittel for tråden."></div><div class="form-group"><label for="Svar">Tråd</label><textarea id="thread_editor" name="thread_content" rows="10" class="form-control"></textarea></div><input type="hidden" value="category_id" name="category_id"><input type="hidden" value="forum_id" name="forum_id"><button type="submit" class="btn btn-success">Post tråd</button></form>'); replace_with_editor.fadeIn(2000); }); For some reason when i try this script, the new content shows up but the fadeIn() doesnt work, it shows up instant.
Any guess what i am doing wrong? Oh and the jQuery is not nested because of debugging. Any help is much appreciated.
-16350841 0Your code is somewhat confusing. Is MyTabBarController the class? It looks like mainTabVC is your instance. You should use that rather than the class, and you should change the type when you instantiate mainTabVC to MyTabBarController, instead of UITabBarController. You also don't need to get the storyboard the way you do, you can just use self.storyboard.
MyTabBarController *mainTabVC = [self.storyboard instantiateViewControllerWithIdentifier:@"mainTabVC"]; mainTabVC.managedObjectContext = self.managedObjectContext; [mainTabVC setModalPresentationStyle:UIModalPresentationFullScreen]; [self presentViewController:mainTabVC animated:NO completion:nil];
-17152024 0 Instead of looping through all your messages and calling the method that displays an alert for each of them, which results in the multiple alerts being displayed to the user, while looping, add all the 'priority' messages in an array. Then, check the number of alerts in your array and you can show one alert that reflects this information: e.g. for one message you could display the title of the message and some other information as title and message of the alertView, while, when you have multiple messages, you could have a title stating something like "You have x new messages with high priority" where x is the number of messages and some other description.
-16651721 0Since this post was made, there has been a third party tokenization service made available. Take a look at https://spreedly.com/. I'm in the market for a similar solution currently.
-17935377 0 unexpected result from regular expression of urlI am trying to match one part in a url. This url has already been processed and consists of domain name only.
For example:
The url I have now is business.time.com Now I want to get rid of the top level domain(.com). The result I want is business.time
I am using the following code:
gawk'{ match($1, /[a-zA-Z0-9\-\.]+[^(.com|.org|.edu|.gov|.mil)]/, where) print where[0] print where[1] }' test In test, there are four lines:
business.time.com mybest.try.com this.is.a.example.org this.is.another.example.edu I was expecting this :
business.time mybest.try this.is.a.example this.is.another.example However, the output is
business.t mybest.try this.is.a.examp this.is.another.examp Can anyone tell me what's wrong and what should I do?
Thanks
-34074507 0I tried using the options above but didn't work. Try this:
from statistics import mean
n = [11, 13, 15, 17, 19] print(n) print(mean(n)) worked on python 3.5
-34829930 1 Is there a way to get function parameter names, including bound-methods excluding `self`?I can use inspect.getargspec to get the parameter names of any function, including bound methods:
>>> import inspect >>> class C(object): ... def f(self, a, b): ... pass ... >>> c = C() >>> inspect.getargspec(c.f) ArgSpec(args=['self', 'a', 'b'], varargs=None, keywords=None, defaults=None) >>> However, getargspec includes self in the argument list.
Is there a universal way to get the parameter list of any function (and preferably, any callable at all), excluding self if it's a method?
EDIT: Please note, I would like a solution which would on both Python 2 and 3.
-19356791 0You want to use an unnamed form. Here is the correct syntax :
# List the forms that are in the page for form in br.forms(): print "Form name:", form.name print form # To go on the mechanize browser object must have a form selected br.select_form(nd = "form1") # works when form has a name br.form = list(br.forms())[0] # use when form is unnamed Python for beginners has a great cheat sheet about mechanize : http://www.pythonforbeginners.com/cheatsheet/python-mechanize-cheat-sheet/
-33618760 0You can't access data asset files in the same way you access a random file using NSBundle.pathForResource. Since they can only be defined within Assets.xcassets, you need to initialize a NSDataAsset instance in order to access the contents of it:
let asset = NSDataAsset(name: "Colors", bundle: NSBundle.mainBundle()) let json = try? NSJSONSerialization.JSONObjectWithData(asset!.data, options: NSJSONReadingOptions.AllowFragments) print(json) Please note that NSDataAsset class was introduced as of iOS 9.0 & macOS 10.11.
Swift3 version:
let asset = NSDataAsset(name: "Colors", bundle: Bundle.main) let json = try? JSONSerialization.jsonObject(with: asset!.data, options: JSONSerialization.ReadingOptions.allowFragments) print(json) Also, NSDataAsset is surprisingly located in UIKit/AppKit so don't forget to import the relevant framework in your code:
#if os(iOS) import UIKit #elseif os(OSX) import AppKit #endif
-338945 0 What are some reasons I might be receiving this "Symbol not defined" error in Visual Studio 2005 (screenshot included) When debugging my VS2005 project, I get the following error when I attempt to step into the function that returns the vScenarioDescriptions local variable it's struggling with...
As I continue to walk through the code and step into functions, it appears I'm getting this error other local variables as well. Any ideas?
Thanks in advance for your help!
-11232507 0Since you're using percentages for both top and margin-top, you can combine them, and simply use top: 10%.
See this demo: http://jsfiddle.net/jackwanders/DEn6r/3/
Also, if you'd like to drop the negative left margin, you can use this trick to center the div horizontally:
#inside { position: absolute; width: 300px; height: 80%; top: 10%; left: 0; right: 0; // set left and right to 0 margin: 0 auto; // set left and right margins to auto background: white; }
-21868051 0 Laravel 4 - ErrorException Undefined variable Trying to bind model to the form to call update function, but model is not found.
{{ Form::model($upload, array('url' => array('uploads/update', $upload->id), 'files' => true, 'method' => 'PATCH')) }} Controller to get edit view
public function getEdit($id) { $upload = $this->upload->find($id); if (is_null($upload)) { return Redirect::to('uploads/alluploads'); } $this->layout->content = View::make('uploads.edit', compact('uploads')); } Controller to do the update
public function patchUpdate($id) { $input = array_except(Input::all(), '_method'); $v = Validator::make($input, Upload::$rules); if ($v->passes()) { $upload = $this->upload->find($id); $upload->update($input); return Redirect::to('uploads/show', $id); } return Redirect::to('uploads/edit', $id) ->withInput() ->withErrors($v) } error i get
ErrorException Undefined variable: upload (View: /www/authtest/app/views/uploads/edit.blade.php)
-39179728 0 uib-accordion-group provides you with a parameter is-open. You can just feed in a truthy value for newly created elements and they will be automatically opened.
See the documentation for reference: https://angular-ui.github.io/bootstrap/#/accordion
-29850405 0There is the bool function in Data.Bool:
import Data.Bool bool b a (x == y)
-5180846 0 This looks like a case of reference versus value comparison. If you have two different instances of objects with the same property values, by default they will never be 'equal' using default comparisons. You have to compare the values of the objects. Try writing code to compare the values of each instance.
-15739734 0You can use javascript's substr() and .lastIndexOf():
var url = '/Home/LoadData?page=2&activeTab=House'; // window.location.href; var activeTab = url.substr(url.lastIndexOf('=')+1); // outputs House I understand that to work on opera versions > 12.X, Operachromiumdriver has been developed. At the same time I couldn't get this to work. I downloaded the windows version of operachromiumdriver.exe from https://github.com/operasoftware/operachromiumdriver/releases but to no avail. Can someone help me with this . Please tell me if my understanding is right.
Thanks
-40363669 0 Contextual type 'AnyObject' cannot be used with dictionary literal multi level dictionaryI'm running into an issue with creating a multi-level dictionary in Swift and have followed some of the suggestions presented here:
var userDict:[String:AnyObject]? = ["SystemId": "TestCompany", "UserDetails" : ["firstName": userDetail.name, "userAddress" : "addressLine1" userDetail.userAdd1]] The use of [String:AnyObject]? works for the first level of the Dict, but Swift is throwing the same error at the next level Dict, UserDetail[]. Any suggestions would be greatly appreciated
There is a particular line-height property for h3 tag with bootstrap.
h1, h2, h3 { line-height: 40px;//line 760 } So you will have to add style to negotiate this additional height.
Also another set for your ul as :
ul, ol { margin: 0 0 10px 25px; //line 812 } Solution :
Over-ride the ul margin as follows :
.pull-right ul{ margin: 0; } Over-ride the line-height for the h3 as follows :
.pull-left h3{ line-height:20px; } First one is pretty straight forward and gives you correct alignment straighaway. Second solution will need you to work some more with tweaking the negative-margins for .pull-right.
Debugging URL : http://jsbin.com/oToRixUp/1/edit?html,css,output
Hope this helps.
-31494182 0Scanner has a nextFloat() for getting floats fashion to nextInt(). Just call it in its own loop:
System.out.print("Enter " + c.length + " float values: "); for(int index1 = 0; index1 < c.length; index1++) { c[index1] = input.nextFloat(); } Unfortunately, there is no nextChar() method, so you'd have to emulate it with next(String)'s variant that accepts a pattern:
System.out.print("Enter " + b.length + " char values: "); for(int index1 = 0; index1 < b.length; index1++) { b[index1] = input.next(".").charAt(0); }
-38319615 0 can we create compact table(excel-like) from normal table using javascript? need to know that how can i form excel-like layout table from normal table.
Child node should come under parent node in next row with indentation.

Try (35 >= strlen($line) rather than (35 <= strlen($line) if you want lines 35 chars or less. Personally, I prefer to order comparisons like that the other way around, e.g. strlen($line) <= 35, which I think is more readable and avoids mistakes like the one you just made :)
I would like to move the following page
http://cliponexpress.com/customize-your-clipon.html
Into this wordpress page
http://cliponexpress.com/customizeit/
The script below changes the images when the thumbnails are clicked. it works fine on the html page, however I can't get it to work on wordpress, no matter where I place it (tried header, footer and within the page itself).
Any idea what I'm doing wrong?
Here is the script:
<script type="text/javascript"> $('a.thumbnail').click(function() { var src = $(this).attr('href'); var output = src.split('/').pop().split('.').shift(); $("#os1").val(output); $("#os1_text").text(output); if (src != $('img#lens').attr('src').replace(/\?(.*)/, '')) { $('img#lens').stop().animate({ opacity: '0' }, function() { $(this).attr('src', src + '?' + Math.floor(Math.random() * (10 * 100))); }).load(function() { $(this).stop().animate({ opacity: '1' }); }); } return false; }); $('a.thumbnail2').click(function() { var src = $(this).attr('href'); var output = src.split('/').pop().split('.').shift(); $("#os0").val(output); $("#os0_text").text(output); if (src != $('img#chassis').attr('src').replace(/\?(.*)/, '')) { $('img#chassis').stop().animate({ opacity: '0' }, function() { $(this).attr('src', src + '?' + Math.floor(Math.random() * (10 * 100))); }).load(function() { $(this).stop().animate({ opacity: '1' }); }); } return false; }); Thank you.
-26381810 0 Calculate 1 line value using 2 or more other linesI have the following query.
How this works my client sells kits. Each kit can contains 3 to 5 lines.
LINTYP = 6 - Kit Item LINTYP = 7 - Components The sequence should always be 6-7-7 where 6 represents the start of an new kit. There will always be 1 line that would contain an gross price. In the sample below there is 2 kits each containing 2 lines with an line status of 7
So what needs to happen is I need to calculate the missing GROSPRI using LINTYP 6 and deducting all my LINTYP 7 lines
eq.
Grosprice on line 1 (Product 550412) = R1 795 Grosprice on line 3 (Product 501301) = R 185 Grosprice on line 2 (Product 650412) should be R 1795-185 = R1 610 ---------------------------------------------------------------- | Invoice No| Product| Line No| Line Type| Gross Price ---------------------------------------------------------------- |SI141000008| 550412| 1000| 6| 1795.00 ---------------------------------------------------------------- |SI141000008| 650412| 2000| 7| 0.00 | This needs to be R1610 ---------------------------------------------------------------- |SI141000008| 501301| 3000| 7| 185.00 --------------------------------------------------------------- |SI141000008| 550413| 4000| 6| 1855.00 -------------------------------------------------------------- |SI141000008| 650413| 5000| 7| 0.00 | This needs to be R1670 --------------------------------------------------------------- |SI141000008| 501301| 6000| 7| 185.00 ----------------------------------------------------------------
-8436066 0 Check out clojure.contrib.repl-utils, and show in particular.
http://richhickey.github.com/clojure-contrib/repl-utils-api.html#clojure.contrib.repl-utils/show
These are utilities for you to introspect objects and classes in the REPL, but the code is a good example of how to explore classes programatically.
-6651537 0For detecting CTRL + F:
event.ctrlKey == true && event.keyCode == Keyboard.F where 'event' is of course a KeyBoardEvent.
As for the F3 question: the code you wrote will work as long as the flash application has focus. The F3 key command will then also not be routed to the browser. So what you need to do, is make sure that your application has focus when the user hits F3. How you solve this will depend on your JavaScript implementation. You could use ExternalInterface to tell the browser that the app is ready and than focus on the app. Or in Javascript you could catch the keyboard event, prevent its default behavior, and then call the function on the Flash app (again through ExternalInterface).
To get you started, here's a little JQuery snippet for preventing the default F3 behaviour:
$('body').keyup(function(event) { if (event.keyCode == '114') event.preventDefault(); }
-29208500 0 Thanks to you both, you were indeed correct Ken, I had read this similar post a lot of times, and somehow didnt understand the answer within:
Calling object methods internally in dojo
After reading what you have posted, I have somehow understood the answer linked above and now understand what my problem was! Thanks to all.
I fixed it by altering my code in the main application as follows:
var appInterface = new Interface(); on(registry.byId("graphBtn"),"click", appInterface.toggleGraphWindow); changed to:
var appInterface = new Interface(); var graphToggle = dojo.hitch(appInterface, "toggleGraphWindow"); on(registry.byId("graphBtn"),"click", graphToggle); I believe the reason for the error, was that the "this" object at runtime, was actually the "graphBtn" instead of the appInterface.
-21259556 0I believe I've come up with an alternate solution to this problem. There are certain circumstances with the other solution proposed where the label colours appear incorrect (using the system default instead of the overridden colour). This happens while scrolling the list of items.
In order to prevent this from happening, we can make use of method swizzling to fix the label colours at their source (rather than patching them after they're already created).
The UIWebSelectSinglePicker is shown (as you've stated) which implements the UIPickerViewDelegate protocol. This protocol takes care of providing the NSAttributedString instances which are shown in the picker view via the - (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component method. By swizzling the implementation with our own, we can override what the labels look like.
To do this, I defined a category on UIPickerView:
@implementation UIPickerView (LabelColourOverride) - (NSAttributedString *)overridePickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component { // Get the original title NSMutableAttributedString* title = (NSMutableAttributedString*)[self overridePickerView:pickerView attributedTitleForRow:row forComponent:component]; // Modify any attributes you like. The following changes the text colour. [title setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor]} range:NSMakeRange(0, title.length)]; // You can also conveniently change the background of the picker as well. // Multiple calls to set backgroundColor doesn't seem to slow the use of // the picker, but you could just as easily do a check before setting the // colour to see if it's needed. pickerView.backgroundColor = [UIColor yellowColor]; return title; } @end Then using method swizzling (see this answer for reference) we swap the implementations:
[Swizzle swizzleClass:NSClassFromString(@"UIWebSelectSinglePicker") method:@selector(pickerView:attributedTitleForRow:forComponent:) forClass:[UIPickerView class] method:@selector(overridePickerView:attributedTitleForRow:forComponent:)]; This is the Swizzle implementation I developed based off the link above.
@implementation Swizzle + (void)swizzleClass:(Class)originalClass method:(SEL)originalSelector forClass:(Class)overrideClass method:(SEL)overrideSelector { Method originalMethod = class_getInstanceMethod(originalClass, originalSelector); Method overrideMethod = class_getInstanceMethod(overrideClass, overrideSelector); if (class_addMethod(originalClass, originalSelector, method_getImplementation(overrideMethod), method_getTypeEncoding(overrideMethod))) { class_replaceMethod(originalClass, overrideSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)); } else { method_exchangeImplementations(originalMethod, overrideMethod); } } @end The result of this is that when a label is requested, our override function is called, which calls the original function, which conveniently happens to return us a mutable NSAttributedString that we can modify in anyway we want. We could completely replace the return value if we wanted to and just keep the text. Find the list of attributes you can change here.
This solution allows you to globally change all the Picker views in the app with a single call removing the need to register notifications for every view controller where this code is needed (or defining a base class to do the same).
-30757178 0I hit a similar issue and solved it using version 1.1.4 of google-api-php-client
Assuming the following code is used to redirect a user to the Google authentication page:
$client = new Google_Client(); $client->setAuthConfigFile('/path/to/config/file/here'); $client->setRedirectUri('https://redirect/url/here'); $client->setAccessType('offline'); //optional $client->setScopes(['profile']); //or email $auth_url = $client->createAuthUrl(); header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL)); exit(); Assuming a valid authentication code is returned to the redirect_url, the following will generate a token from the authentication code as well as provide basic profile information:
//assuming a successful authentication code is returned $authentication_code = 'code-returned-by-google'; $client = new Google_Client(); //.... configure $client object $client->authenticate($authentication_code); $token_data = $client->getAccessToken(); //get user email address $google_oauth =new Google_Service_Oauth2($client); $google_account_email = $google_oauth->userinfo->get()->email; //$google_ouath->userinfo->get()->familyName; //$google_ouath->userinfo->get()->givenName; //$google_ouath->userinfo->get()->name; However, location is not returned. New YouTube accounts don't have YouTube specific usernames
-34298113 0Download the akka for eclipse from below location
http://downloads.typesafe.com/akka/akka_2.11-2.4.1.zip?_ga=1.167921254.618585520.1450199987
extract the zip
add dependencies from the lib folder into project
-38678120 0What you are referring in Java is called anonymous inner class - you are actually declaring a one-time derived class inline.
Unfortunately Swift doesn't have this feature.
But you can consider passing a closure to the instance.
Lets say that your Card class have a var getCardFunction:
Class Card { var getCardFunction : () -> Int } Now you can pass the function you desire after initialising:
var card = Card() card.getCardFunction = { return 6 } Note: you can even have a default value for the getCardFunction function:
Class Card { var getCardFunction : () -> Int = { return 3 } }
-26670693 0 <input type="name[]" value="1"> //row1 <input type="name[]" value="2"> //row2 <input type="name[]" value="3"> // row3 this is wrong i think you are looking for this
<input type="text" name="name[]" value="1"> //row1 <input type="text" name="name[]" value="2"> //row2 <input type="text" name="name[]" value="3"> // row3
-29094706 0 jQuery - If first element has class then Function I'm looking to add a piece of code sitewide to affect all of my pages.
Right now, it goes something like this.
if($('#container > div:first').attr('id') == 'filterOptions') { $('#container').prepend('<div class="banner"></div>'); } The output:
<div id="container"> <div class="banner"></div> <div id="filterOptions"><div> </div> Example, if the container looked like this:
<div id="container"> <div class="existingBanner"></div> <div id="filterOptions"><div> </div> Nothing would happen as the first div doesn't have the filterOptions ID.
Now I've hit a bump as I also have something that looks like this that the banner DOES get added to
<div id="container"> <a class="existingBanner" href="#"></a> <div id="filterOptions"><div> </div> This will essentially have a double banner which is something I want to avoid. because it's an anchor instead of a div.
So my question is. instead of targeting div:first how would I target ALL elements?
Something like...
if($('#container > any:first').attr('id') == 'filterOptions') { ... }
In the case of method over riding in objective c how selector knows that which method needs to call via selector?
As we dont pass any arguments in slector section...
Ex: in tmp.m file There is 2 methods with different arguments
-(void)details { } -(void)details:(NSDictionary *)result { } And when m call another method with the use of selector as:
[mc detailstrac:[[NSUserDefaults standardUserDefaults] valueForKey:@"userID"] tracid:self.trac_id selector:@selector(details:)]; How selector knows to call which method !
I have checked that
-(void)details:(NSDictionary *)result { } this method is called every time then what about
-(void)details { } this ?
-9455032 0You can't: floating point numbers aren't exact values, only estimations, by definition. You are supposed to get such deviations.
-30950216 1 Unit testing Python Flask StreamDoes anybody have any experience/pointers on testing a Flask Content Streaming resource? My application uses Redis Pub/Sub, when receiving a message in a channel it streams the text 'data: {"value":42}' The implementation is following Flask docs at: docs and my unit tests are done following Flask docs too. The messages to Redis pub/sub are sent by a second resource (POST).
I'm creating a thread to listen to the stream while I POST on the main application to the resource that publishes to Redis.
Although the connection assertions pass (I receive OK 200 and a mimetype 'text/event-stream') the data object is empty.
My unit test is like this:
def test_04_receiving_events(self): headers = [('Content-Type', 'application/json')] data = json.dumps({"value": 42}) headers.append(('Content-Length', len(data))) def get_stream(): rv_stream = self.app.get('stream/data') rv_stream_object = json.loads(rv_stream.data) #error (empty) self.assertEqual(rv_stream.status_code, 200) self.assertEqual(rv_stream.mimetype, 'text/event-stream') self.assertEqual(rv_stream_object, "data: {'value': 42}") t.stop() threads = [] t = Thread(target=get_stream) threads.append(t) t.start() time.sleep(1) rv_post = self.app.post('/sensor', headers=headers, data=data) threads_done = False while not threads_done: threads_done = True for t in threads: if t.is_alive(): threads_done = False time.sleep(1) The app resource is:
@app.route('/stream/data') def stream(): def generate(): pubsub = db.pubsub() pubsub.subscribe('interesting') for event in pubsub.listen(): if event['type'] == 'message': yield 'data: {"value":%s}\n\n' % event['data'] return Response(stream_with_context(generate()), direct_passthrough=True, mimetype='text/event-stream') Any pointers or examples of how to test a Content Stream in Flask? Google seems to not help much on this one, unless I'm searching the wrong keywords.
Thanks in advance.
-10412684 0 compiling your own glibcI am trying to compile my own glibc. I have a directory glibc, which contain the glibc source code I downloaded from the internet. From that directory I typed mkdir ../build-glibc. Now from the build-glibc directory I typed ../glibc/configure, which performed the configuration. Now I'm not sure how to call make. I can't call it from glibc directory since it doesn't have the configuration set, neither I can call it from build-glibc, since makefile is not in that directory. How do I solve this problem?
I'm a little bit new with with php and i just want to ask how can i make the the "Send Message" button send the inputted information on the form i created to my email.
Here's the code:
<section id="three"> <h2>Email Me!</h2> <p>You will receive a reply within 24-48 hours.</p> <div class="row"> <div class="8u 12u$(small)"> <form method="post" action="MAILTO:sample@email.com"> <div class="row uniform 50%"> <div class="6u 12u$(xsmall)"><input type="text" name="name" id="name" placeholder="Name" /></div> <div class="6u$ 12u$(xsmall)"><input type="email" name="email" id="email" placeholder="Email" /></div> <div class="12u$"><textarea name="message" id="message" placeholder="Message" rows="4"></textarea></div> </div> </form> <ul class="actions"> <li><input type="submit" value="Send Message" /></li> </ul> </div> <div class="4u$ 12u$(small)"> <ul class="labeled-icons"> <li> <h3 class="icon fa-home"><span class="label">Address</span></h3> 1234 Somewhere Rd.<br /> Nashville, TN 00000<br /> United States </li> <li> <h3 class="icon fa-mobile"><span class="label">Phone</span></h3> 000-000-0000 </li> <li> <h3 class="icon fa-envelope-o"><span class="label">Email</span></h3> <a href="#">hello@untitled.tld</a> </li> </ul> </div> </div> </section> Thanks!
-26121708 0This should do what you want:
select si.Rollnumber, max(case when si.Property = 'Name' then si.Value end) as Name, max(case when si.Property = 'Year' then si.Value end) as Year, max(case when si.Property = 'City' then si.Value end) as City from StudentInfo si group by si.Rollnumber;
-13823707 0 Creating a list of most popular posts of the past week - Wordpress I have created a widget for my Wordpress platform that displays the most popular posts of the week. However, there is an issue with it. It counts the most popular posts from Monday, not the past 7 days. For instance, this means that on Tuesday, it will only include posts from Tuesday and Monday.
Here is my widget code:
<?php class PopularWidget extends WP_Widget { function PopularWidget(){ $widget_ops = array('description' => 'Displays Popular Posts'); $control_ops = array('width' => 400, 'height' => 300); parent::WP_Widget(false,$name='ET Popular Widget',$widget_ops,$control_ops); } /* Displays the Widget in the front-end */ function widget($args, $instance){ extract($args); $title = apply_filters('widget_title', empty($instance['title']) ? 'Popular This Week' : $instance['title']); $postsNum = empty($instance['postsNum']) ? '' : $instance['postsNum']; $show_thisweek = isset($instance['thisweek']) ? (bool) $instance['thisweek'] : false; echo $before_widget; if ( $title ) echo $before_title . $title . $after_title; ?> <?php $additional_query = $show_thisweek ? '&year=' . date('Y') . '&w=' . date('W') : ''; query_posts( 'post_type=post&posts_per_page='.$postsNum.'&orderby=comment_count&order=DESC' . $additional_query ); ?> <div class="widget-aligned"> <h3 class="box-title">Popular Articles</h3> <div class="blog-entry"> <ol> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <li><h4 class="title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4></li> <?php endwhile; endif; wp_reset_query(); ?> </ol> </div> </div> <!-- end widget-aligned --> <div style="clear:both;"></div> <?php echo $after_widget; } /*Saves the settings. */ function update($new_instance, $old_instance){ $instance = $old_instance; $instance['title'] = stripslashes($new_instance['title']); $instance['postsNum'] = stripslashes($new_instance['postsNum']); $instance['thisweek'] = 0; if ( isset($new_instance['thisweek']) ) $instance['thisweek'] = 1; return $instance; } /*Creates the form for the widget in the back-end. */ function form($instance){ //Defaults $instance = wp_parse_args( (array) $instance, array('title'=>'Popular Posts', 'postsNum'=>'','thisweek'=>false) ); $title = htmlspecialchars($instance['title']); $postsNum = htmlspecialchars($instance['postsNum']); # Title echo '<p><label for="' . $this->get_field_id('title') . '">' . 'Title:' . '</label><input class="widefat" id="' . $this->get_field_id('title') . '" name="' . $this->get_field_name('title') . '" type="text" value="' . $title . '" /></p>'; # Number of posts echo '<p><label for="' . $this->get_field_id('postsNum') . '">' . 'Number of posts:' . '</label><input class="widefat" id="' . $this->get_field_id('postsNum') . '" name="' . $this->get_field_name('postsNum') . '" type="text" value="' . $postsNum . '" /></p>'; ?> <input class="checkbox" type="checkbox" <?php checked($instance['thisweek'], 1) ?> id="<?php echo $this->get_field_id('thisweek'); ?>" name="<?php echo $this->get_field_name('thisweek'); ?>" /> <label for="<?php echo $this->get_field_id('thisweek'); ?>"><?php esc_html_e('Popular this week','Aggregate'); ?></label> <?php } }// end AboutMeWidget class function PopularWidgetInit() { register_widget('PopularWidget'); } add_action('widgets_init', 'PopularWidgetInit'); ?> How can I change this script so that it will count the past 7 days rather than posts from last Monday?
-16865164 0Chrome (or any other browser) doesn't support HTAs at all. Actually HTAs are run by mshta.exe, and IE is used as a rendering & scripting engine.
When HTA is run with IE9 (<meta http-equiv="x-ua-compatible" content="IE=9">) there are some issues with <HTA: application>, like some mess with icon and window borders.
With IE10 (<meta http-equiv="x-ua-compatible" content="IE=edge">) it seems, that HTA properties are ignored totally, even singleInstance="yes" doesn't work. If you take a look at a runtime source, you can see the <HTA: application> tag is moved to the body, where it has not the expected influence.
All above written about IE is related to the actual HTA properties only, all HTML, scripts and privilegs work well. With IE10 even better and faster than ever before, and you can use real JavaScript instead of JScript.
To utilize all available features, you need to add document type and x-ua-compatible to your pages:
<!DOCTYPE html> <html> <head> <title></title> <meta http-equiv="x-ua-compatible" content="IE=edge"> ...
-22576505 0 Use the replace method:
function cap(str) { return str.replace(/([a-z])/, function (match, value) { return value.toUpperCase(); }) } Edit: In case you have a string containing multiple (space-separated) words, try something like:
function cap(str) { return str.split(' ').map(function (e) { return e.replace(/([a-z])/, function (match, value) { return value.toUpperCase(); }) }).join(' '); } This would convert "50newyork paris84 london" to "50Newyork Paris84 London"
Update your compateString method as follows:
u need to compare each step of the id alone.
public static int compareString(String str1, String str2){ String subString = str1.substring(str1.indexOf("##")+3, str1.length()); String subString1 = str2.substring(str2.indexOf("##")+3, str2.length()); String[] array1 = subString.split("-"); String[] array2 = subString1.split("-"); for(int i=0;i< array1.length && i< array2.length;i++) { BigInteger b1 = new BigInteger(array1[i]); BigInteger b2 = new BigInteger(array2[i]); if(b1.compareTo(b2) >0) //b1 is larger than b2 return 1; if(b1.compareTo(b2) <0) return -1; } if(array1.length == array2.length)//both numbers are equal return 0; if(array1.length > array2.length) return 1; return -1; }
-39010768 0 You cantry it this way, it should work:
$.ajax({ type: "GET", url: "/grafana/dashboard", contentType: "application/json", beforeSend: function(xhr, settings){ xhr.setRequestHeader("some_custom_header", "foo");}, success: function(data){ $("#output_iframe_id").attr('src',"data:text/html;charset=utf-8," + escape(data)) } });
-4589800 0 join is faster
SELECT COUNT(comments.uid) FROM comments JOIN user_relationships ON user_relationships.requestee_id = comments.uid WHERE user_relationships.requester_id = $some_id
-18099453 0 Why the data retrieved isn't shown I would to retrieve the data from http://api.eventful.com/rest/events/search?app_key=42t54cX7RbrDFczc&location=singapore . The tag under "title", "start_time", "longitude", "latitude". But I not sure why it couldn't be display out after I added the longitude and latitude.
This is from logcat:
08-07 17:17:44.190: E/AndroidRuntime(23734): FATAL EXCEPTION: main 08-07 17:17:44.190: E/AndroidRuntime(23734): java.lang.NullPointerException 08-07 17:17:44.190: E/AndroidRuntime(23734): at com.example.eventfulmaptry.MainActivity$ItemAdapter.getView(MainActivity.java:147) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.AbsListView.obtainView(AbsListView.java:1618) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.ListView.measureHeightOfChildren(ListView.java:1241) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.ListView.onMeasure(ListView.java:1152) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.View.measure(View.java:8513) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3143) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1017) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.LinearLayout.measureVertical(LinearLayout.java:386) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.LinearLayout.onMeasure(LinearLayout.java:309) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.View.measure(View.java:8513) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3143) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.FrameLayout.onMeasure(FrameLayout.java:250) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.View.measure(View.java:8513) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.LinearLayout.measureVertical(LinearLayout.java:531) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.LinearLayout.onMeasure(LinearLayout.java:309) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.View.measure(View.java:8513) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3143) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.FrameLayout.onMeasure(FrameLayout.java:250) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.View.measure(View.java:8513) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.ViewRoot.performTraversals(ViewRoot.java:857) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.ViewRoot.handleMessage(ViewRoot.java:1878) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.os.Handler.dispatchMessage(Handler.java:99) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.os.Looper.loop(Looper.java:130) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.app.ActivityThread.main(ActivityThread.java:3691) 08-07 17:17:44.190: E/AndroidRuntime(23734): at java.lang.reflect.Method.invokeNative(Native Method) 08-07 17:17:44.190: E/AndroidRuntime(23734): at java.lang.reflect.Method.invoke(Method.java:507) 08-07 17:17:44.190: E/AndroidRuntime(23734): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912) 08-07 17:17:44.190: E/AndroidRuntime(23734): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:670) 08-07 17:17:44.190: E/AndroidRuntime(23734): at dalvik.system.NativeStart.main(Native Method) This is my code :
public class MainActivity extends Activity { ArrayList<String> title; ArrayList<String> start_time; ArrayList<String> latitude; ArrayList<String> longitude; ItemAdapter adapter1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ListView list = (ListView) findViewById(R.id.list); title = new ArrayList<String>(); latitude = new ArrayList<String>(); longitude = new ArrayList<String>(); try { URL url = new URL( "http://api.eventful.com/rest/events/search?app_key=42t54cX7RbrDFczc&location=singapore"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new InputSource(url.openStream())); doc.getDocumentElement().normalize(); NodeList nodeList = doc.getElementsByTagName("event"); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); Element fstElmnt = (Element) node; NodeList nameList = fstElmnt.getElementsByTagName("title"); Element nameElement = (Element) nameList.item(0); nameList = nameElement.getChildNodes(); title.add(""+ ((Node) nameList.item(0)).getNodeValue()); NodeList websiteList = fstElmnt.getElementsByTagName("start_time"); Element websiteElement = (Element) websiteList.item(0); websiteList = websiteElement.getChildNodes(); start_time.add(""+ ((Node) websiteList.item(0)).getNodeValue()); NodeList websiteList1 = fstElmnt.getElementsByTagName("latitude"); Element websiteElement1 = (Element) websiteList1.item(0); websiteList1 = websiteElement1.getChildNodes(); latitude.add(""+ ((Node) websiteList1.item(0)).getNodeValue()); NodeList websiteList2 = fstElmnt.getElementsByTagName("longitude"); Element websiteElement2 = (Element) websiteList2.item(0); websiteList2 = websiteElement2.getChildNodes(); longitude.add(""+ ((Node) websiteList2.item(0)).getNodeValue()); } } catch (Exception e) { System.out.println("XML Pasing Excpetion = " + e); } adapter1 = new ItemAdapter(this); list.setAdapter(adapter1); } class ItemAdapter extends BaseAdapter { final LayoutInflater mInflater; private class ViewHolder { public TextView title_text; public TextView des_text; public TextView lat_text; public TextView long_text; } public ItemAdapter(Context context) { // TODO Auto-generated constructor stub super(); mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } //@Override public int getCount() { return title.size(); } //@Override public Object getItem(int position) { return position; } //@Override public long getItemId(int position) { return position; } //@Override public View getView(final int position, View convertView, ViewGroup parent) { View view = convertView; final ViewHolder holder; if (convertView == null) { view = mInflater.inflate(R.layout.mainpage_list,parent, false); holder = new ViewHolder(); holder.title_text = (TextView) view.findViewById(R.id.title_text); holder.des_text = (TextView) view.findViewById(R.id.des_text); holder.lat_text = (TextView) view.findViewById(R.id.lat_text); holder.long_text = (TextView) view.findViewById(R.id.long_text); view.setTag(holder); } else { holder = (ViewHolder) view.getTag(); } holder.title_text.setText(""+title.get(position)); holder.des_text.setText(""+Html.fromHtml(start_time.get(position))); holder.lat_text.setText(""+Html.fromHtml(latitude.get(position))); holder.long_text.setText(""+Html.fromHtml(longitude.get(position))); return view; } } }
-10316217 0 How to see output in Amazon EMR/S3? I am new to Amazon Services and tried to run the application in Amazon EMR.
For that I have followed the steps as:
1) Created the Hive Scripts which contains --> create table, load data statement in Hive with some file and select * from command.
2) Created the S3 Bucket. And I load the object into it as: Hive Script, File to load into the table.
3) Then Created the Job Flow (Using Sample Hive Program). Given the input, ouput, and script path (like s3n://bucketname/script.q, s3n://bucketname/input.txt, s3n://bucketname/out/). Didn't create out directory. I think it will get created automatically.
4) Then Job Flow start to run and after some time I saw the states as STARTING, BOOTSTRAPING, RUNNING, and SHUT DOWN.
5) While running SHUT DOWN state, it get terminated automatically showing FAILES status for SHUT DOWN.
Then on the S3, I didn't see the out directory. How to see the output? I saw directory like daemons, nodes, etc......
And also how to see the data from HDFS in Amazon EMR?
-40066740 0There might be other problems in your snippet, so far I've noticed you're using std::map which is unusual data-structure for this purpose as std::map will overwrite previous nodeId with same weight. You can use std::multimap but you will need some more std::iterator and stuffs for looping on key-value pairs. Use std::priority_queue which will allow you to keep the code precise.
Here is a simple snippet solution with std::priority_queue which calculate shortest distance from source to destination node. You can modify or write similarly for your problems:
#define Max 20010 // MAX is the maximum nodeID possible vector <pair<int, int>> adj[Max]; // adj[u] contains the adjacent nodes of node u int dis[Max]; // dis[i] is the distance from source to node i priority_queue <pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > Q; int dijkstra(int src, int des) { memset(dis, MAX, sizeof dis); Q = priority_queue <pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > (); dis[src] = 0; Q.push({dis[src] , src}); while(!Q.empty()) { int u = Q.top().second; Q.pop(); if(u == des) { return dis[des]; } for(int i = 0; i < (int)adj[u].size(); ++i) { int v = adj[u][i].first; int cost = adj[u][i].second; if(dis[v] > dis[u] + cost) { dis[v] = dis[u] + cost; Q.push({dis[v], v)}); } } } return -1; // no path found }
-15404711 0 in the javascript function. Then it will not postback.
$j(".colorBoxLink").click((function () { $j("div#popup").show(); var editor = new wysihtml5.Editor("wysihtml5_textarea", { // id of textarea element toolbar: "wysihtml5-toolbar", // id of toolbar element parserRules: wysihtml5ParserRules, // defined in parser rules set stylesheets: ["Styles/wysihtml5.css", "Styles/wysihtml5.css"] }); $j.colorbox({ inline: true, href: "#popup", modal: true, scrolling: false, onCleanup: function () { $j("div#popup").hide(); } }); return false; }));
-9373371 0 In magento admin in
Catalog->Manage categories Select category and choose preffered store view. There you should edit and save "URL key" parameter.
In case it still shows old url - clean cache and make url rewrite reindex.
-35814790 0stack.top() is illegal if the stack is empty.while((!highPrecedence(stack.top(),c)) && (stack.size()!=0)){while((!stack.empty()) && (!highPrecedence(stack.top(),c))){i is not good and you are printing uninitialized variable, which has indeterminate value.int i=0; to int i=-1;Try this updated regex:
(?<=href\=\")[^<]*?(?=\">\[link\]) See demo. The problem is that the dot matches too many characters and in order to get the right 'href' you need to just restrict the regex to [^<]*?.
I have the following code:
obj2 = JSON.parse(ajax.responseText); for (var i = 0; i <= obj2.length - 1; i++) { var row = table.insertRow(1); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); var cell3 = row.insertCell(2); var cell4 = row.insertCell(3); var cell5 = row.insertCell(4); var cell6 = row.insertCell(5); var cell7 = row.insertCell(6); var cell8 = row.insertCell(7); cell1.innerHTML = obj2[i].qid; cell2.innerHTML = obj2[i].question; cell3.innerHTML = obj2[i].answer1; cell4.innerHTML = obj2[i].answer2; cell5.innerHTML = obj2[i].answer3; cell6.innerHTML = obj2[i].answer4; $(function(){ var btn = document.createElement("BUTTON"); var t = document.createTextNode("Delete "+cell1.innerHTML); //this works well btn.appendChild(t); btn.className="menu_buttons"; $(btn).on('click' ,function(){ delete_(cell1.innerHTML);//this assigns the value of the last iteration to each button }); cell8.appendChild(btn); }); } I'm iterating over a json array and I want to assign the same function (with different parameter, depending on an id from the array) to each button, and as I mentioned in the comment, it overwrites each button with the same parameter. What's wrong?
-32481778 0Quick answer:
First af all you are starting from x=0 and then increasing it which is not the best solution since you are looking for the maximum value and not the first one. So for that I would go from an upperbound that can be
x=abs((b)^(1/4))
than decrease from that value, and as soon you find an element <=b you are done.
You can even think in this way:
for y=b to 1 solve(x^4+x^3+x^2+x+1=y) if has an integer solution then return solution See this
This is a super quick answer I hope I didn't write too many stupid things, and sorry I don't know yet how to write math here.
-5167035 0 Excutereader is very slow when taking data by oledbcommand objectI am fetching data from dBase4 database by using object of oledbcommand and load it into datatable. but it is taking too much time to fetch 160 records around 5-10 minutes. Please Help me Out.
Code:
using (OleDbConnection cn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;" + @"Data Source=" + TrendFilePath + "\\" + Pathname + ";" + @"Extended Properties=dBASE III;")) using (OleDbCommand cm = cn.CreateCommand()) { cn.Open(); for (int L = 0; L <= months; L++) { DataTable dt_Dbf = new DataTable(); From_Date = DateTime.ParseExact(frmdate, dateFormat2, provider); From_Date = From_Date.AddMonths(L); int month = From_Date.Month; string year = "1" + From_Date.Year.ToString().Substring(2, 2); if (L == 0) { cm.CommandText = @"SELECT * FROM 128.DBF where DATE_Y =" + year + " and DATE_M = " + month + " and DATE_D>=" + From_Day + ""; dt_Dbf.Load(cm.ExecuteReader(CommandBehavior.CloseConnection)); } } }
-28447945 0 method 1.you can use load data command
http://blog.tjitjing.com/index.php/2008/02/import-excel-data-into-mysql-in-5-easy.html method 2. Excel reader
https://code.google.com/p/php-excel-reader/
method 3. parseCSV
https://github.com/parsecsv/parsecsv-for-php method4. (PHP 4, PHP 5) fgetcsv
http://in1.php.net/fgetcsv
-37004827 0 You need to lerp (linearly interpolate) between the two textures. Your fragment shader needs to hold both textures and then trigger lerping once you load the second texture, the one that you want to change to. Than use operation like col = fromTex.rgb * (1.0-t) + toTex.rgb * t and change the blending/lerping coefficient t throughout the time until you completely blend into the second texture. t can be sent as a uniform that would be slowly changing from the 0.0->1.0 over the time.
I Am trying to include in app purchase and i have successfully through in showing up SKUs available.Now I want to make a fake purchase.So I used appId = "android.test.purchased". For the first time it worked flawlessly, but from next it is throwing exception as below.
Attempt to invoke virtual method 'android.content.IntentSender android.app.PendingIntent.getIntentSender()' on a null object reference
Has any body come across such situation?Please help out.
package com.inappbilling.poc; import java.util.ArrayList; import org.json.JSONObject; import android.app.Activity; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import com.android.vending.billing.IInAppBillingService; public class TestInAppPurchase extends Activity { private final static String SERVICE_INTENT = "com.android.vending.billing.InAppBillingService.BIND"; private static final String _TAG = "BILLING ACTIVITY"; private final String _testSku = "android.test.purchased"; //available skus static final String SKU_7DAYS = "7days"; static final String SKU_30DAYS = "30days"; private Button _7daysPurchase = null; private Button _30daysPurchase = null; private IInAppBillingService _service = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d(_TAG, "created"); _7daysPurchase = ( Button ) findViewById(R.id.sevendays_btn); _30daysPurchase = ( Button ) findViewById(R.id.thirtydays_btn); _7daysPurchase.setOnClickListener(_purchaseListener); _30daysPurchase.setOnClickListener(_purchaseListener); } @Override protected void onStart() { super.onStart(); } OnClickListener _purchaseListener = new OnClickListener() { @Override public void onClick(View v) { switch ( v.getId() ) { case R.id.sevendays_btn: doPurchase(); break; case R.id.thirtydays_btn: break; } } }; private ServiceConnection _serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { _service = IInAppBillingService.Stub.asInterface( service ); Log.d(_TAG, _service.toString()); } @Override public void onServiceDisconnected(ComponentName name) { _service = null; Log.d(_TAG, "destroyed"); } }; private void doPurchase(){ if ( _service == null) { Log.e( _TAG , "Billing failed: billing service is null "); return; } ArrayList testSku = new ArrayList( ); testSku.add( _testSku ); Bundle querySkus = new Bundle(); querySkus.putStringArrayList("ITEM_ID_LIST", testSku); Bundle skuDetails ; try { skuDetails = _service.getSkuDetails(3, getPackageName(), "inapp", querySkus); int response = skuDetails.getInt("RESPONSE_CODE"); if( response == 0 ){ ArrayList<String> responseList = new ArrayList<String>( ); responseList = skuDetails.getStringArrayList("DETAILS_LIST"); for( String responseString : responseList ) { JSONObject jobj = new JSONObject( responseString ); String sku = jobj.getString("productId"); if( sku.equals( _testSku )){ Bundle buyIntentBundle = _service.getBuyIntent(3, getPackageName(), sku ,"inapp","" ); PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT"); startIntentSenderForResult(pendingIntent.getIntentSender(), 1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0)); } } } else { Log.e( _TAG , "Failed " ); } } catch (Exception e) { Log.e( _TAG, "Caught exception !"+ e.getMessage() ); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(requestCode == 1001 ){ String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA"); if( resultCode == RESULT_OK ){ try{ JSONObject jobj = new JSONObject( purchaseData ); String sku = jobj.getString(_testSku); String paid = jobj.getString("price"); Log.v("SKU DATA", sku +"============"+ paid); }catch( Exception e) { e.printStackTrace(); } } } } @Override protected void onDestroy() { super.onDestroy(); if( _serviceConnection != null ){ unbindService( _serviceConnection ); } } }
-29214004 0 Change the color of the series line dynamically by month I have a series from Jan - Dec, the requirement is to update the last data point to grayscale colors. So I have created additional data series assigning grayscale colors to the series. Can I be able to join the colored series with grayscale colored series
http://jsfiddle.net/hgj7sfhp/33/
for example, London colored and London grayscale should be joined, like continuouss series after November, without any break in the series. I have London & Berlin in December points in the chart, but i wanted to attached to the colored series, is it possible ?
Also group the legend of colored series and grayscale series.
London, Berlin
LondonGray, BerlinGray
$(function () { var grayblue = '#1D1D1D'; var grayred = '#4C4C4C'; dataLondon = [ 48.9, 38.8, 39.3, 41.4, 47.0, 48.3, 59.0, 59.6, 52.4, 45.6, 90.4]; dataBerlin = [ 42.4, 33.2, 34.5, 39.7, 52.6, 75.5, 57.4, 60.4, 47.6, 23.6, 29.1] highcharts(dataLondon, dataBerlin, 0); function highcharts(dataLondon, dataBerlin, number) { $('#container').highcharts({ chart: { type: 'line' }, title: { text: 'Monthly Average Rainfall' }, subtitle: { text: 'Source: WorldClimate.com' }, xAxis: { categories: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ], plotBands: { color: 'Red', from: 10.5, to: 10.55, label: { text: 'I am label' } } }, yAxis: { min: 0, title: { text: 'Rainfall (mm)' } }, tooltip: { headerFormat: '<span style="font-size:10px">{point.key}</span><table>', pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' + '<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>', footerFormat: '</table>', shared: true, useHTML: true }, colors: ['#0000FF', '#FF0000'], plotOptions: { column: { pointPadding: 0.2, borderWidth: 0 } }, series: [{ name: 'London', data: dataLondon }, { name: 'Berlin', data: dataBerlin }, { name: 'London', data: [null,null,null,null,null,null,null,null,null,null,null,10], color: '#1D1D1D' }, { name: 'Berlin', data: [null,null,null,null,null,null,null,null,null,null,null, 51.1], color: '#4C4C4C' }] }); } });
-28422790 0 Per ngInfiniteScroll's test case of infinite-scroll-immediate-chec, If this parameter is set as true (the default value), meanwhile the directive's element can not fill up the browser window' height, it will trigger a loadMore() immediately even you don't scroll your window at all. And this action will only be triggered once, therefor if there are 3 three tiny results on first load and they don't reach the bottom, function loadMore() won't be triggered until you scroll the window.
While if this parameter is set as false, you have to trigger the first call of loadMore manually or programmably.
On Android 5.0 this has changed, you have to call setElevation(0) on your action bar. Note that if you're using the support library you must call it to that like so:
getSupportActionBar().setElevation(0); It's unaffected by the windowContentOverlay style item, so no changes to styles are required
-23311182 0 Convert JSON String to Object - jqueryI have a JSON String like this.
{"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11464"} I wanted to convert it to object like this
[{"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11464"}] I did figure that out like this.
'[' + {"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11464"} + ']' And using $.parseJSON() to make it a JSON.
But instead of concatenating. Is there any elegant way to do it?
If so please do share me.
Thanks in advance.
-22064095 1 fast system calls in RI have a nest for loop inside which I run a python script using the system call option in R, I found that all the execution time of my code is spent just on the system call in order to run the python script, so I was wondering if there is any tricks that I can use to save this great loss of time spent on repeatedly using the system call especially cause the python script in itself only take 1 second per each call, the problem is that I can't run the .py script independently cause I's using some parameters generated by other parts in R. here is a snapshot of my code and any suggestion is highly appreciated:
for(x in 1:10000){ ....... for (y in 1:10000){ ..... x=system("python calc.py -c1 -c2",intern = TRUE) } }
-18638692 0 Gradient Filling a PNG with Quartz How can I fill the non-transparent areas of a PNG UIImage with a linear gradient? I'd like to reuse a PNG shape for MKAnnotationViews, but change the gradient per annotation's properties.
-29734434 0If you want to send a parameter to another page, then you need to set the url and query string in the href tag of an a tag.
For example:
<a id="myatag" href=""> <!-- Whatever you want the user to click--> </a> and the js:
document.getElementById("myatag").href = "OrderPrint.html?image=" + "sniperImg" + i; Then, you can retrieve the name of the image on the server side script, and append ".jpg" or whatever extension you are using. For example, in PHP:
$image = "VideoImages/" + $_GET["image"] + ".jpg";
-21777508 0 I am not sure you are asking for this.
If the path of the folders are same you can use -or with find
find $CATALINA_HOME/webapps/myapp/WEB-INF/lib/ -name "*.jar" -or -type d
-type d will also find directories
You can match number with decimals only or numbers with integer and decimal parts:
for (var x in arr = ["ZAR 200.15", "300.0", "1.02", "29.001", "10"]) { // decimal part only console.log(x, arr[x].match(/(\d+)(\.\d+)?/g)) // integer + decimal part console.log(x, arr[x].match(/(\d+\.\d+)/g)) } The ODP.NET managed data provider does not support code-first development with the Entity Framework. From its readme.txt in odp.net/doc under the oracle client dir:
"7. ODP.NET 11.2.0.3 does not support Code First nor the DbContext APIs."
You'll have to use the model-first or database-first approach.
-27625701 0You did not even use a search engine to look for the error message.
In google, the first result is the MDB2 FAQ page which explains the error and the reason for it.
-14136639 0Yes, you might run into trouble. See this link for how to solve your problem.
@Service are constructed twice
The way you proceed when creating modules seems valid to me. You have a context.xml file for each module and all will get loaded once you load the application. Your modules are self-contained and can also be used in different environments. That's pretty much the way I'd also do it.
-10051688 0A local branch can only track a remote branch for pushing if the local and remote branches have the same name. For pulling, the local branch need not have the same name as the remote branch. Interestingly, if you setup a branch 'foo' to track a remote branch 'origin/bar' (with 'git branch foo origin/bar') and if the remote repository does not currently have a branch named 'foo', then if later the remote does get a branch named foo, then the local branch foo will track origin/foo thereafter!
$ git clone dev1 dev2 Cloning into 'dev2'... done. $ cd dev2 # # After clone, local master tracks remote master. # $ git remote show origin * remote origin Fetch URL: /Users/ebg/dev1 Push URL: /Users/ebg/dev1 HEAD branch: master Remote branch: master tracked Local branch configured for 'git pull': master merges with remote master Local ref configured for 'git push': master pushes to master (up to date) # # Create branch br1 to track origin/master # $ git branch br1 origin/master Branch br1 set up to track remote branch master from origin. # # br1 tracks origin/master for pulling, not pushing # $ git remote show origin * remote origin Fetch URL: /Users/ebg/dev1 Push URL: /Users/ebg/dev1 HEAD branch: master Remote branch: master tracked Local branches configured for 'git pull': br1 merges with remote master master merges with remote master Local ref configured for 'git push': master pushes to master (up to date) # # Go to the origin repo and now create a new 'br1' branch # $ cd ../dev1 $ git checkout -b br1 Switched to a new branch 'br1' # # Go back to dev2, fetch origin # $ cd ../dev2 $ git fetch origin From /Users/ebg/dev1 * [new branch] br1 -> origin/br1 # # Now local branch 'br1' is tracking origin/br1 for pushing # $ git remote show origin * remote origin Fetch URL: /Users/ebg/dev1 Push URL: /Users/ebg/dev1 HEAD branch (remote HEAD is ambiguous, may be one of the following): br1 master Remote branches: br1 tracked master tracked Local branches configured for 'git pull': br1 merges with remote master master merges with remote master Local refs configured for 'git push': br1 pushes to br1 (up to date) master pushes to master (up to date) So br1 was originally supposed to pull/push from master and we end up with br1 pulling from origin/master and pushing to a branch we never knew existed.
-29651029 0If i'm not getting your question wrongly, your question mysql solution would be Get top n records for each group of grouped results
But when we convert our desire query to laravel, so its will look alike:
$Rating1 = Model::whereRating(1)->take(10); $Rating2 = Model::whereRating(2)->take(10); $Rating3 = Model::whereRating(3)->take(10); $result = Model::unionAll($Rating1)->unionAll($Rating2)->unionAll($Rating3)->get(); And its also one query not multiple as per laravel 4.2 docs, If you still confuse to implement it, let me know.
-7009356 0Not very elegant solution too, but also works and do not require recreating array. Also, you can access the element value.
$array = (array)json_decode('{"123":100}'); $array_keys = array_keys($array); $array = (object)$array; foreach ($array_keys as $key) { if (!isset($array->$key)) { print "What is happening here?"; } else { print "It's OK val is {$array->$key}"; } } Note $ before key in $array->$key, it is important.
I'm sure this is pretty simple, but I'm stumped for a way to do this. Essentially if I have an array with P collumns and V^P rows, how can I fill in all the combinations, that is, essentially, all possible numbers in base V of P digits. For example, for P=3 and V=2:
000 001 010 011 100 101 110 111 Keep in mind that this is an 2 dimensional array, not an array of ints.
For P=4 and V=3.
0000 0001 0002 0010 0011 0012 .... Having this array generated, the rest of work for what I'm trying to devolop is trivial. So having some code/tips on how to do this would be greatly appreciated. Thanks.
-38432624 0 Fast inserting or updating data from huge JSON to MYSQL with phpIn a project of mine I have a problem updating my mysql db from a huge json. the json object in question consist of ~1000 entries like this:
[{ "uniqueId":"578742901714e", "lat": -76.760541, "lng": 121.289062, "description":"foo and bar", "visible": true }] In order to compare the data in the json to the database, I used different statements enclosed in different loops. While this worked it took some time ~45 seconds for the whole json to be processed and written.
Edit:
To clarify, I loop through the array returned by json_decode() and compare the data directly to the Database via SELECT and INSERT STATEMENTS - which works but is slow as hell, because the data is huge
Because the user has to wait for this to ensure data integrity, I decided this should be sped up.
So I looked using INSERT INTO ON DUPLICATE KEY UPDATE, which should work with multiple data sets.
But here's the real problem: Because some entries like "description" are saved in their own table I need something like LAST_INSERT_ID() to know the auto-increment id of the just inserted dataset. But LAST_INSERT_ID() doesn't work that way and only returns the first row if it is used in a batch INSERT. (Documentation)
So I'm stuck between a functioning but very slow execution and a non-functioning but (supposedly) very fast execution.
I don't really know how to proceed, can you help me?
Edit:
The database in question consists of some tables. The most prominent ones are the following two:
table poi:
#1 id int auto-increment primary #2 unique_id varchar(13) unique #3 date int(11) #4 visible tinyint(1)/bool table poi_description:
#1 id int auto-increment primary #2 poi_id int(11) #3 description text #4 date int(11) #5 user int(11) I read so much in the last two days that I'm really not sure how to update the rows if the uniqueid is already in the table. I thought, I could get it to work with INSERT ON DUPLICATE UPDATE, but that looks only for the primary key - at least that's how it looks to me.
-36343998 0How I centered a Topojson, where I needed to pull out the feature:
var projection = d3.geo.albersUsa(); var path = d3.geo.path() .projection(projection); var tracts = topojson.feature(mapdata, mapdata.objects.tx_counties); projection .scale(1) .translate([0, 0]); var b = path.bounds(tracts), s = .95 / Math.max((b[1][0] - b[0][0]) / width, (b[1][1] - b[0][1]) / height), t = [(width - s * (b[1][0] + b[0][0])) / 2, (height - s * (b[1][1] + b[0][1])) / 2]; projection .scale(s) .translate(t); svg.append("path") .datum(topojson.feature(mapdata, mapdata.objects.tx_counties)) .attr("d", path)
-15153597 0 You could use this:
If this was your url:
url(r'(?P<category>[a-z]+)$', 'display', name='dyn_display') reverse('dyn_display', kwargs={'category': 'first'}) To redirect you can use it like this in your view:
from django.http import HttpResponseRedirect return HttpResponseRedirect(reverse('dyn_display', kwargs={'category': 'first'})) If this was your url:
url(r'$', 'display', name='dyn_dysplay') reverse('dyn_display') To redirect you can use it like this in your view:
from django.http import HttpResponseRedirect return HttpResponseRedirect(reverse('dyn_display')) To have a view that could receive an optional value you would need 2 urls:
url(r'$', 'display', name='dyn_optional_display') url(r'(?P<category>[a-z]+)$', 'display', name='dyn_display') And then your view:
def courses_display(request, category=None): ctx = {} if category: ctx.update({category: 'in'}) return render_to_response('display/basic.html', ctx, context_instance=RequestContext(request))
-35723634 0 Simplest way would be to use a wild card character (*) and add the wildcarded option
cts:search(fn:doc(),cts:word-query("*226", ('wildcarded'))) EDIT:
Although this matches the example documents, as Kishan points out in the comments, the wildcard also matches unwanted documents (e.g. containing "226226").
Since range indexes are not an option in this case because the data is mixed, here is an alternative hack:
cts:search( fn:doc(), cts:word-query( for $lead in ('', '0', '00', '000') return $lead || "226")) Obviously, this depends on how many leading zeros there can be and will only work if this is known and limited.
-36117190 0 Laravel with drivers of MongoDBI'm new using MongoDB in laravel, I want to use laravel 4.2 with MongoDB but I have this problem:
> C:\xampp\htdocs\laravel-mongo>composer require jenssegers/mongodb Using version ^3.0 for jenssegers/mongodb ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev) Your requirements could not be resolved to an installable set of packages. Problem 1 - jenssegers/mongodb v3.0.0 requires mongodb/mongodb ^1.0.0 -> satisfiable by mongodb/mongodb[1.0.0, 1.0.1]. - jenssegers/mongodb v3.0.1 requires mongodb/mongodb ^1.0.0 -> satisfiable by mongodb/mongodb[1.0.0, 1.0.1]. - jenssegers/mongodb v3.0.2 requires mongodb/mongodb ^1.0.0 -> satisfiable by mongodb/mongodb[1.0.0, 1.0.1]. - mongodb/mongodb 1.0.1 requires ext-mongodb ^1.1.0 -> the requested PHP extension mongodb has the wrong version (1.0.0) installed. - mongodb/mongodb 1.0.0 requires ext-mongodb ^1.1.0 -> the requested PHP extension mongodb has the wrong version (1.0.0) installed. - Installation request for jenssegers/mongodb ^3.0 -> satisfiable by jenssegers/mongodb[v3.0.0, v3.0.1, v3.0.2]. To enable extensions, verify that they are enabled in those .ini files: - C:\xampp\php\php.ini You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode. Installation failed, reverting ./composer.json to its original content.-15299618 0
I would like to set startAt as an number.
SomeClass.prototype.startAt is a number (0).
Your get function explicitly returns false if the property is "falsey":
if(!this[prop]){return false;} In JavaScript, 0, "", false, undefined, and null are all "falsey", and so the condition above will be true and cause get to return false.
If your goal is to return false if the property doesn't exist, you can do that like this:
if (!(prop in this)) { return false; } That will check if the property exists on the object itself or its prototype, which I suspect is what you want. But if you only want to check the object itself and ignore properties on the prototype, that would be:
if (!this.hasOwnProperty(prop)) { return false; } Bringing that all together, if your goal is for get to return false for properties that the object doesn't have (either its own, or via its prototype), then:
get : function(prop){ if (typeof prop !== "string" || !(prop in this)) { return false; } return this[prop]; } I've done a few things there:
typeof is an operator, not a function, so you don't use parens around its operand (normally)
Since "undefined" is !== "string", there's no need to check for it specifically when checking that prop is a string.
I used !(prop in this) to see if the object (or its prototype) has the property.
I combined the two conditions that returned false into a single if statement using ||.
You can look into jQuery to dynamically change CSS properties as the certain events are called. You can find a great tutorial here. Here is an example from an old project of mine:
$(window).scroll(function (e) { $el = $('.fixedElement'); if ($(this).scrollTop() > 98 && $el.css('position') != 'fixed') { $('.fixedElement').css({ 'position': 'fixed', 'top': '0px', 'width': '90%', 'min-width': '1200px' }); } });
-34439047 0 This is what you want to use:
sort -t: -k 1.5,1.8n -k 2.1,2.7n inputfile 440c0401 mfcc.1.ark:9 440c0401 mfcc.1.ark:501177 440c0402 mfcc.2.ark:15681 440c0403 mfcc.3.ark:516849
-t -separator of fields(should not be used elsewhere in the inputfile
-k is key for sorting(could be used > 1) -k 1.5,1.8n means: sort numerical(this tells the n) by the field 1 from 5th to 8th character.
second -k tells sort the field 2 from the first to the 7th character numerically.
Better code (at least for me):
void MyClass::OnPaint() { CPaintDC dc(this); // device context for painting COLORREF highlightFillColor; CPen nPen, *pOldPen = NULL; CBrush nBrush, *pOldBrush = NULL; CRect rect; GetWindowRect(rect); ScreenToClient(rect); BmsMemDC memDc(&dc, &rect); memDc.SetBkMode(TRANSPARENT); //dc.Re highlightFillColor = RGB(0x99,0xB4,0xFF); nPen.CreatePen( PS_SOLID, 4, highlightFillColor); nBrush.CreateSolidBrush( GetSysColor(COLOR_3DFACE )); pOldPen = memDc.SelectObject(&nPen); pOldBrush = memDc.SelectObject(&nBrush); if(leftGroupSelected) { rect.SetRect(rect.left + 4, rect.top+30, rect.left + 126, rect.bottom - 5); memDc.FillRect(&rect,&nBrush); memDc.RoundRect(rect.left, rect.top, rect.right, rect.bottom, 8, 8); } if (rightGroupSelected) { rect.SetRect(rect.left + 134, rect.top+30, rect.left + 256, rect.bottom - 5); memDc.FillRect(&rect,&nBrush); memDc.RoundRect(rect.left, rect.top, rect.right, rect.bottom, 8, 8); } }
-37129365 0 Contenteditable, bizarre behaviour of child elements, and NOT whitespace independent?I've been playing around with contenteditable fields, and have come across an odd behaviour that I cannot figure out.
Check out fiddle for this particular problem.
I have two identical contenteditable divs. Both of them have the same <span> child, followed by a single blank character (otherwise carrot issues ensue). The only difference between the two is that the second div has been "prettified", and made more readable by indenting the <span> on a new line.
<div style="margin-bottom: 15px;" contenteditable="true"><span class="lead" contenteditable="false">Something something</span>​</div> <div contenteditable="true"> <span class="lead" contenteditable="false">Something something</span>​ </div> Try this in both of the divs...
You'll notice that in the top (first) contenteditable div, you can delete the <span> element, as though it were one giant character. You should also notice that that in the second div, no amount of backspacing will ever clear it out. At least not in Safari.
So what gives!? I thought HTML was whitespace independent - why the difference in behaviour of the two?
Viewing the source, they have slightly different markup...
... but it still behooves me as to why there would be any difference.
I would like it to be deletable, and so the solution is obviously just to use the former version, but it is still curious as to why this issue exists at all.
Also! If you happen to be a contenteditable guru, I've been fighting with another issue over here. Any help on that one is welcome!
I'm currently coding against a library that uses an event system to signify user interface interactions. Each listener can either be a pointer to an object and a function to call, or a std::function. For example, the MenuItem object defines an OnClick event that will call a function that takes a MenuItem*:
someMenuItem->OnClick.addListener( this, &myObj.doSomeAction ); ... void myObj::doSomeAction( MenuItem* menuItem ) {} or
someMenuItem->OnClick.addListener( []( MenuItem* menuItem ) {} ); It's often the case that doSomeAction is part of the public API of the class that we might want to call for some reason other than the user selecting the menu item. Is it possible to use std::bind to throw away the MenuItem* argument so that doSomeAction( MenuItem* menuItem ) could be defined as simply doSomeAction()?
PS - I do realize that I could use lambdas to do the same thing, but if bind can do the same thing then it might be more stylistically pleasing to some.
-26729511 0Just check once if it is only \037 or ,\037 in delimiter. And also check the same in session in set file properties for the flat file target.
-23350686 0Spring Social Facebook is a module within the Spring Social family of projects that enables you to connect your Spring application with the Facebook Graph API.
I'm experimenting around the idea of a simple logger that would look like this:
log(constant: String, _ variable: [String: AnyObject]? = nil) Which would be used like this:
log("Something happened", ["error": error]) However I want to prevent misuse of the constant/variable pattern like the following:
log("Something happened: \(error)") // `error` should be passed in the `variable` argument Is there a way to make sure that constant wasn't constructed with a string interpolation?
I have installed Berkeley DB 5.1.25.msi Windows installer and now I want to connect to it with a Java API. How can I do that?
-35382289 1 Controlling pygame animation through text inputI need to create a fighting game that gives prompts and accepts input through text, such as a raw input and then performs the animation, while still have the characters animated, e.g. moving back and forth in a ready to fight stance. How would I go about this?
-1217690 0I'm probably showing my age, but I still love my copy of Foley, Feiner, van Dam, and Hughes (The White Book).
Jim Blinn had a great column that's available as a book called Jim Blinn's Corner: A Trip Down the Graphics Pipeline.
Both of these are quited dated now, and aside from the principles of 3D geometry, they're not very useful for programming today's powerful pixel pushers.
OTOH, they're probably just perfect for an embedded environment with no GPU or FPU!
-24426871 0 Accessing a controller from a external library file codeigniterI have added a external library controller in "application/libraries/Validate_login.php".
When i load a controller in application/controllers/ from external library controller, i'm getting error Library verifylogin Not Found.
Validate_login.php
class Validate_login extends CI_Controller { function __construct() { parent::__construct(); $this->load->model('loginuser'); $this->load->helper('url'); $this->load->library('verifylogin');// controller which is in application/controllers/ } }
-2836845 0 The extra "stuff" is there because you've passed the buffer size to memcpy. It's going to copy that many characters, even when the source is shorter.
I'd do things a bit differently:
void copy_string(char *dest, char const *src, size_t n) { *dest = '\0'; strncat(dest, src, n); } Unlike strncpy, strncat is defined to work how most people would reasonably expect.
Ensure you are including the correct (latest) cordova file in your HTML.
I had the same problem and I was including
cordova-1.8.0.js rather than
cordova-2.4.0.js
-14359504 0 After wondering for hours through different advices, this one worked for me (Installed via MacPorts):
Courtesy of Chris Brewer:
Download and install MacPorts from http://macports.org.
The following steps are performed in the Terminal:
Force MacPorts to update (will only work if Apple's Xcode installed):
sudo port -v selfupdate Now, install memcached:
sudo port install php5-mcrypt Copy the newly created shared object for mcrypt into Mac OS X’s default PHP5 extension directory:
sudo cp /opt/local/lib/php/extensions/no-debug-non-zts-20090626/mcrypt.so /usr/lib/php/extensions/no-debug-non-zts-20090626/ Next, you need to edit php.ini to add the extensions. Find the phrase Dynamic Extensions, and add:
extension=mcrypt.so And finally, restart Apache:
sudo apachectl restart
How to restrict a user (role) to visit a particular page only certain number of times?
I am using drupal 6. It's for premium content, I just want to give 5 premium content free.
-30850931 0You can't append to a tuple at all (tuples are immutable), and extending to a list with + requires another list.
Make curveList a list by declaring it with:
curveList = [] and use:
curveList.append(curve) to add an element to the end of it. Or (less good because of the intermediate list object created):
curveList += [curve]
-23445517 0 calculate expected cost of final product using atleast k out of n items in c Suppose I have 4 items and i have to pick at least 1 item to make a product out of them. I have cost corresponding to each item as Item1 -> 4 , Item2 -> 7 , Item3 -> 2 , Item4 -> 5.I have to to find expected cost of the final product means an average of all possible combinations Item used like if I use only 1 item then cost may be 4 , 7 , 2 , 5 and if if i use 2 items the cost would be 4+7 , 4+2 , 4+5 , 7+2 , 7+5 , 2+5 and similarly all combinations for using three items and 4+2+7+5 for using four items.Adding those all combinations and dividng them with no. of combination gives me expected cost of the final product.So I want to find sum of all these combinations then how can I go for it??
I think recursion will be used for calculating these combination but unable to apply ???
-36428352 0To make it works, you can use padding-left instead of margin-left and also adapt the width of the td
.modules-table > tbody > tr > td:nth-child(2) { width:256px; padding-left:80px; }
-15252037 0 Do not extend Activity class in AppPreferences. and remove the onCreate() method.
Do like this way.
public class AppPreferences extends Activity { private SharedPreferences settings = null; AppPreferences(Context context) { settings = context.getSharedPreferences(LOGIN_CREDENTIALS, MODE_PRIVATE); } ...//Rest of your code. } In Login activity.
appPreferences = new AppPreferences(this);
-27737330 0 AppDomain.CurrentDomain.SetData("DataDirectory", Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); This should work always because Directory.GetCurrentDirectory() may return other directory than the executable one
-12619745 0It's a bit of a mystery, isn't it? Several superficially plausible theories turn out to be wrong on investigation:
So that the POST object doesn't have to implement mutation methods? No: the POST object belongs to the django.http.QueryDict class, which implements a full set of mutation methods including __setitem__, __delitem__, pop and clear. It implements immutability by checking a flag when you call one of the mutation methods. And when you call the copy method you get another QueryDict instance with the mutable flag turned on.
For performance improvement? No: the QueryDict class gains no performance benefit when the mutable flag is turned off.
So that the POST object can be used as a dictionary key? No: QueryDict objects are not hashable.
So that the POST data can be built lazily (without committing to read the whole response), as claimed here? I see no evidence of this in the code: as far as I can tell, the whole of the response is always read, either directly, or via MultiPartParser for multipart responses.
To protect you against programming errors? I've seen this claimed, but I've never seen a good explanation of what these errors are, and how immutability protects you against them.
In any case, POST is not always immutable: when the response is multipart, then POST is mutable. This seems to put the kibosh on most theories you might think of. (Unless this behaviour is an oversight.)
In summary, I can see no clear rationale in Django for the POST object to be immutable for non-multipart requests.
A problem I ran into was related to the ordering in Application_Start(). Note the order of Web API configuraton below:
This does NOT work
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); GlobalConfiguration.Configure(WebApiConfig.Register); } This does work
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); }
-11785670 0 Closing generic handlers before logging and other functionalities I am working on a high volumne API that needs to provide substantial logging for reporting purposes. In order to limit the effect of this logging functionality to the api users, I would like to finish the request, and then start logging all the stuff that needs to be logged.
Will flush, then close cause this to occur or will the client system wait until all the "Business Stuff " (BS for short) is complete?
-10056284 0I would suggest using MVC Display/EditorTemplates rather than a helper in this context. With templates you get automatic collection support, and you can use a strongly typed model.
-19683021 0The turbolinks gem caused the problem.
Solved by following these tips here: http://reed.github.io/turbolinks-compatibility/twitter.html
http://reed.github.io/turbolinks-compatibility/facebook.html
-3225534 0 Where do I start with reporting services in SQL Server 2008 R2I have installed Visual Web Developer Express 2010, and SQL Server 2008 R2 Express with advanced services.
How can I write reports to use with reporting services?
Do I need to install Visual Studio C# Express 2010 for instance?
Thanks.
-34711569 0 node.js: Is it possible to pass jQuery code in server-side html response?var server = http.createServer(function (req, res) { if (req.method.toLowerCase() == 'get') { displayForm(res); } else if (req.method.toLowerCase() == 'post') { //processAllFieldsOfTheForm(req, res); processFormFieldsIndividual(req, res); } }); function displayForm(res) { fs.readFile('form.html', function (err, data) { res.writeHead(200, { 'Content-Type': 'text/html', 'Content-Length': data.length }); res.write(data); res.end(); }); } I am following this example, where form.html contains only html blocks.
My question is, can't jQuery/javaScript code be merged with form.html in server response?
I have tried both external and internal js code but to no avail.
You may be able to parse it from the __FILE__ magic constant. I don't have any Windows computer, but I guess it will be the first character. So this may work:
$drive = substr(__FILE__, 0, 1);
-3653698 0 I kept this project as a bookmark a while ago : http://code.google.com/p/gaedjango-ratelimitcache/
Not really an answer to your specific question but maybe it could help you get started.
-19876693 0(This was originally a comment)
You seem to miss what the point of pseudo code is. Pseudo code is neither standardized nor somewhat defined. In general it is just a code-like representation of an algorithm, while maintaining a high level and readability. You can write pseudo code in whatever form you like. Even real Python code could be considered pseudo code. That being said, there are no thing disallowed in pseudo code; you can even write prose to explain something that happens. For example in the inner-most loop, you could just write “swap value1 and value2”.
This is approximately how I would transform your Python code into pseudo-code. I tend to leave out all language specific stuff and focus just on the actual algorithmic parts.
Input: list: Array of input numbers FOR j = 0 to length(list): FOR i = 0 to length(list)-1: if list[i] > list[i+1]: Swap list[i] and list[i+1] OUTPUT ordered list So is it okay to use lists, tuples, dictionaries in a pseudocode, even if they are not common to all programming languages?
Absolutely! In more complex algorithms you will even find things like “Get minimum spanning tree for XY” which would be a whole different problem for which again multiple different solutions exist. Instead of specifying a specific solution you are keeping it open to the actual implementation which algorithm is to be used for that. It usually does not matter for the algorithm you are currently describing. Maybe later when you analyze your algorithm, you might mention things like “There are algorithms known for this who can do this in O(log n)” or something, so you just use that to continue.
-19572181 0 CSS Generated Content allows us to insert and move content around a document. We can use this to create footnotes, endnotes, and section notes, as well as counters and strings, which can be used for running headers and footers, section numbering, and lists. -2444704 0The construct you are looking for is called column_property. You could use a secondary mapper to actually replace the amount column. Are you sure you are not making things too difficult for yourself by not just storing the negative values in the database directly or giving the "corrected" column a different name?
from sqlalchemy.orm import mapper, column_property wrongmapper = sqlalchemy.orm.mapper(Transaction, Transaction.__table, non_primary = True, properties = {'amount': column_property(case([(Transaction.transfer_account_id==1, -1*Transaction.amount)], else_=Transaction.amount)}) Session.query(wrongmapper).filter(...)
-24873633 0 Here's one possible way of reading a file and getting just the "chunks":
import java.io.*; import java.util.Scanner; public class ScanXan { public static void main(String[] args) throws IOException { Scanner s = null; try { s = new Scanner(new BufferedReader(new FileReader("xanadu.txt"))); while (s.hasNext()) { System.out.println(s.next()); } } finally { if (s != null) { s.close(); } } } } You can take a look at the Java Scanner Tutorial for other ideas.
-18036788 0First of all per K&R, the answer is yes.
At the conceptual level an array name is a ptr, they are absolutely the same thing, CONCEPTUALLY.
How a compiler implements an array is up to the compiler. This is the argument between those who say they are not the same thing and those who say they are.
A compiler could implement int a[5] as the pointer a to an unnamed chunk of storage that can contain 5 integers. But they don't. It is easier for a compiler writer to generate code for a simple array and then fudge on the pointer-ness of a.
Anyway, conceptually, the data area allocated by the int a[5]; statement can be referenced by the ptr a or it can be referenced by the pointer produced by the &a[0] statement.
I would like to hide an expanded tableviews label, when the cell is expanded and hide a button when it is collapsed. I have my cell implementation in another class, with the property of the label and the button in the header. The problem is that when I call these cell methods in the ExpandedViewController, the code goes into the method, but it won't change the properties behaviour. Could you possibly help me with this issue?
Thank you
ExpandedCell.h
@property (nonatomic, retain) IBOutlet UILabel *lblTitle; @property (strong, nonatomic) IBOutlet UIButton *setTime; ExpandedCell.m
(void)setIfHidden:(BOOL)showIfHidden { if (showIfHidden) { [self.lblTitle setHidden:YES]; [self.setTime setHidden:NO]; } else { [self.lblTitle setHidden:NO]; [self.setTime setHidden:YES]; } } ExpandedViewController.m
import ExpandedCell.h .
(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { if ([indexPath isEqual:self.expandedIndexPath]) { return CELL_HEIGHT_EXPANDED; } else { return CELL_HEIGHT_COLLAPSED; } } (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { self.expandedIndexPath = ([self.expandedIndexPath isEqual:indexPath]) ? nil : indexPath; ExpandedCell *hideCell = [[ExpandedCell alloc] init]; showIfHidden = YES; [hideCell setIfHidden:showIfHidden]; [tableView beginUpdates]; [tableView endUpdates]; [tableView deselectRowAtIndexPath:indexPath animated:YES]; }
-997954 0 I'm not sure why you would want to use a hill-climbing algorithm, since Djikstra's algorithm is polynomial complexity O( | E | + | V | log | V | ) using Fibonacci queues: http://en.wikipedia.org/wiki/Dijkstra's_algorithm
If you're looking for an heuristic approach to the single-path problem, then you can use A*: http://en.wikipedia.org/wiki/A*_search_algorithm
but an improvement in efficiency is dependent on having an admissible heuristic estimate of the distance to the goal. http://en.wikipedia.org/wiki/A*_search_algorithm
-14920406 0Heres a couple of better syntax options:
<?php if(isset($_SESSION['guest2First'])){ $name = $_SESSION["guest2First"]. (isset($_SESSION["guest2Middle"])?' '.$_SESSION["guest2Middle"]:null). (isset($_SESSION["guest2Last"])?' '.$_SESSION["guest2Last"]:null); ?> <tr> <td><input type="text" name="guest2Ticket" id="guest2Ticket" onblur="isTicketNumber(this);" size ="22"/></td> <td><?php echo $name;?></td> </tr> <?php }?> Or
<?php if(isset($_SESSION['guest2First'])){ echo '<tr>', '<td><input type="text" name="guest2Ticket" id="guest2Ticket" onblur="isTicketNumber(this);" size ="22"/></td>', '<td>'.$name.'</td>', '</tr>'; } ?>
-38865180 0 Excel evaluates both parts of an OR expression independent if the first part is true. So A1<0 and therefore the OR function result in an error if A1 contains an error.
You can try something like that:
IF(ISERROR(A1),"Y",IF(A1<0,"Y","N"))
-30795069 0 While you could use AntiSamy to do it, I don't know how sensible that would be. Kinda defeats the purpose of it's flexibility, I think. I'd be curious about the overhead, even if minimal, to running that as a filter over just a regex.
Personally I'd probably opt for the regex route in this scenario. Your example appears to only strip the brackets. Is that acceptable in your situation? (understandable if it was just an example) Perhaps use something like this:
reReplace(string, "<[^>]*>", "", "ALL");
-24947366 0 Ruby on Rails: How to change the Foriegn Key values on a collection_select drop down? I have a drop down on my form which is a foreign key to another table:
<div class="field"> <td><%= f.label "#{column_name}" %></td> <td><%= f.collection_select "#{column_name}", Table.all, :id, :message_id %></td> </div> "Table" has a column "message_id" which is a foreign_key to a different table "Messages".
The "Messages" table contains all the text/strings in my application.
When I load this code on my page it will give me a drop down list of all records but it will only show foreign key ID numbers pointing to the "Messages" table.
How can I change the foreign key ID numbers in the drop down to switch with message content I have on my Messages table?
-34460204 0import re sample = open ('text_numbers.txt') total =0 dignum = 0 for line in sample: line = line.rstrip() dig= re.findall('[0-9]+', line) if len(dig) >0: dignum += len(dig) linetotal= sum(map(int, dig)) total += linetotal print 'The number of digits are: ' print dignum print 'The sum is: ' print total print 'The sum ends with: ' print total % 1000
-17019288 0 well for standard HTML such as head,footer,sidebars or whatever .. there is Partials the example explains everything ..
Trying to create a data.frame like this:
a = "foo" bar = data.frame(a = 1:3) But the name of the column is a, not foo:
> bar a 1 1 2 2 3 3 The column can be renamed after creating data.frame, but how to easily assign it's name by a variable just in the same data.frame command?
-5765020 0Mocha is a traditional mocking library very much in the JMock mould. Stubba is a separate part of Mocha that allows mocking and stubbing of methods on real (non-mock) classes. It works by moving the method of interest to one side, adding a new stubbed version of the method which delegates to a traditional mock object. You can use this mock object to set up stubbed return values or set up expectations of methods to be called. After the test completes the stubbed version of the method is removed and replaced by the original.
for more detail with example
http://jamesmead.org/blog/2006-09-11-the-difference-between-mocks-and-stubs
-5077413 0Try this:
DateTime dt = DateTime.ParseExact(strDate, "MMM dd, yyyy", CultureInfo.InvariantCulture);
-12465639 0 show progress bar when pushing using git I'm trying to push a large file to a git repository using git push -u origin master but it is failing on the half way. It would be of great help if I can see when it fails. Is there a way to show something like a progress bar in git push?
Edit: Doing some brute force I was able to push the file at last on my 7th or 8th trial but I'm still curious about the question.
-33707795 0First, classes, enums, and structs are terminated with ';' following the closing bracket (or scope). i.e.
struct St { .... };//<--- end of scope terminator Next, what exactly are you trying to do following this bit? I'm guessing you're trying to define cases of it for use, but you're going about it entirely wrong. You need to have a member in the struct to set a value to, this can be an instance of the struct itself. Like this...
struct St { St element; }; Then you can set a value to the structs member, but in this particular instance you're probably gonna want some more data members for this sturct to be of any use...
struct St { char value; St element; St(char value, St element) // struct constructor : this->value(value), this->element(element){} // init list }; Now you can use the struct in the rest of your code simply by calling it by its identifier, which in this case would be 'St'.
Although, for what you're trying to achieve (I could be wrong) would be better suited for an enumerated value, which is (basically) a way of defining your own primitive, switchable, variable type. An example of where an enum would be useful would be something like...
const int MON = 0, TUE = 1, ....// rather than using "const int's" // define them as enumerations enum Day {MON,TUE,WED,THU,FRI,SAT,SUN}; /*each enum is assigned an integer ordinal that corresponds to its location as it is declared, so MON == 0, TUE == 1, and so on. You can alternatively assign your own value to it in an instance where the default ordinal would not be useful, for instance if you wanted them as characters...*/ enum Foo {Bar = 'B', Qat = 'Q', ...}; // or enum Ratings {PG13 = 13, R = 18, ...}; You would probably benefit from a resource like:
http://www.tutorialspoint.com/cplusplus/cpp_references.htm
or
-183197 0Just like Perl,
loop1: for (var i in set1) { loop2: for (var j in set2) { loop3: for (var k in set3) { break loop2; // breaks out of loop3 and loop2 } } } as defined in EMCA-262 section 12.12. [MDN Docs]
Unlike C, these labels can only be used for continue and break, as Javascript does not have goto (without hacks like this).
You can find the extra braces by making use of stack as below:
public static void main(final String[] args) { Stack<String> stack = new Stack<String>(); File file = new File("InputFile"); int lineCount = 0; try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line; while ((line = br.readLine()) != null) { lineCount++; for (int i = 0; i < line.length(); i++) { if (line.charAt(i) == '{') { stack.push("{"); } else if (line.charAt(i) == '}') { if (!stack.isEmpty()) { stack.pop(); } else { System.out.println("Extra brace found at line number : " + lineCount); } } } } if (!stack.isEmpty()) { System.out.println(stack.size() + " braces are opend but not closed "); } } catch (Exception e) { e.printStackTrace(); } }
-28758654 0 This is the correct way to use $http service and scope variables.
<html ng-app="people"> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <script type="text/javascript"> var app = angular.module('people', []); app.controller('firstController', ["$scope", "$http", function ($scope, $http) { $scope.store = {}; $scope.store.products = []; $http.get('http://api.randomuser.me').success(function(data){ $scope.user = data.results[0].user; }) }]); </script> </head> <body> <div id="clk" style="background-color: indigo; widht: 100px; height: 100px"></div> <div ng-controller="firstController"> {{ user.email}} </div> </body> </html>
-35259544 0 QT5/QSql bindValue query doesn't work I have a query made with QSql
query.prepare("SELECT id,title,content FROM posts ORDER BY :field :order LIMIT :limit OFFSET :offset"); query.bindValue(":field",QVariant(field)); query.bindValue(":order",order); query.bindValue(":limit",limit); query.bindValue(":offset",offset); I use order value as "DESC" but it doesn't work properly. But , when I do
query.prepare("SELECT id,title,content FROM posts ORDER BY "+field+" "+order+" LIMIT :limit OFFSET :offset"); query.bindValue(":limit",limit); query.bindValue(":offset",offset); it works fine and I don't know why. The values are of the same type ( QString and int ). Any suggestions ?
Thanks.
-4460050 0Haskell, because once you've learned Haskell, you will love it. And then, you will be able to learn Common LISP. However, if your editor is Emacs, then go start with Lisp.
-40495193 0 Passing Datomic console options via fileSomeone noticed that on one of our Datomic transactor boxes, our process running the Datomic console is exposing database credentials.
Here is what our we get back when running ps aux | grep datomic (linebreaks added for readability):
[ian@testtransactor ~]$ ps aux | grep datomic datomic 18372 0.8 55.7 6898068 4495820 ? Sl Nov01 31:20 java -server -cp lib/*:datomic-transactor-pro-0.9.5394.jar:samples/clj:bin:resources -Xmx4g -Xms4g -Ddatomic.printConnectionInfo=false -Doracle.net.tns_admin=/usr/lib/oracle/11.2/client64/network/admin -Dgraphite.host=graphite -Dgraphite.port=2003 -Dgraphite.prefix=datomic.testransactor clojure.main --main datomic.launcher /opt/datomic-pro-0.9.5394/config/transactor.properties root 18821 0.2 10.2 3503992 826664 ? Sl May20 504:04 java -server -Xmx1g -Doracle.net.tns_admin=/usr/lib/oracle/11.2/client64/network/admin -cp lib/console/*:lib/*:datomic-transactor-pro-0.9.5327.jar:samples/clj:bin:resources clojure.main -i bin/bridge.clj --main datomic.console -p 3035 dev datomic:sql://?jdbc:oracle:thin:USERNAME/PASSWORD@DB_SID Our security team would prefer that the password be passed to the console process via a properties file, like we do with the transactor. Unfortunately, just mirroring it with clojure.main -i bin/bridge.clj --main datomic.console /opt/datomic-pro-0.9.5394/config/console.properties doesn't work. Does anyone have suggestions on how to set this up?
To get a dynamic select from the appropriate table, you can use a dynamic SQL finder.
In this example, we select from a table named 'albums', and fabricate a column 'name' to hold the values. These will be returned in the 'Album' model object. Change any of these names to suit your needs.
Album.find_by_sql("SELECT DISTINCT SUBSTR(name,1,1) AS 'name' FROM albums ORDER BY 1") Note that you can't use the Album model objects for anything except querying the 'name' field. This is because we've given this object a lobotomy by only populating the 'name' field - there's not even a valid 'id' field associated!
-35176703 0I have the same problem. The facebook pixel analytic page shows all traffic, regardless if they clicked an ad link or not. What are we doing wrong.?
-33369903 0What version of Opentaps are you running ? did you clone from the master git repository ?
are you trying to compile the code in the ide? I suggest you run ./ant inside the project and don't use the ide to compile
-29889112 0 where the behavior of private and static method is different from only private methodAs for my understanding:
When a method is static it is
I never found any other behaviour of static either at compile time or runtime. Is there any?
When a method is private it is
For example the hugeCapacity() method in the ArrayList class.
private static final int DEFAULT_CAPACITY = 10; private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) // overflow throw new OutOfMemoryError(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; } Since there are in Java private+static method exist. Why their need occurs. Is it for restriction purpose, to restrict access of non static variables inside a method?
-22722188 0.form-control[disabled] { background-color:white; }
-24274017 0 This is the solution, I didn't change anything in the original code and script:
<div id="content"> <div id="tab1">@{ Html.RenderAction("TabbedIndex", "Stuff", new { claimed = false }); }</div> <div id="tab2">@{ Html.RenderAction("TabbedIndex", "Stuff", new { claimed = true }); }</div> </div>
-40900686 1 Make anaconda jupyter notebook auto save .py script I would like to simply be able to launch the jupyter notebook from Anaconda and have it automatically save a .py script when I save the .ipynb. I tried modifying the jupyter-notebook-script.py in the Anaconda3/envs/env_name/Scripts/ but that wasn't the right way. I know I want to set the post-save-hook=True somewhere.
as someone who spent time looking for such a solution for my company's product--I can tell you that you are not going to find one. It does not exist. Sorry, dude. :(
-5689570 0This behaviour of Joda Time Contrib is fixed in my project Usertype for Joda Time and JSR310. See http://usertype.sourceforge.net/ which is practically otherwise a drop in replacement for JodaTime Hibernate.
I have written about this issue: http://blog.jadira.co.uk/blog/2010/5/1/javasqldate-types-and-the-offsetting-problem.html
Hope this helps,
Chris
-32001570 0 Issue with experimental gradle: The android plugin must be applied to the projectI'm trying to run some native code with the NDK in Android Studio. I have followed the steps shown HERE to use the experimental Gradle, but obviously it's not all going smoothly. I'm getting this error: The android or android-library plugin must be applied to the project
Here is my gradle file:
apply plugin: 'com.android.model.application' apply plugin: 'com.neenbedankt.android-apt' apply plugin: 'io.fabric' model { android { compileSdkVersion = 22 buildToolsVersion = "22.0.1" android.ndk { moduleName = "test" } defaultConfig.with { applicationId = "com.shaperstudio.dartboard" minSdkVersion.apiLevel = 15 targetSdkVersion.apiLevel = 22 versionCode = 1 versionName = "1.0" } } android.buildTypes { release { minifyEnabled = false proguardFiles += file('proguard-rules.pro') } } packagingOptions { exclude = 'META-INF/services/javax.annotation.processing.Processor' } } repositories { maven { url "https://jitpack.io" } maven { url 'https://maven.fabric.io/public' } } buildscript { repositories { jcenter() maven { url 'https://maven.fabric.io/public' } } dependencies { classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4' classpath 'io.fabric.tools:gradle:1.+' } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:22.2.0' compile 'com.android.support:recyclerview-v7:22.2.0' compile 'com.android.support:design:22.2.0' compile 'com.jakewharton:butterknife:6.1.0' compile 'de.greenrobot:eventbus:2.4.0' apt 'com.bluelinelabs:logansquare-compiler:1.1.0' compile 'com.bluelinelabs:logansquare:1.1.0' compile 'com.birbit:android-priority-jobqueue:1.3' compile 'com.squareup.picasso:picasso:2.5.2' compile 'com.facebook.android:facebook-android-sdk:4.1.0' compile 'com.parse.bolts:bolts-android:1.+' compile fileTree(dir: 'libs', include: '*.jar') compile('com.crashlytics.sdk.android:crashlytics:2.4.0@aar') { transitive = true; } } Any help as to why I'm getting this error would be appreciated
-28000225 0 How to return a value from a range if cell contains that valueI have a list of Names (First and Surname) in A:A. I also have a range called 'Surnames'. How can I apply a formula so that B:B returns the surname only of A:A if that name is found in the range 'Surnames'.
I other words, I want to check a cell in A1, if part of this cell value contains a name listed in my range of surnames, return the surname that A1 include in B1.
I hope this makes sense, and thank you in advanced :)
-7448853 0I have an internationalized product. No translation has been done, but the strings are all externalized, so if we had a desire to ship the product localized for a specific country we could get the files translated, have the product tested, and ship it for use natively in that country.
For now the fully internationalized product is all english, but the coding is all done. If someone were to attempt to check in code that was not proper the reviewer could rightly reject it on the grounds that it is not internationalized, and would render the product unable to be fully localized.
But since no testing has been done then it really is not internationalized fully yet ...
-38048090 0It's a bug in iex. I've tracked down and fixed it: https://github.com/elixir-lang/elixir/pull/4895
Before,I use
<select id="queryUser" parameterType="userInfo"> select * from uc_login_${tableSuffix} </select> userInfo:{ private String tableSuffix; } and I create userInfo with tableSuffix like
new DateTime().getYear() + "_" + new DateTime().getMonthOfYear(); and now I select from uc_login_nowYear_nowMonth(uc_login_2015_12). Now,I don't want create tabkeSuffix by myself,I want Mybatis help me to dynamic create sql in xml. How can I do that?
-34128285 0One way would be to:
a) Copy your JSON to Clipboard (CTRL+C)
b) On a Visual Studio class, click on EDIT-> Paste Special -> Paste JSON as classes. This will create the classes equivalent of your JSON for you. Your main object would be named as "Rootobject" and you can change this to whatever name you want.
c) Add System.Web.Extensions to your references
d) You can convert your JSON to class like so:
JavaScriptSerializer serializer = new JavaScriptSerializer(); Rootobject rootObject = serializer.Deserialize<Rootobject>(JsonString); Where JsonString is your API output.
I'm trying to create a talent calculator for myself, and the entire first sheet calls to a Data sheet that does all the background work. On the excel sheet itself, everything calls to INDEX(TableName,Row,Column) because it's much easy to keep track of and I find I often have to move data around while working on it so handling Names is easier than handling cell references.
However, I also use VBA on this sheet, and I'm rather new to it. Instead of, for example, using Range("C1"), if C1 was part of table TableOne, would there be a way to reference it like in the Excel formulas such as INDEX(TableOne,1)?
-15129833 0 Suppress Page header when there is no data in Details sectionsI am using a datatable to load the data for the crystal report. Based on the data filtered by the user in the DataGridview and clicking on Print will display the filtered data in Report.
All is fine.I have done this.When there is no data in the Details section I am suppressing it using the below formula in the suppress.
Shared NumberVar PageofLastField; If OnLastRecord then PageofLastField = PageNumber; In the header section when there is no data in Details section supress page header.Below is the formula used.
(Reference Crystal Reports - Suppress a Page Header if the page has 0 records)
Shared NumberVar PageofLastField; PageofLastField := PageofLastField; if pageofLastfield <> 0 and PageNumber > PageofLastField THEN TRUE ELSE FALSE Below is the image of the crystal report.
When I click PRINT button in the front end. When there is no data in Details section the Page header is displayed.
Below image is the Second page of the report where there are no records and summary is displayed.

If in the header section if I use the below formula
OnLastRecord AND Count({PaymentReportTable.InvID}) <> 1 In the Second Page even if the records are displayed Pageheader is not displayed.I understand it becos the formula says it all.

I have created around 12 Crystal reports and I am facing the same problem in all of them.
Please advice.
-29988115 0You are not using postdata while sending request:
var postdata = "{ \"version\": \"1.0.1\", \"observations\": [ { \"sensor\": \"TISensorTag_temp_01\", \"record\": [ { \"starttime\": \"" + formatDate(new Date()) + "\", \"output\": [ { \"name\": \"ObjTemp\", \"value\": \"" + objtemp + "\" }, { \"name\": \"AmbTemp\", \"value\": \"" + ambtemp + "\" } ] } ] } ] }"; options.data = postdata; //added data to post request request.post(options, callback); About Callback, you have initialized callback and in your case you don't have to pass callback as function parameter. Try use following:
async.series([ /*some functions*/ function() { setTimeout(callback, 2000); loop(); } ])
-840421 0 You can check if its a digit:
char c; scanf( "%c", &c ); if( isdigit(c) ) printf( "You entered the digit %c\n", c );
-11020766 0 I really liked Phaxmohdem solution, so I added a bit more to it. I hope others continue to improve this. =)
<NotepadPlus> <UserLang name="X12" ext=""> <Settings> <Global caseIgnored="no" /> <TreatAsSymbol comment="no" commentLine="no" /> <Prefix words1="no" words2="no" words3="no" words4="no" /> </Settings> <KeywordLists> <Keywords name="Delimiters">000000</Keywords> <Keywords name="Folder+"></Keywords> <Keywords name="Folder-"></Keywords> <Keywords name="Operators">* : ^ ~ +</Keywords> <Keywords name="Comment"></Keywords> <Keywords name="Words1">ISA IEA GS GE ST SE</Keywords> <Keywords name="Words2">AAA ACT ADX AK1 AK2 AK3 AK4 AK5 AK6 AK7 AK8 AK9 AMT AT1 AT2 AT3 AT4 AT5 AT6 AT7 AT8 AT9 AT8 AT9 B2 B2A BEG BGN BHT BPR CAS CL1 CLM CLP CN1 COB CR1 CR2 CL3 CL4 CR5 CR6 CRC CTX CUR DMG DN1 DN2 DSB DTM DTP EB EC ENT EQ FRM G61 G62 HCP HCR HD HI HL HLH HSD ICM IDC III IK3 IK4 IK5 INS IT1 K1 K2 K3 L3 L11 LIN LQ LUI LX MEA MIA MOA MPI MSG N1 N2 N3 N4 NM1 NTE NX OI PAT PER PLA PLB PO1 PRV PS1 PWK QTY RDM REF RMR S5 SAC SBR SLN STC SV1 SV2 SV3 SV4 SV5 SVC SVD TA1 TOO TRN TS2 TS3 UM</Keywords> <Keywords name="Words3">LS LE</Keywords> <Keywords name="Words4">00 000 0007 001 0010 0019 002 0022 003 004 00401 004010 004010X061 004010X061A1 004010X091 004010X091A1 004010X092 004010X092A1 004010X093 004010X093A1 004010X094 004010X094A1 004010X095 004010X095A1 004010X096 004010X096A1 004010X098 004010X098A1 005 00501 005010 005010X212 005010X217 005010X218 005010X220 005010X220A1 005010X221 005010X221A1 005010X222 005010X222A1 005010X223 005010X223A1 005010X223A2 005010X224 005010X224A1 005010X224A2 005010X230 005010X231 005010X279 005010X279A1 006 007 0078 008 009 01 010 011 012 013 014 015 016 017 018 019 02 020 021 022 023 024 025 026 027 028 029 03 030 031 032 035 036 04 05 050 06 07 08 09 090 091 096 097 0B 0F 0K 102 119 139 150 151 152 18 193 194 196 198 1A 1B 1C 1D 1E 1G 1H 1I 1J 1K 1L 1O 1P 1Q 1R 1S 1T 1U 1V 1W 1X 1Y 1Z 200 232 233 270 271 276 277 278 286 290 291 292 295 296 297 2A 2B 2C 2D 2E 2F 2I 2J 2K 2L 2P 2Q 2S 2U 2Z 30 300 301 303 304 307 31 314 318 330 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 356 357 36 360 361 374 382 383 385 386 388 393 394 3A 3C 3D 3E 3F 3G 3H 3I 3J 3K 3L 3M 3N 3O 3P 3Q 3R 3S 3T 3U 3V 3W 3X 3Y 3Z 40 405 41 417 431 434 435 438 439 441 442 444 446 45 452 453 454 455 456 458 46 461 463 471 472 473 474 480 481 484 492 4A 4B 4C 4D 4E 4F 4G 4H 4I 4J 4K 4L 4M 4N 4O 4P 4Q 4R 4S 4U 4V 4W 4X 4Y 4Z 539 540 543 573 580 581 582 598 5A 5B 5C 5D 5E 5F 5G 5H 5I 5J 5K 5L 5M 5N 5O 5P 5Q 5R 5S 5T 5U 5V 5W 5X 5Y 5Z 607 636 695 6A 6B 6C 6D 6E 6F 6G 6H 6I 6J 6K 6L 6M 6N 6O 6P 6Q 6R 6S 6U 6V 6W 6X 6Y 70 71 72 738 739 74 77 771 7C 82 820 831 834 835 837 85 850 866 87 8H 8U 8W 938 997 999 9A 9B 9C 9D 9E 9F 9H 9J 9K 9V 9X A0 A1 A172 A2 A3 A4 A5 A6 A7 A8 A9 AA AAE AAG AAH AAJ AB ABB ABC ABF ABJ ABK ABN AC ACH AD ADD ADM AE AF AG AH AI AJ AK AL ALC ALG ALS AM AN AO AP APC APR AQ AR AS AT AU AV AX AY AZ B1 B2 B3 B4 B6 B680 B7 B9 BA BB BBQ BBR BC BD BE BF BG BH BI BJ BK BL BLT BM BN BO BOP BP BPD BQ BR BS BT BTD BU BV BW BX BY BZ C1 C2 C3 C4 C5 C6 C7 C8 C9 CA CAD CB CC CCP CD CE CER CF CG CH CHD CHK CI CJ CK CL CLI CLM01 CM CN CNJ CO CON CP CQ CR CS CT CV CW CX CY CZ D2 D3 D8 D9 D940 DA DB DCP DD DEN DEP DG DGN DH DI DJ DK DM DME DN DO DP DQ DR DS DT DX DY E1 E1D E2 E2D E3 E3D E5D E6D E7 E7D E8 E8D E9 E9D EA EAF EBA ECH ED EI EJ EL EM EMP EN ENT01 EO EP EPO ER ES ESP ET EV EW EX EXS EY F1 F2 F3 F4 F5 F6 F8 FA FAC FAM FB FC FD FE FF FH FI FJ FK FL FM FO FS FT FWT FX FY G0 G1 G2 G3 G4 G5 G740 G8 G9 GB GD GF GH GI GJ GK GM GN GO GP GR GW GT GY H1 H6 HC HE HF HH HJ HLT HM HMO HN HO HP HPI HR HS HT I10 I11 I12 I13 I3 I4 I5 I6 I7 I8 I9 IA IAT IC ID IE IF IG IH II IJ IK IL IN IND IP IR IS IV J1 J3 J6 JD JP KG KH KW L1 L2 L3 L4 L5 L6 LA LB LC LD LI LM LOI LR LT LU LTC LTD M1 M2 M3 M4 M5 M6 M7 M8 MA MB MC MD ME MED MH MI MJ ML MM MN MO MOD MP MR MRC MS MSC MT N5 N6 N7 N8 NA ND NE NF NH NI NM109 NL NN NON NQ NR NS NT NTR NU OA OB OC OD ODT OE OF OG OL ON OP OR OT OU OX OZ P0 P1 P2 P3 P4 P5 P6 P7 PA PB PC PD PDG PE PI PID PL PN PO POS PP PPO PQ PR PRA PRP PS PT PU PV PW PXC PY PZ Q4 QA QB QC QD QE QH QK QL QM QN QO QQ QR QS QV QY R1 R2 R3 R4 RA RB RC RD8 RE REC RET RF RGA RHB RLH RM RN RNH RP RR RT RU RW RX S1 S2 S3 S4 S5 S6 S7 S8 S9 SA SB SC SD SEP SET SFM SG SJ SK SL SP SPC SPO SPT SS STD SU SV SWT SX SY SZ T1 T10 T11 T12 T2 T3 T4 T5 T6 T7 T8 T9 TC TD TE TF TJ TL TM TN TNJ TO TPO TQ TR TRN02 TS TT TTP TU TV TWO TZ UC UH UI UK UN UP UPI UR UT V1 V5 VA VER VIS VN VO VS VV VY W1 WA WC WK WO WP WR WU WW X12 X3 X4 X5 X9 XM XN XP XT XV XX XX1 XX2 XZ Y2 Y4 YR YT YY Z6 ZB ZH ZK ZL ZM ZN ZO ZV ZX ZZ</Keywords> </KeywordLists> <Styles> <WordsStyle name="DEFAULT" styleID="11" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /> <WordsStyle name="FOLDEROPEN" styleID="12" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /> <WordsStyle name="FOLDERCLOSE" styleID="13" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /> <WordsStyle name="KEYWORD1" styleID="5" fgColor="0000FF" bgColor="FFFFFF" fontName="" fontStyle="1" /> <WordsStyle name="KEYWORD2" styleID="6" fgColor="800000" bgColor="FFFFFF" fontName="" fontStyle="1" /> <WordsStyle name="KEYWORD3" styleID="7" fgColor="00FF00" bgColor="FFFFFF" fontName="" fontStyle="1" /> <WordsStyle name="KEYWORD4" styleID="8" fgColor="8000FF" bgColor="FFFFFF" fontName="" fontStyle="0" /> <WordsStyle name="COMMENT" styleID="1" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /> <WordsStyle name="COMMENT LINE" styleID="2" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /> <WordsStyle name="NUMBER" styleID="4" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /> <WordsStyle name="OPERATOR" styleID="10" fgColor="FF00FF" bgColor="FFFFFF" fontName="" fontStyle="0" /> <WordsStyle name="DELIMINER1" styleID="14" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /> <WordsStyle name="DELIMINER2" styleID="15" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /> <WordsStyle name="DELIMINER3" styleID="16" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /> </Styles> </UserLang> </NotepadPlus>
-6063744 0 Ajax client for a CXF service I'm new to CXF, and I was trying to implement a CFX client in Ajax. I had already implemented a client in Java but now I need to implement a client-side application to access CXF. I'm not even sure that it's possible to do that (Accessing CXF directly from client-side). If it's possible then kindly direct me to some ajax code. If not, then please help me with your ideas for a web-based CFX client. Thanks
-31940324 0 vb.net to pull data from Excel Data GridViewI have 78 excel columns and I have 5 datagridviews.
How do I make connection?
-761352 0 Django QuerySet orderI am new to both django and python but I am beginning to get a grasp on things. I think.
I have this problem and I can not seem to find an answer to it. (Though I assume it is really simple and the limiting factors are my google skills and lack of python/django knowledge)
The scenario:
a user can opt in to recieve temporary job openings at any number of stores he or she chooses.
I would like to present a list of upcoming job openings (StoreEvents) sorted by the DateField only.
Example: Store A - 2009-04-20 Store B - 2009-04-22 Store A - 2009-04-23 Atm I am stuck with presenting the data first sorted by store then by date since I am obviously accessing the StoreEvents through the Store model.
Example: Store A - 2009-04-20 Store A - 2009-04-23 Store B - 2009-04-22 So my question is: Is it possible to create a QuerySet that looks like the first example and how do I do it?
Examples of related models included:
class Store(models.Model): class StoreEvent(models.Model): info = models.TextField() date = models.DateField() store = models.ForeignKey(Store, related_name='events') class UserStore(models.Model): user = models.ForeignKey(User, related_name='stores') store = models.ForeignKey(Store, related_name='available_staff') Edit:
The following SQL does the trick but I still can't figure out how to do it in django:
SELECT * FROM store_storeevent WHERE store_id IN ( SELECT store_id FROM profile_userstore WHERE user_id =1 ) ORDER BY date
-17492192 0 With validation efficiency is not usually the concern. There are two types of validation that you should be concerned with:
Skipping over either of these is a very very good way to end up with either a hacked or badly broken application.
If you're using ASP.net there are a plethora of libraries (mostly from Microsoft) to do the former, Anti-XSS lib etc.
The latter would be most efficiently preformed in your shared business logic in the entities themselves. E.G your user entity should not allow an age of -1.
-36843106 0You can use position: absolute and transform: translate()
nav { position: relative; background: #2196F3; height: 50px; } .mdl-layout-title { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); } <nav> <span class="mdl-layout-title navbar">Title</span> </nav> I'm creating a Windows Add/Remove Programs application in Qt 5.4 and I'm becaming crazy to solve a little "puzzle":
My application (APP_0) runs another application (APP_1) and waits for this APP_1 until it terminates.
APP_1 is an uninstaller (i.e. uninstall.exe) and I've not the source code of the APP_1, just of my Qt APP_0.
APP_1, instead of doing the uninstall job, it simply copies itself somewhere in the filesystem (I saw as Au_.exe but other apps could use different names and locations), runs this copy of itself (APP_2) and terminates.
The APP_2 has a GUI and the job I'm waiting for (uninstall) is demanded to the final user of the running APP_2.
In this situation my application (APP_0) stops waiting for APP_1 pratically immediately (because it launches APP_1 and waits for APP_1). But to work properly, obviously, I need to know instead when APP_2 is terminated...
So the question is: is there a way (using some techniques (hooking?)) to know if and when APP_2 terminates?
Note: Consider that the standard Windows Add/Remove Programs utility does the job successfully (it seems it waits for APP_2). You can test this, for example, installing Adobe Digital Edition. Its uninstaller (uninstall.exe) copies itself into a new folder in the User_Local_Temp folder as Au_.exe, runs it and terminates. But the OS utility successfully waits for Au_.exe and only after it terminates refreshes the list of installed programs.
If this kind of technique (uninstall.exe copies itself somewhere ALWAYS with THE SAME name (Au_.exe) ) the problem could be resolved, obviously, very simply. But I don't think that the name of the copied uninstaller is always the same and also I don't like to assume things I'm not sure are real.
Many thanks in advance
-36362270 0You don't need an SqlDataAdapter and all the infrastructure required to work with if you just have a single value returned by your Stored Procedure. Just use ExecuteScalar
int count = 0; using (var con = new SqlConnection(connectionString)) using (var cmd = new SqlCommand("RunAStoredProc", con)) { cmd.CommandType = CommandType.StoredProcedure; count = (int)cmd.ExecuteScalar(); } Console.WriteLine(count); Console.ReadKey(); However if your really want to use an adapter and a dataset then you can find the result of your query reading the value from the first row and first column from the returned table
int count = Convert.ToInt32(table1.Rows[0][0]); or even (without declaring the table1 variable)
int count = Convert.ToInt32(ds.Tables[0].Rows[0][0]); To discover the difference between the result of the first select statement and the count of rows returned in the second select statement you could write
int allStudents = Convert.ToInt32(ds.Tables[0].Rows[0][0]); int enrolledStudents = ds.Tables[1].Rows.Count; int notEnrolledStudents = allStudents - enrolledStudents;
-3140611 0 Assuming it's a business site:
What's your target market? How long do you expect until you release a working version of your website? If current trends continue, what will be IE6's market share by then? How much profit/value will those users bring? How much will it cost to support those additional users? Unless the costs are far below the profit, then don't bother. Otherwise, it might be a good idea.
If it's not a for-profit site(hobby, for instance), then you probably shouldn't bother, unless there's a really significant IE6 market share in your target market.
By the way, remember to use graceful degradation when possible and use feature detection instead of browser detection. Finally, avoid blocking IE6 users and instead just display a warning saying the website is untested in their browser and suggesting an update(this last piece of advice only applies if you don't plan to support IE6)
-28229830 0You can implement a wrapper for fb.App and override Session method to return IFbSession instead of Facebook.Session.
package main import fb "github.com/huandu/facebook" type IFbApp interface { ExchangeToken(string) (string, int, error) Session(string) IFbSession } type MockFbApp struct { IFbApp } func (myFbApp *MockFbApp) ExchangeToken(token string) (string, int, error) { return "exchangetoken", 1, nil } func (myFbApp *MockFbApp) Session(token string) IFbSession { return &MyFbSession{} } type IFbSession interface { User() (string, error) Get(string, fb.Params) (fb.Result, error) } type MyFbSession struct { IFbSession } func (myFbSession *MyFbSession) User() (string, error) { return "userid", nil } func (myFbSession *MyFbSession) Get(path string, params fb.Params) (fb.Result, error) { return fb.Result{}, nil } type RealApp struct { *fb.App } func (myFbApp *RealApp) Session(token string) IFbSession { return myFbApp.App.Session(token) } func SomeMethod() { Facebook(&MockFbApp{}) Facebook(&RealApp{fb.New("appId", "appSecret")}) } func Facebook(fbI IFbApp) { fbI.ExchangeToken("sometokenhere") fbI.Session("session") } func main() { SomeMethod() }
-1762373 0 The preferred way to interact with a db when using an ORM is not to use queries but to use objects that correspond to the tables you are manipulating, typically in conjunction with the session object. SELECT queries become get() or find() calls in some ORMs, query() calls in others. INSERT becomes creating a new object of the type you want (and maybe explicitly adding it, eg session.add() in sqlalchemy). UPDATE becomes editing such an object, and DELETE becomes deleting an object (eg. session.delete() ). The ORM is meant to handle the hard work of translating these operations into SQL for you.
Have you read the tutorial?
-40267118 0You can create a class no-gutter for your row and remove the margin/padding that's added by bootstrap, like suggested in this post:
.row.no-gutter { margin-left: 0; margin-right: 0; } .row.no-gutter [class*='col-']:not(:first-child), .row.no-gutter [class*='col-']:not(:last-child) { padding-right: 0; padding-left: 0; } .row > div { background: lightgrey; border: 1px solid; } <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <div class="row no-gutter"> <div class="col-md-2"> 1 </div> <div class="col-md-10"> 2 </div> </div> I've set a gray background and a border for demonstration purposes. Watch the result in fullscreen to see, that there is no space anymore between the columns. More information about the predefined margin and padding in Bootstrap can be found here.
-20835797 0using inline-jquery
onkeyup="if($(this).val()==''){ $(this).css({'text-align':'right'})} else{ $(this).css({'text-align':'left'})}"
-10412443 0 The Java final keyword is used in the Java programming language under different conditions and has different implications. For example:
To declare a constant method parameter.
A variable declared as final must have an initialization prior to its usage. This variable cannot be assigned a new value such as (a = b). But if the variable is not of primitive type then its properties can be set using the set methods or any other public fields. This means that the object instance reference cannot be changed but the properties of the object instance can be changed as long as they themselves are not declared final.
To prohibit the parameter being modified in the method where it is being used.
You need to modify web.xml to use the special role ** as indicated here: Authorization section for Jetty Authentication:
access granted to any user who is authenticated, regardless of roles. This is indicated by the special value of "**" for the <role-name> of a <auth-constraint> in the <security-constraint>
So, this is what my security-constraint looks like:
<security-constraint> <web-resource-collection> <web-resource-name>Secured Solr Admin User Interface</web-resource-name> <url-pattern>/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>**</role-name> </auth-constraint> </security-constraint>
-17262932 0 You need to invoke session_start at beginning of each file where session data is accessed.
-8978409 0The spacing is intentional and cannot be changed (without custom drawing the entire thing, which is not so easy in managed code), as WinMo 6.5 and later supposedly moved toward more "finger friendly" UIs.
I realize the link is for a ListView, but the TreeView in CE also supports custom drawing in the same way, and that link is the only custom drawn anything I've seen for the CF.
-21756702 0 WCF service Endpoint X509 certificate IdentityI have service on one machine which I would like to access from another machine. So I need a help with setting the identity of the endpoints because i am getting
The identity check failed for the outgoing message. The expected identity is 'identity(http://schemas.xmlsoap.org/ws/2005/05/identity/right/possessproperty:http://schemas.xmlsoap.org/ws/2005/05/identity/claims/thumbprint)' (http://schemas.xmlsoap.org/ws/2005/05/identity/claims/thumbprint%29%27) for the 'net.tcp:...' target endpoint. My service is configured to use certificate for transport security and validation mode is set to ChainTrust.
What type of identity should I set on the client of this service since I am accessing the service using the ip address of the machine hosting it and not the dns name? More precisely what EndpointIdentity setting should I set to the EndpointAddress when I am setting the service host and what should I use on the client when I am setting the EndpointAddress?
On both client and the service machine the issuer of the certificates used to secure the transport is in the trusted authorities.
-37653196 0 Why isn't the divide() function working in Java BigInteger?I'm attempting to divide the variable 'c' by 2(stored in 'd'). For some reason that doesn't happen. I'm passing 10 and 2 for input right now.
import java.util.*; import java.lang.*; import java.io.*; import java.math.BigInteger; class Ideone { public static void main (String[] args) throws java.lang.Exception { Scanner sc = new Scanner(System.in); BigInteger a = new BigInteger(sc.next()); BigInteger b = sc.nextBigInteger(); BigInteger d = new BigInteger("2"); System.out.println(d); BigInteger c = a.subtract(b); c.divide(d); System.out.println(c); a.subtract(c); System.out.println(a); System.out.println(c); } } Any help would be appreciated. Thanks in advance!
-23863338 0This is a very interesting scenario. While in general, we can change any method which is returning void to return anything else without much impact, main method is a special case.
In earlier programming languages, the return from main method was supposed to return exit values to the OS or calling environment.
But in case of Java (where multi-threading concept case into picture), returning a value from main method would not be right, as the main method returns to JVM instead of OS. JVM then finishes other threads e.g. deamon threads (if any) and performs other exit tasks before exit to OS.
Hence allowing main method to return, would have lead to a false expectation with the developers. hence it is not allowed.
-28945990 0 MVC 4: Create HTML textboxes dynamically with JQUERY and PartialViewResult. How to fill the model if the code is added dynamically?I am creating form input fields with JQUERY like
$('#students').live('change', function () { var value = $(this).val(); if (value) { $.ajax({ type: "GET", timeout: 10000, url: "@Url.Action(MVC.Company.ManageWorkReport.GetStudent())", data: { studentId: value }, cache: false, success: function (data) { if (data) { $("#students tbody").html(data); } }, error: function (xhr, status, error) { alert(xhr.responseText); } }); } return false; }); HTML code to insert data is
@using (Html.BeginDefaultForm(MVC.Company.ManageWorkReport.Create())) { <table class="table table-striped table-bordered bootstrap-datatable datatable" id="students"> <thead> <tr> <th>Ime in Priimek</th> <th>Vrsta</th> <th>Začetek dela</th> <th>Konec dela</th> <th>Enota</th> <th>Cena za enoto</th> <th>Količina</th> <th>Neto znesek</th> <th>Bruto znesek</th> <th></th> </tr> </thead> <tbody> <tr> <td colspan="11">Podatek še ne obstaja</td> </tr> </tbody> </table> @Html.SimpleSubmitAndCancelButton(Translations.Global.SAVE, Translations.Global.CANCEL) } and C#
[HttpGet] public virtual PartialViewResult GetStudent(int studentId) { StudentsWorksReportsFormModel studentsWorksReportsFormModel = new StudentsWorksReportsFormModel(); ..... var view = PartialView("StudentWorkReportResult", studentsWorksReportsFormModel); return view; }
Problem is that when I enter data in form and click SUBMIT button model is always empty. Why model is empty if I fill page with JQUERY and later enter data in text fields? How to fill the model also that I can insert data in DB.
-26292279 0Yes, you have a return on the previous line. The method is done.
return monthlyPayment; // <-- the method is finished. boolean isValid; // <-- no, you can't do this (the method finished on the // previous line).
-33848992 0 Store the questions and a counter to store which question has been asked in $_SESSION['questions']. Use the counter (also stored in the $_SESSION) to figure out what the next question is and increment it after each submit.
To do this check after session_start(); if $_SESSION['questions'] is set. If not get your questions and store them into $_SESSION['questions] and set the counter to 0.
Instead of the foreach() you access your questions by $_SESSION['questions'][$_SESSION['counter']] but do not forget to increase the counter each time.
Sample code:
The part to set set / get the questions and increase the counter:
session_start(); if(!isset($_SESSION['questions'])) { $query = "SELECT * FROM question_table"; $statement = $db->prepare($query); $statement->execute(); $question = $statement->fetchall(); $statement->closeCursor(); $_SESSION['questions'] = $question; $_SESSION['counter'] = 0; } if (isset($_POST["submit"])){ // DO YOUR STUFF $_SESSION['counter']++; } ?> The part the output the question:
<?php $question = $_SESSION['questions'][$_SESSION['counter']]; if(empty($question)) { // FINISHED ALL QUESTIONS } else { ?> <form action="QuestionAndOption.php" method="POST"> Question <?php echo $_SESSION['counter'] . ": " . $question["Question"]; ?><br> A: <input type="radio" name="option" value="OptionA"> <?php echo $question["OptionA"]; ?><br> B: <input type="radio" name="option" value="OptionB"> <?php echo $question["OptionB"]; ?><br> C: <input type="radio" name="option" value="OptionC"> <?php echo $question["OptionC"]; ?><br> D: <input type="radio" name="option" value="OptionD"> <?php echo $question["OptionD"]; ?><br> <button name="submit" type="submit">Submit</button> </form> <?php } // if close ?>
-9046428 0 You can't do that. You need to setup a delegate protocol. See This tutorial and search down for the words "new delegate" and it will explain how that is done. That is the design pattern you need to use. There are several steps involved so follow closely. It is worth learning. Delegate protocols are common in iPhone Apps.
In a current project I created a delegate protocol to communicate between two controller: SelectNoteViewController (Select) and EditNoteViewController (Edit). The basic idea is that Select is used to select from a list of notes and Edit is used to edit those notes. Now, I need Edit to have access back into the data and methods kept by Select because I have buttons in edit to call up the previous or next note from the list which is managed by Select so I implement a delegate protocol. Select is a delegate for Edit. That means Select does things for Edit. Here is the essential code.
SelectNoteViewController.h:
// this next statement is need to inform Select of the protocols defined in Edit #import "EditNoteViewController.h" // STEP 1 @interface SelectNoteViewController : UITableViewController <EditNoteViewControllerDelegate> { ... // STEP 2: this says Select implements the protocol I created ... // STEP 3: EditNoteViewController Delegate Methods - these are the methods in the protocol - (Notes *)selectPreviousNote; - (Notes *)selectNextNote; SelectNoteViewController.m:
// STEP 4: the protocol methods are implemented - (Notes *)selectPreviousNote { if (isPreviousToSelectedNote) { NSIndexPath *indexPath, *previousIndexPath; indexPath = [self.tableView indexPathForSelectedRow]; previousIndexPath = [NSIndexPath indexPathForRow:indexPath.row+1 inSection:0]; // update the selected row self.selectedNote = [self.fetchedResultsController objectAtIndexPath:previousIndexPath]; [self.tableView selectRowAtIndexPath:previousIndexPath animated:NO scrollPosition:UITableViewScrollPositionMiddle]; [self setPreviousNote]; [self setNextNote]; } return selectedNote; } - (Notes *)selectNextNote { if (isNextToSelectedNote) { NSIndexPath *indexPath, *nextIndexPath; indexPath = [self.tableView indexPathForSelectedRow]; nextIndexPath = [NSIndexPath indexPathForRow:indexPath.row-1 inSection:0]; // update the selected row self.selectedNote = [self.fetchedResultsController objectAtIndexPath:nextIndexPath]; [self.tableView selectRowAtIndexPath:nextIndexPath animated:NO scrollPosition:UITableViewScrollPositionMiddle]; [self setPreviousNote]; [self setNextNote]; } return selectedNote; } ... ... if ([[segue identifier] isEqualToString:@"editNote"]) { // STEP 5: this is where Edit is told that its delegate is Select [[segue destinationViewController] setEditNoteViewControllerDelegate:self]; // STEP 5 Select now has the structure to do be a delegate for Edit. Now Edit needs to define the protocol on its end that it is going to use to get to those methods in Select.
EditNoteViewController.h
#import ... // put protocol after import statements // STEP 6 @protocol EditNoteViewControllerDelegate <NSObject> - (Notes *)selectPreviousNote; - (Notes *)selectNextNote; @end @interface ... // STEP7: Edit needs a property to tell it who the delegate is - it was set back in Select.m @property (weak) id <EditNoteViewControllerDelegate> editNoteViewControllerDelegate; EditNoteViewController.m
// STEP 8: the property is synthesized @synthesize editNoteViewControllerDelegate; ... // STEP 9: now when any method needs to call selectPreviousNote or selectNext Note it does it like this: selectedNote = [self.editNoteViewControllerDelegate selectPreviousNote]; // or selectedNote = [self.editNoteViewControllerDelegate selectNextNote]; That is it. Of course the protocol methods are like and other method and they can be passed parameters which what you need to do to pass data back which was your question in the first place. As a side note, see that I can pass data from Select to Edit without a protocol by creating properties in Edit and setting those properties in the prepareForSegue method of Select. Doing so gives me one shot to set some parameters when Edit is instantiated. My use of a the delegate protocol goes back to Select and has it pass another note (previous or next) to Edit. I hope that helps. You can see there are several steps to creating a delegate protocol. I numbered them 1-9. If the data is not making it back, I usually find I forgot one of the steps.
-29683014 0You can get rid of that kernel loop to calculate D with this bsxfun based vectorized approach -
D = squeeze(sum(bsxfun(@min,A,permute(B,[3 2 1])),2)) Or avoid squeeze with this modification -
D = sum(bsxfun(@min,permute(A,[1 3 2]),permute(B,[3 1 2])),3) If the calculations of D involve max instead of min, just replace @min with @max there.
Explanation: The way bsxfun works is that it does expansion on singleton dimensions and performs the operation as listed with @ inside its call. Now, this expansion is basically how one achieves vectorized solutions that replace for-loops. By singleton dimensions in arrays, we mean dimensions of 1 in them.
In many cases, singleton dimensions aren't already present and for vectorization with bsxfun, we need to create singleton dimensions. One of the tools to do so is with permute. That's basically all about the way vectorized approach stated earlier would work.
Thus, your kernel code -
... case {'dist_histint','ih'} [m,d]=size(A); [n,d1]=size(B); if (d ~= d1) error('column length of A (%d) != column length of B (%d)\n',d,d1); end % With the MATLAB JIT compiler the trivial implementation turns out % to be the fastest, especially for large matrices. D = zeros(m,n); for i=1:m % m is number of samples of A if (0==mod(i,1000)) fprintf('.'); end for j=1:n % n is number of samples of B D(i,j) = sum(min([A(i,:);B(j,:)]));%./max(A(:,i),B(:,j))); end end reduces to -
... case {'dist_histint','ih'} [m,d]=size(A); [n,d1]=size(B); if (d ~= d1) error('column length of A (%d) != column length of B (%d)\n',d,d1); end D = squeeze(sum(bsxfun(@min,A,permute(B,[3 2 1])),2)) %// OR D = sum(bsxfun(@min,permute(A,[1 3 2]),permute(B,[3 1 2])),3) I am assuming the line: if (0==mod(i,1000)) fprintf('.'); end isn't important to the calculations as it does printing of some message.
Store the image names in an NSMutableArray and shuffle the array, e.g. via methods like this SO answer
Then loop over the array.
-3072842 0In addition to JQuery, Google CDN also hosts JQueryUI and all the default Themeroller CSS UI themes (including images!). If you're planning to build a UI from JQuery this is pretty clutch.
http://encosia.com/2009/10/11/do-you-know-about-this-undocumented-google-cdn-feature/
-20837913 0The approach will not succeed, as you can search, but you cannot sort by a multivalued field. This pointed out in Sorting with Multivalued Field in Solr and written in Solr's Wiki
Sorting can be done on the "score" of the document, or on any multiValued="false" indexed="true" field provided that field is either non-tokenized (ie: has no Analyzer) or uses an Analyzer that only produces a single Term (ie: uses the KeywordTokenizer)
Update
About the alternatives, as you point out that you need to find similar documents for one given ID, why not create a second core with a schema like
<fields> <field name="doc_id" type="int" indexed="true" stored="true" /> <field name="similar_to_id" type="int" indexed="true" stored="true" /> <field name="similarity" type="string" indexed="true" stored="true" /> </fields> <types> <fieldType name="int" class="solr.TrieIntField"/> <fieldType name="string" class="solr.StrField" /> </types> Then you could do a second query, after performing the actual search
-10374930 1 Matplotlib: Annotating a 3D scatter plotq=similar_to_id=42&sort=similarity
I'm trying to generate a 3D scatter plot using Matplotlib. I would like to annotate individual points like the 2D case here: Matplotlib: How to put individual tags for a scatter plot.
I've tried to use this function and consulted the Matplotlib docoment but found it seems that the library does not support 3D annotation. Does anyone know how to do this?
Thanks!
-10198630 0You may want to look at example 17-2 on the following site since it looks to cover what you are trying to do http://www.datypic.com/books/defxmlschema/chapter17.html.
EDIT: The feedback is that the key does need to be unique, so I'm removing that part of my response to avoid confusion.
-4982879 0Here's another way. Of course this is just for int but the code could easily be altered for other datatypes.
AOMatrix.h:
#import <Cocoa/Cocoa.h> @interface AOMatrix : NSObject { @private int* matrix_; uint columnCount_; uint rowCount_; } - (id)initWithRows:(uint)rowCount Columns:(uint)columnCount; - (uint)rowCount; - (uint)columnCount; - (int)valueAtRow:(uint)rowIndex Column:(uint)columnIndex; - (void)setValue:(int)value atRow:(uint)rowIndex Column:(uint)columnIndex; @end AOMatrix.m
#import "AOMatrix.h" #define INITIAL_MATRIX_VALUE 0 #define DEFAULT_ROW_COUNT 4 #define DEFAULT_COLUMN_COUNT 4 /**************************************************************************** * BIG NOTE: * Access values in the matrix_ by matrix_[rowIndex*columnCount+columnIndex] ****************************************************************************/ @implementation AOMatrix - (id)init { return [self initWithRows:DEFAULT_ROW_COUNT Columns:DEFAULT_COLUMN_COUNT]; } - (id)initWithRows:(uint)initRowCount Columns:(uint)initColumnCount { self = [super init]; if(self) { rowCount_ = initRowCount; columnCount_ = initColumnCount; matrix_ = malloc(sizeof(int)*rowCount_*columnCount_); uint i; for(i = 0; i < rowCount_*columnCount_; ++i) { matrix_[i] = INITIAL_MATRIX_VALUE; } // NSLog(@"matrix_ is %ux%u", rowCount_, columnCount_); // NSLog(@"matrix_[0] is at %p", &(matrix_[0])); // NSLog(@"matrix_[%u] is at %p", i-1, &(matrix_[i-1])); } return self; } - (void)dealloc { free(matrix_); [super dealloc]; } - (uint)rowCount { return rowCount_; } - (uint)columnCount { return columnCount_; } - (int)valueAtRow:(uint)rowIndex Column:(uint)columnIndex { // NSLog(@"matrix_[%u](%u,%u) is at %p with value %d", rowIndex*columnCount_+columnIndex, rowIndex, columnIndex, &(matrix_[rowIndex*columnCount_+columnIndex]), matrix_[rowIndex*columnCount+columnIndex]); return matrix_[rowIndex*columnCount_+columnIndex]; } - (void)setValue:(int)value atRow:(uint)rowIndex Column:(uint)columnIndex { matrix_[rowIndex*columnCount_+columnIndex] = value; } @end
-8916704 0 You can do it with Generalized Algebraic Data Types. We can create a generic (GADT) type with data constructors that have type constraints. Then we can define specialized types (type aliases) that specifies the full type and thus limiting which constructors are allowed.
{-# LANGUAGE GADTs #-} data Zero data Succ a data Axis a where X :: Axis (Succ a) Y :: Axis (Succ (Succ a)) Z :: Axis (Succ (Succ (Succ a))) type Axis2D = Axis (Succ (Succ Zero)) type Axis3D = Axis (Succ (Succ (Succ Zero))) Now, you are guaranteed to only have X and Y passed into a function that is defined to take an argument of Axis2D. The constructor Z fails to match the type of Axis2D.
Unfortunately, GADTs do not support automatic deriving, so you will need to provide your own instances, such as:
instance Show (Axis a) where show X = "X" show Y = "Y" show Z = "Z" instance Eq (Axis a) where X == X = True Y == Y = True Z == Z = True _ == _ = False
-38958511 0 java on osx - xmx ignored? i've got two computers running on Mac OS X El Capitan and Ubuntu 16.04 LTS. On both is Java SDK 1.8.0_101 installed.
When I try to start an game server on Ubuntu with more memory than available, I get the following output:
$ java -Xms200G -Xmx200G -jar craftbukkit.jar nogui Java HotSpot(TM) 64-Bit Server VM warning: INFO: os::commit_memory(0x00007f9b6e580000, 71582613504, 0) failed; error='Cannot allocate memory' (errno=12) # # There is insufficient memory for the Java Runtime Environment to continue. # Native memory allocation (mmap) failed to map 71582613504 bytes for committing reserved memory. # An error report file with more information is saved as: # On Mac OS I don't get this error:
$ java -Xms200G -Xmx200G -jar craftbukkit.jar nogui Loading libraries, please wait... Both computers have 8GB of memory. I also tried with an other Apple computer - same problem.
Is that a bug of java mac version?
(Is there a way to force limit the memory usage e.g. to 1GB? -Xmx1G won't work and I wasn't able to find another reason. Not here neither on google)
Thank you!
Sorry for my bad english...
-4927396 0var lis = $('ul > li'); function switchClass(i) { lis.eq(i).removeClass('current'); lis.eq(i = ++i % lis.length).addClass('current'); setTimeout(function() { switchClass(i); }, 2000); } switchClass(-1);
-217275 0 Use == on objects to perform identity comparison.
That is what the default implementation of equals() does, but one normally overrides equals() to serve as an "equivalent content" check.
I am using the same book and had the same issue, I remove Ruby 1.9.3-p0 and install Ruby 1.9.2-p290, it is working now
-23967955 0use the following function
left(@test, charindex('/', @test) - 2)
-39262726 0 XLS is either a typo for XSL or a reference to Microsoft's Excel spreadsheet format.
XSL refers to a family of W3C recommendations related to XML transformation and presentation:
So, if now i need to make a ssl request i will have to use HttpsURLConnection (?) and create a request.
My question is -How does HttpsURLConnection know about the encryption algorithm and then encrypts using that?
Yes you have to use HttpsURLConnection. But you dont have to do it explicitly. new URL("https://google.pl").openConnection(); is more then enough.
In Server Hello, server anounces what encrypiton it can accept. All encryption methods have to "announce" themselves so the server knows how to interpret them. So when you initiatle the connection, servers says what it can handle, client choose one of the cipers and ciper the data using it. At the beginning of the connection, client announces what suite will it use.
This information can be public to this is not a problem that this is sent as plaintext. The point is, to exchange the symetric key between client in server in private way, so the rest of communication can be ciphered usint that key.
How is session maintained? How does HttpsURLConnection know that this connection has already been initiated and handshake procedures have already been completed?
Well SSL stands for Secure Socket Layer. It means that data transmit and received is ciphered, decrypted on raw socket(streams) level; You can open SSL connection to transmit data from point to point not only via Https
There is no "session". As long as you open a connection, you got 2 streams. Input and Output. As long as those are open, you can write data or read from them. Once they are closed, you will have to initiate another connection.
Every Http request is a new connection (unless Keep-Alive is sent). JsessionId for example, or php's sessionid is to identity that you are the same client that made requests earlier so it can "simulate" constant connection.
-5601412 0It's actually doing exactly what it should. Server.Execute() basically will insert the second page's content into the first page, including ViewState.
To remedy your problem, are you able to disable ViewState on the page that's being called (demo.aspx)?
<%@ Page Language="C#" EnableViewState="false" CodeBehind="demo.aspx.cs"
-18094751 0 Use e.Cancel = true; to cancel back navigation.
Please correct me if I'm wrong. Your code is looking messed up. I think you last page/back page is mainpage.xaml and in OK you are again navigating to this page. If this is the case then there is no need of navigating again you can use below code.
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e) { MessageBoxResult res = MessageBox.Show("Are you sure that you want to exit?", "", MessageBoxButton.OKCancel); if (res != MessageBoxResult.OK) { e.Cancel = true; //when pressed cancel don't go back } }
-7262750 0 Assuming that listings is indexed on id:
If your id is an integer:
SELECT listings.id, listings.price, listings.seller_id, sellers.blacklisted FROM listings INNER JOIN sellers ON sellers.id = listings.sellers_id WHERE listings.price > 100 AND sellers.blacklisted = 0 AND listings.ID LIKE CONCAT(CEIL(RAND() * 100),'%') LIMIT 4 and if it's ascii
SELECT listings.id, listings.price, listings.seller_id, sellers.blacklisted FROM listings INNER JOIN sellers ON sellers.id = listings.sellers_id WHERE listings.price > 100 AND sellers.blacklisted = 0 AND listings.ID LIKE CONCAT(CHAR(CEIL(RAND() * 100)),'%') LIMIT 4 basically my advice to speed things up is dump the order by. On anything over a few records you're adding measurable overhead.
ps please forgive me if concat can't be used this way in mqsql; not entirely certain whether it'll work.
-9351921 0 Change Combobox via Textbox Input VB.NETHi I need some help over here... how do i change the display member of a ComboBox after i have entered a code in a textbox that it represent the combobox value??
example
Code: 02-001 Combobox: Provider X
if i change the code the provider combobox must change and if i change the provider combobox the code should change!.. i haven't found any help.. heres little code I remember
if e.keychar = chr(13) Then combobox.valuemember = textbox.text combobox.displaymember = me.stockdataset.selectprovider(@textbox.text) end if this code change the combo box display member but if I change the comobox by clicking it the code on the textbox doesnt change, to its corresponding code...?? please help
....the combo box is bound to the provider tables....
-24219023 0Use %0a , it might be helpful.
Reference :http://www.twilio.com/help/faq/sms/how-do-i-add-a-line-break-in-my-sms-message
-34394842 0I guess you mean the category tree, And this should give you category tree. you can see the various filters being applied. (You can always do according to your need.)
<?php $rootCatId = Mage::app()->getStore()->getRootCategoryId(); $catlistHtml = getTreeCategories($rootCatId, false); echo $catlistHtml; function getTreeCategories($parentId, $isChild){ $allCats = Mage::getModel('catalog/category')->getCollection() ->addAttributeToSelect('*') ->addAttributeToFilter('is_active','1') ->addAttributeToFilter('include_in_menu','1') ->addAttributeToFilter('parent_id',array('eq' => $parentId)) ->addAttributeToSort('position', 'asc'); $class = ($isChild) ? "sub-cat-list" : "cat-list"; $html .= '<ul class="'.$class.'">'; foreach($allCats as $category) { $html .= '<li><span>'.$category->getName()."</span>"; $subcats = $category->getChildren(); if($subcats != ''){ $html .= getTreeCategories($category->getId(), true); } $html .= '</li>'; } $html .= '</ul>'; return $html; } ?> EDIT: getting all parent category using an id/current category id..
$id = Mage::registry('current_category'); //or if you are retrieving other way around $category = Mage::getModel('catalog/category')->load($id); $categorynames = array(); foreach ($category->getParentCategories() as $parent) { $categorynames[] = $parent->getName(); } print_r($categorynames); //dumping category names for eg.
-3667773 0 One possibility: Use an xhtml parser that fixes malformed xhtml. One such library is libxml2. Then use the library to locate and remove empty p tags.
-14371345 1 Get field value within Flask-MongoAlchemy DocumentI've looked at documentation, and have searched Google extensively, and haven't found a solution to my problem.
This is my readRSS function (note that 'get' is a method of Kenneth Reitz's requests module):
def readRSS(name, loc): linkList = [] linkTitles = list(ElementTree.fromstring(get(loc).content).iter('title')) linkLocs = list(ElementTree.fromstring(get(loc).content).iter('link')) for title, loc in zip(linkTitles, linkLocs): linkList.append((title.text, loc.text)) return {name: linkList} This is one of my MongoAlchemy classes:
class Feed(db.Document): feedname = db.StringField(max_length=80) location = db.StringField(max_length=240) lastupdated = datetime.utcnow() def __dict__(self): return readRSS(self.feedname, self.location) As you can see, I had to call the readRSS function within a function of the class, so I could pass self, because it's dependent on the fields feedname and location.
I want to know if there's a different way of doing this, so I can save the readRSS return value to a field in the Feed document. I've tried assigning the readRSS function's return value to a variable within the function __dict__ -- that didn't work either.
I have the functionality working in my app, but I want to save the results to the Document to lessen the load on the server (the one I am getting my RSS feed from).
Is there a way of doing what I intend to do or am I going about this all wrong?
-11968366 0 cURL loop memory growthI have this problem with a loop using cURL where memory grows exponentially. In this example script, it starts using approximately 14MB of memory and ends with 28MB, with my original script and repeating to 1.000.000, memory grows to 800MB, which is bad.
PHP 5.4.5
cURL 7.21.0
for ($n = 1; $n <= 1000; $n++){ $apiCall = 'https://api.instagram.com/v1/users/' . $n . '?access_token=5600913.47c8437.358fc525ccb94a5cb33c7d1e246ef772'; $options = Array(CURLOPT_URL => $apiCall, CURLOPT_RETURNTRANSFER => true, CURLOPT_FRESH_CONNECT => true ); $ch = curl_init(); curl_setopt_array($ch, $options); $response = curl_exec($ch); curl_close($ch); unset($ch); }
-37337715 0 Online Check, This is just a demo example.
See below the real example:
At first you need to use array_search for get the position of the same data, if exist then just remove it using $arr[$pos] = '';, and each and every time you need to import data into the new array called $arr and after completing fetching data you need to use a foreach loop to print them.
$arr = array(); foreach($query->result() as $row){ $pos = array_search($row->name, $arr); if($pos !== false) $arr[$pos] = ''; $arr[] = $row->name; } foreach($arr as $val){ echo $val.'<br/>'; } Check this and let me know.
-18776688 0When catch exceptions I usually find that more specific is better, that being said typing out all of those different blocks that do the same thing can get really annoying. Thankfully in the Java 7 release a try-catch notation was added where you can specific multiple exceptions for a single block:
try{ //some statements } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | FileNotFoundException | IOException | UnrecoverableKeyException | NoPropertyFoundException e) { LOGGER.error(e); } This sounds like what you are looking for, but there is more detailed information in the Oracle docs: http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html
-17133620 0 Setting timeout on blocking I/O ops with ServerSocketChannel doesn't work as expectedI'm working on a small group conversation server in Java and I'm currently hacking network code, but it seems like I cannot set right timeout on blocking I/O ops: chances are I've been bitten by some Java weirdness (or, simply, I misinterpret javadoc).
So, this is the pertinent code from ConversationServer class (with all security checks and logging stripped for simplicity):
class ConversationServer { // ... public int setup() throws IOException { ServerSocketChannel server = ServerSocketChannel.open(); server.bind(new InetSocketAddress(port), Settings.MAX_NUMBER_OF_PLAYERS + 1); server.socket().setSoTimeout((int) Settings.AWAIT_PLAYERS_MS); int numberOfPlayers; for (numberOfPlayers = 0; numberOfPlayers < Settings.MAX_NUMBER_OF_PLAYERS; ++numberOfPlayers) { SocketChannel clientSocket; try { clientSocket = server.accept(); } catch (SocketTimeoutException timeout) { break; } clients.add(messageStreamFactory.create(clientSocket)); } return numberOfPlayers; } // ... } The expected behaviour is to let connect Settings.MAX_NUMBER_OF_PLAYERS clients at most, or terminate setup anyway after Settings.AWAIT_PLAYER_MS milliseconds (currently, 30000L).
What happens, is that if I connect Settings.MAX_NUMBER_OF_PLAYERS clients, everything is fine (exit because of for condition), but if I don't, the SocketTimeoutException I'd expect is never thrown and the server hangs forever.
If I understand right, server.socket().setSoTimeout((int) Settings.AWAIT_PLAYERS_MS); should be sufficient, but it doesn't give the expected behaviour.
So, can anyone spot the error here?
-33217783 0 Optimizing opencl kernelI am trying to optimize this kernel. The CPU version of this kernel is 4 times faster than the GPU version. I would expect that the GPU version would be faster. It might be that we have a lot of memory accesses and that is why we have a low performance. I am using an Intel HD 2500 and OpenCL 1.2.
The GPU kernel is:
__kernel void mykernel(__global unsigned char *inp1, __global unsigned char *inp2, __global unsigned char *inp3, __global unsigned char *inp4, __global unsigned char *outp1, __global unsigned char *outp2, __global unsigned char *outp3, __global unsigned char *outp4, __global unsigned char *lut, uint size ) { unsigned char x1, x2, x3, x4; unsigned char y1, y2, y3, y4; const int x = get_global_id(0); const int y = get_global_id(1); const int width = get_global_size(0); const uint id = y * width + x; x1 = inp1[id]; x2 = inp2[id]; x3 = inp3[id]; x4 = inp4[id]; y1 = (x1 & 0xff) | (x2>>2 & 0xaa) | (x3>>4 & 0x0d) | (x4>>6 & 0x02); y2 = (x1<<2 & 0xff) | (x2 & 0xaa) | (x3>>2 & 0x0d) | (x4>>4 & 0x02); y3 = (x1<<4 & 0xff) | (x2<<2 & 0xaa) | (x3 & 0x0d) | (x4>>2 & 0x02); y4 = (x1<<6 & 0xff) | (x2<<4 & 0xaa) | (x3<<2 & 0x0d) | (x4 & 0x02); // lookup table y1 = lut[y1]; y2 = lut[y2]; y3 = lut[y3]; y4 = lut[y4]; outp1[id] = (y1 & 0xc0) | ((y2 & 0xc0) >> 2) | ((y3 & 0xc0) >> 4) | ((y4 & 0xc0) >> 6); outp2[id] = ((y1 & 0x30) << 2) | (y2 & 0x30) | ((y3 & 0x30) >> 2) | ((y4 & 0x30) >> 4); outp3[id] = ((y1 & 0x0c) << 4) | ((y2 & 0x0c) << 2) | (y3 & 0x0c) | ((y4 & 0x0c) >> 2); outp4[id] = ((y1 & 0x03) << 6) | ((y2 & 0x03) << 4) | ((y3 & 0x03) << 2) | (y4 & 0x03); } I use :
size_t localWorkSize[1], globalWorkSize[1]; localWorkSize[0] = 1; globalWorkSize[0] = X*Y; // X,Y define a data space of 15 - 20 MB LocalWorkSize can vary between 1 - 256.
for LocalWorkSize = 1 I have CPU = 0.067Sec GPU = 0.20Sec for LocalWorkSize = 256 I have CPU = 0.067Sec GPU = 0.34Sec Which is really weird. Can you give me some ideas why I get these strange numbers? and do you have any tips on how I can optimize this kernel?
My main looks like this:
int main(int argc, char** argv) { int err,err1,j,i; // error code returned from api calls and other clock_t start, end; // measuring performance variables cl_device_id device_id; // compute device id cl_context context; // compute context cl_command_queue commands; // compute command queue cl_program program_ms_naive; // compute program cl_kernel kernel_ms_naive; // compute kernel // ... dynamically allocate arrays // ... initialize arrays cl_uint dev_cnt = 0; clGetPlatformIDs(0, 0, &dev_cnt); cl_platform_id platform_ids[100]; clGetPlatformIDs(dev_cnt, platform_ids, NULL); // Connect to a compute device err = clGetDeviceIDs(platform_ids[0], CL_DEVICE_TYPE_GPU, 1, &device_id, NULL); // Create a compute context context = clCreateContext(0, 1, &device_id, NULL, NULL, &err); // Create a command queue commands = clCreateCommandQueue(context, device_id, 0, &err); // Create the compute programs from the source file program_ms_naive = clCreateProgramWithSource(context, 1, (const char **) &kernelSource_ms, NULL, &err); // Build the programs executable err = clBuildProgram(program_ms_naive, 0, NULL, NULL, NULL, NULL); // Create the compute kernel in the program we wish to run kernel_ms_naive = clCreateKernel(program_ms_naive, "ms_naive", &err); d_A1 = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, mem_size_cpy/4, h_A1, &err); d_A2 = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, mem_size_cpy/4, h_A2, &err); d_A3 = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, mem_size_cpy/4, h_A3, &err); d_A4 = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, mem_size_cpy/4, h_A4, &err); d_lut = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, 256, h_ltable, &err); d_B1 = clCreateBuffer(context, CL_MEM_WRITE_ONLY, mem_size_cpy/4, NULL, &err); d_B2 = clCreateBuffer(context, CL_MEM_WRITE_ONLY, mem_size_cpy/4, NULL, &err); d_B3 = clCreateBuffer(context, CL_MEM_WRITE_ONLY, mem_size_cpy/4, NULL, &err); d_B4 = clCreateBuffer(context, CL_MEM_WRITE_ONLY, mem_size_cpy/4, NULL, &err); int size = YCOLUMNS*XROWS/4; int size_b = size * 4; err = clSetKernelArg(kernel_ms_naive, 0, sizeof(cl_mem), (void *)&(d_A1)); err |= clSetKernelArg(kernel_ms_naive, 1, sizeof(cl_mem), (void *)&(d_A2)); err |= clSetKernelArg(kernel_ms_naive, 2, sizeof(cl_mem), (void *)&(d_A3)); err |= clSetKernelArg(kernel_ms_naive, 3, sizeof(cl_mem), (void *)&(d_A4)); err |= clSetKernelArg(kernel_ms_naive, 4, sizeof(cl_mem), (void *)&d_B1); err |= clSetKernelArg(kernel_ms_naive, 5, sizeof(cl_mem), (void *)&(d_B2)); err |= clSetKernelArg(kernel_ms_naive, 6, sizeof(cl_mem), (void *)&(d_B3)); err |= clSetKernelArg(kernel_ms_naive, 7, sizeof(cl_mem), (void *)&(d_B4)); err |= clSetKernelArg(kernel_ms_naive, 8, sizeof(cl_mem), (void *)&d_lut); //__global err |= clSetKernelArg(kernel_ms_naive, 9, sizeof(cl_uint), (void *)&size_b); size_t localWorkSize[1], globalWorkSize[1]; localWorkSize[0] = 256; globalWorkSize[0] = XROWS*YCOLUMNS; start = clock(); for (i=0;i< EXECUTION_TIMES;i++) { err1 = clEnqueueNDRangeKernel(commands, kernel_ms_naive, 1, NULL, globalWorkSize, localWorkSize, 0, NULL, NULL); err = clFinish(commands); } end = clock(); return 0; }
-7575471 0 Assigning issue with numpy structured arrays I was trying this simple line of assigning codes to a structured array in numpy, I am not quiet sure, but something wrong happens when I assign a matrix to a sub_array in a structured array I created as follows:
new_type = np.dtype('a3,(2,2)u2') x = np.zeros(5,dtype=new_type) x[1]['f1'] = np.array([[1,1],[1,1]]) print x Out[143]: array([('', [[0, 0], [0, 0]]), ('', [[1, 0], [0, 0]]), ('', [[0, 0], [0, 0]]), ('', [[0, 0], [0, 0]]), ('', [[0, 0], [0, 0]])], dtype=[('f0', '|S3'), ('f1', '<u2', (2, 2))]) Shouldn't the second field of the subarray equals at this stage
[[1,1],[1,1]]
-31583742 0 The essential difference is that Special:SMWAdmin only ''queues'' the updates in the job queue, while rebuildData.php actually performs the updates.
If your job queue is correctly configured, the difference may be trivial; otherwise you'll run into performance issues. A common error is to have insufficient memory for the job runner. If all else fails, the last resort is null-editing all the pages.
The difference was actually written in the help page, but in a weird English; fixed that too.
-32577045 0Remove import U;. You don't need it because both files are in the same location. That is what causing the problem.
You need to check for memory allocations with following in your app -
Using Instruments check Allocation and Leaks
Using Static memory analyser check static memory leaks. To use this either use "cmd+shift+B" or go to "Xcode -> Product -> Analyze"
Also you need to ensure proper release of your view controllers.
-38128265 0Fix for Chrome on Windows.
First, you need to export the certificate.
To import
I've got a malformed xml file, basically it have ampersan(&) inside the tags and they are not escaped...
This is the code i'm using for loading the xml.
$archivo = "tarifa_mayorista.xml"; echo "Reading file<br>"; if (file_exists($archivo)) { $articulos = simplexml_load_file($archivo); if($articulos){ foreach ($articulos->Categoria as $rs) { $categoria = (string) $rs->TxCategoria; $subCat = (string) $rs->SubCategoria[0]->TxSubCategoria; $cod = (string) $rs->SubCategoria[0]->SubCategoria2[0]->PartNumber; $stock = (string) $rs->SubCategoria[0]->SubCategoria2[0]->Stock; $precio = (string) $rs->SubCategoria[0]->SubCategoria2[0]->Precio; $fabricante = (string) $rs->SubCategoria[0]->SubCategoria2[0]->Fabricante; $ean = (string) $rs->SubCategoria[0]->SubCategoria2[0]->EAN; $descripcion = (string) $rs->SubCategoria[0]->SubCategoria2[0]->Descripcion; $canon = (string) $rs->SubCategoria[0]->SubCategoria2[0]->Canon; $desc = mysql_real_escape_string($descripcion); $sql2="insert into `activadosmil` set cod='".trim($cod)."', stock='".trim($stock)."', precio='".trim($precio)."', categoria='".$categoria."', subcategoria='".$subCat."', descripcion='".$desc."', ean='".trim($ean)."', canon='".trim($precio)."', fabricante='".trim($fabricante)."'"; mysql_query($sql2) or die(mysql_error()."<hr>".$sql2); } } else echo "<br>Invalid XML sintaxis"; } else echo "<br>Error opening ".$archivo; /* SAMPLE XML CODE */
<Categoria> <TxCategoria>ALMACENAMIENTO</TxCategoria> <SubCategoria> <TxSubCategoria>CARCASAS DISCO DURO</TxSubCategoria> <SubCategoria2> <TxSubCategoria2>2,5"</TxSubCategoria2> <PartNumber>5VECTRIXALU3,5</PartNumber> <Fabricante>TACENS</Fabricante> <EAN>4710700954461</EAN> <Descripcion>MONITOR ASUS LED&PIP 27 VE278Q</Descripcion> <Precio> 12.37</Precio> <Stock> 0</Stock> <Canon> 0.00</Canon> </SubCategoria2> </SubCategoria> </Categoria> Is there any way to load the xml malformed file with simplexml? Or escape the characteres from tags?
Thank you guys in advance
-9401392 0You can add panels to a form at runtime the same way the designer does - construct the Panel, and add it to the form (via this.Controls.Add(thePanel);).
The easiest way to see the appropriate code is to add a panel to the form using the designer, then open up the "YourForm.designer.cs" file. The designer just generates the required code for you - but you can see the exact code required to duplicate what the designer would create.
As for the layout, I'd recommend watching the Layout Techniques for Windows Forms Developers video. It may give you some good clues as to the various options available for layout. There is nothing exactly like Java's GridLayout, though there are some open source projects that attempt to duplicate this functionality.
-40940970 0Adding -ExecutionPolicy ByPass is what made it work. So now what I am passing is:
-ExecutionPolicy ByPass -file "\SERVER\Share\Script.ps1"
This is where I got this tip - http://www.sqlservercentral.com/Forums/Topic1714552-147-1.aspx
After I added this, Read-Host started working also and paused the execution of the script.
-13156139 0If you could change your student class properties to match the Xml element names and/or decorate the properties with attributes indicating what XML value goes to what class property, then you could use the .Net to deserialise the XML into a List Students in one line.
Then just persist to the DB as you normally would.
-21572016 1 List connected Bluetooth LE devices to Windows 8 with pythonI want to be able to read out information about connected Bluetooth Low Energy HID devices in Windows 8. My main application uses Qt, but I thought it could be much easier to get help from a Python script. Since Windows 8.1 supports Bluetooth Low Energy natively, I connect my mouse to it and tried using the pywinusb package, but it doesn't seem to be able to read out this wirelessly connected device, only connected HID devices.
How can I read out information about my BLE device with Python?
-22866252 0 Regex get text between parentheses and keywordsi have a text pattern like this;
(((a) or (b) or (c)) and ((d) or (e)) and ((!f) or (!g))) and i want to get it like this;
((a) or (b) or (c)) ((d) or (e)) ((!f) or (!g)) After that i want to seperate them like this;
a,b,c d,e !f,!g any help would be awesome :)
edit 1: sorry about the missing parts; using language is C# and this is what i got;
(\([^\(\)]+\))|([^\(\)]+) with i got;
(a) or (b) or (c) and (d) or (e) and (!f) or (!g) thanks already!
-21456670 0You could also use analytic functions to compute the number of NULL values for the name and filter by that:
with v_data as ( select name, value from table1 union select name, value from table2 ) select v2.* from ( select v1.*, count(value) over (partition by name) as value_cnt from v_data v1 ) v2 where value_cnt = 0 or value is not null
-39388527 0 All answers are creating NEW arrays before projecting the final result : (filter and map creates a new array each) so basically it's creating twice.
Another approach is only to yield expected values :
Using iterator functions
function* foo(g) { for (let i = 0; i < g.length; i++) { if (g[i]['images'] && g[i]["images"].length) yield g[i]['images'][0]["name"]; } } var iterator = foo(data1) ; var result = iterator.next(); while (!result.done) { console.log(result.value) result = iterator.next(); } This will not create any additional array and only return the expected values !
However if you must return an array , rather than to do something with the actual values , then use other solutions suggested here.
https://jsfiddle.net/remenyLx/7/
-5701468 0Own java agent should do the trick:
http://blogs.captechconsulting.com/blog/david-tiller/not-so-secret-java-agents-part-1
I suppose that intercepting System.currentTimeMillis() calls should be enough.
-36778764 0 Rails: Upload to Instagram programatically?I want to upload photos to my own instagram account programatically from my Rails app. I've only been able to find posts from ~2013 that state this is against Instagram TOS. Is there any update or are photo uploads still disabled using the Instagram API?
-8772833 0You are just passing that function a string. For it to make any sense of that, it would have to parse the string to split up the key/value pairs. I'm not saying it's the best approach, but if you want to do that, you should use parse_str().
Note that this is not by any means a language feature of PHP, but I am just providing a means to handle what you've shown.
-37933027 0If I understand you correctly, you want to not include any of the changes from master, but just "close" it and keep going with exactly what you have in symfony. If so, use the ours merge strategy, which will create a merge commit without incorporating any of the changes from the other branch and thus effectively "close" the other branch. The last two commands simply rearrange the branch names.
git checkout symfony git merge -s ours master git checkout -B master git branch -D symfony
-24327386 0 Try this... You can do it in single line...
formSubmit = isValidToggle($('#rta_cl_fn'), $('#div_cl_fn')) && isValidToggle($('#rta_cl_ln'), $('#div_cl_ln')) && isValidToggle($('#rta_cl_ph'), $('#div_cl_ph')) && isValidToggle($('#rta_cl_mob'), $('#div_cl_mob')) in this, it will check first one condition and if it is true then It will check further condition otherwise it will take you out.
-27990634 0Thanks for the answers.
I solved it altogether differently: upon a selection change event I enable a short timer which, when ticked, checks whether or not there's a selected item in the ListView, and if not, it selects the first one. And it disables itself in any case. Seems that it works for me, so I am stopping there.
-7861459 0Responding to dvcolgan's clarifying comment:
So, you want to have an HTML file on the server with inline CoffeeScript that gets served as HTML with inline JavaScript. The CoffeeScript compiler doesn't support this directly, but you could write a Node script to do it fairly easily, using the coffee-script library and jsdom to do the HTML parsing.
Exactly how you want to implement this would depend on the web framework you're using. You probably don't want the CoffeeScript compiler to run on every request (it's pretty fast, but it's still going to reduce the number of requests/second your server can handle); instead, you'd want to compile your HTML once and then serve the compiled version from a cache. Again, I don't know of any existing tools that do this, but it shouldn't be too hard to write your own.
-28081273 0 How do I change only background color of ProgressDialog without affecting border in Android?I used the following code to change the background of Progress Dialog. But the color changes on the outside frame too as below. I want to change only inside the dialog.
<style name="StyledDialog" parent="@android:style/Theme.Panel"> <item name="android:background">#083044</item> </style> 
As per the answer given at this question Change background of ProgressDialog
<style name="StyledDialog" parent="@android:style/Theme.Dialog"> <item name="android:alertDialogStyle">@style/CustomAlertDialogStyle</item> <item name="android:textColorPrimary">#000000</item> </style> <style name="CustomAlertDialogStyle"> <item name="android:bottomBright">@color/background</item> <item name="android:bottomDark">@color/background</item> <item name="android:bottomMedium">@color/background</item> <item name="android:centerBright">@color/background</item> <item name="android:centerDark">@color/background</item> <item name="android:centerMedium">@color/background</item> <item name="android:fullBright">@color/background</item> <item name="android:fullDark">@color/background</item> <item name="android:topBright">@color/background</item> <item name="android:topDark">@color/background</item> </style> This code gives background color perfect. But since, dialog color and activity's background color is same. It appears like transparent with no border. I want some border as before.

In the case where you are ignoring the first character, you only want to compare word.length() - 1 characters -- and the same length for both the string and the word.
Note that you really don't need to test the case where the first letter exactly matches as that is a subset of the case where you are ignoring the first letter.
-9420810 0To run Python scripts on your Android phone all you have to do is install SL4A and this is how you do that:
To install SL4A, you will need to enable the "Unknown sources" option in your device's "Application" settings, download the .apk and install it either by accessing http://code.google.com/p/android-scripting/ from your computer and click the qr-code or directly from your phone and click the qr-code and then run the downloaded .apk file.
After installing SL4A:
and after that a new screen will appear with an Install button on the top, press it and it will download Python 2.6.2, at the moment, for you. Optionally there is a button so that you can download a few more Python modules.
After these steps you are ready to go. You will be able to create Python scripts using SL4A and run the directly on your phone without "compiling" them, if that's your worry. It also makes the .pyc files if those are the ones you're talking about.
-12229258 0This answer is based upon what you mentioned in the question when no code snippet was provided and quetion was...
I have created a component instance, drawn it onto the screen, and added it to an ArrayList. I'm accessing it by referencing to the drawn one using it's children (getParent() method). However, when I then pass this reference to ArrayLists indexOf(); method, it returns -1. I suppose that means that the component does not exist in the ArrayList. Is this what should happen, or did I probably mess something up in my program? I'm NOT providing you with a SSCCE, I'm not asking you to do any coding, just to tell me if this is normal Java behavior...
Here goes the my response
The javadoc of indexOf() says...
Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.
As you can see this depends on the equals() implementation for you component. Check your implementation as that holds the key of retrieving the value from list.
I've found a solution.
I can apply system theme for that single element in the resource, something like this:
<ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="/PresentationFramework.Aero;V3.0.0.0;31bf3856ad364e35;component\themes/aero.normalcolor.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary>
-18219695 0 Maybe you forgot to match the scopes of PlusClient and getToken:
new PlusClient .Builder(this, this, this) .setScopes(Scopes.PLUS_LOGIN, "https://www.googleapis.com/auth/userinfo.email") .build();
-28892840 0 You can do it like this:
function setCaret() { var element = document.getElementById("input"); var range = document.createRange(); var node; node = document.getElementById("first"); range.setStart(node.childNodes[0], 1); <-- sets the location var sel = window.getSelection(); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); element.focus(); } node.childNodes[] pertains to which line you want to set the cursor on and the next number is the location on that line. In this example is moves to space 1 line 0 (line 1 really). So if you change those values to variables and put them as parameters in your function you could specify where.
-12240084 0AFAIK, there is no direct answer because multiple wavelengths can combine to give the same color right? So you have the wavelengths that map to pure colors and then their combinations can give many other and the same colors. And there are several combinations that can give the same color. This is because of inteference. So you essentially are asking for a one to many mapping.
To answer your question: There is no fixed formula. The reverse formulas will give you a range. That is the best it can get.
-28355924 0Add $GOPATH/bin to your PATH variable in your shell,
for bash:
export PATH=$GOPATH/bin:$PATH
-9865547 0 Random crashes occur in my iphone project, see two call stacks, all in web core, all crash after UIWebView deallocate Random crashes occur in my iphone project, see two call stacks, all in web core, all crash after UIWebView deallocate.
See crash 1, seems web core can't close it completely, is it blocked by other running threads?
See crash 2, why it is still dealing with some issues even if UIWebView has been released?
Any idea or discussion will be appreciated, thanks in advance.
Crash 2 has higher reproducible rate than crash 1, scan WebCore source code, it seems be manifest cache has been deleted (who did it?) when try to access it.


The documentation is pretty clear. You cannot use this property on characteristics you publish. The purpose of this value is to enable you to interpret the properties of characteristics that are discovered from other peripherals.
If you want to advise centralised that your value has changed then notify is the appropriate method.
hey, i was trying to do a bottom sticky footer link test and but it kept being more then 100% meaning it scrolled a litle bit..
so i made a simple HTML code, without any additions but its still more than 100%, see here:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="he" lang="he" dir="rtl" id="bangler"> <head> <title>my title</title> <style type="text/css"> html, body, #wrapper { height: 100%; } body > #wrapper { height: auto; min-height: 100%; } </style> </head> <body> <div id="wrapper">aa</div> </body> </html> the thing is, it scrolls just a little bit more then 100% meaning about 5-10px more.. this is really strange, on both IE and Firefox !!
Thanks in advance !
-20857311 0In your code import.
Import android.support.v4.app.Fragment
Maybe your code work fine.
-13151175 0 Passing an SDL surface to a functionI'm a bit confused how i pass my SDL_Surface to my function so that i can setup my screen in SDL.
This is my error:
No operator "=" matches these operands My function is this:
void SDL_Start(SDL_Surface screen){ Uint32 videoflags = SDL_SWSURFACE | SDL_DOUBLEBUF | SDL_ANYFORMAT;// | SDL_FULLSCREEN; // Initialize the SDL library if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) { fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError()); exit(500); } //get player's screen info const SDL_VideoInfo* myScreen = SDL_GetVideoInfo(); //SDL screen int reso_x = myScreen->current_w; int reso_y = myScreen->current_h; Uint8 video_bpp = 32; //setup Screen [Error on the line below] screen = SDL_SetVideoMode(reso_x, reso_y, video_bpp, videoflags|SDL_FULLSCREEN); } This function is called in my main function like so :
SDL_Surface *screen; SDL_Start(*screen); Any ideas what the mistake is ?
-5684415 0(1) The stack is actually only local to expressionParser so I KNOW I can remove the new keyword
correct
(2) Do I HAVE To create a pointer to the queue in this case. If I need to create the pointer, then I should call a delete output in my query function to properly get rid of the queue?
correct. Here, "creating pointer" doesn't mean again using new and copy all contents. Just assign a pointer to the already created queue<string>. Simply delete output; when you are done with it in your query().
(3) vector being returned by query. Should that be left as I have it or should it be a pointer and what's the difference between them?
I would suggest either you pass the vector<Line*> by non-const reference to your query() and use it or return a vector<Line*>* from your function. Because difference is, if the vector is huge and return by value then it might copy all its content (considering the worst case without optimization)
(4) Once I consume that vector (display the information in it) I need it to be removed from memory, however, the pointers contained in the vector are still good and the items being pointed to by them should not be deleted. What's the best approach in this case?
Pass the vector<Line*> into the function by reference. And retain it in scope until you need it. Once you are done with pointer members 'Line*inside it, justdelete` them
(5) What happens to the contents of containers when you call delete on the container? If the container held pointers?
Nothing happens to the pointer members of the container when it's deleted. You have to explicitly call delete on every member. By the way in your case, you can't delete your vector<Line*> because it's an object not a pointer & when you delete output;, you don't have to worry about contents of queue<> because they are not pointers.
(6) Those pointers are deleted won't that affect other areas of my program?
Deleting a valid pointer (i.e. allocated on heap) doesn't affect your program in any way.
-7511670 0I had the same feature in Aix and Linux implementations. In Aix, internal bitset storage is char based:
typedef unsigned char _Ty; .... _Ty _A[_Nw + 1]; In Linux, internal storage is long based:
typedef unsigned long _WordT; .... _WordT _M_w[_Nw]; For compatibility reasons, we modified Linux version with char based storage
Check which implementation are you using inside bitset.h
-9625734 0You are trying to do too much in the main method. You need to break this up into more manageable parts. Write a method boolean isPrime(int n) that returns true if a number is prime, and false otherwise. Then modify the main method to use isPrime.
I have one problem with google map, I used https://ngmap.github.io/#/!places-auto-complete.html.
I split my web app into multiple tabs and turn catch it by ng-if.
Currently in the main tab, I can google map fully loaded, but in others, it fails tab as shown below. The first image is the main tab, it's okay. But the 2nd picture is faulty, somebody please tell me why and how to fix me, please In tab Dashboard, google map is okay, but in tab Manage it does not load completely.
-36891296 0I don't think so. But if the goal is to match intents/actions inside your application (with associated topics) you have another solution. Please try LUIS (Language Understanding Intelligent Service) ; this service is part of Microsoft Cognitive Services.
Just perform a free speech and send the text to this service (once you train it). You can check the following video to obtain additional détails https://www.luis.ai/Help. Note: This is free until 100,000 transactions per month.
-33265909 0The problem is that you're trying to encode the whole URL. The only pieces you want to encode are the querystring values, and you can just use Url.Encode() for this.
You don't want to encode the address, the querystring params, or the ? and & delimiters, otherwise you'll end up with an address the browser can't parse.
Ultimately, it would look something like this:
<a href="https://www.notmysite.co.uk/controller/action?order_ID=@Url.Encode(Model.bookingNumber)&hashComparator=@Url.Encode(Model.hashCode)">Click Here to be transferred</a>
-28655156 0 Thank you, all commentors and visitors, especially @PM 77-1, I solved the problem with your help,
generally speaking, I need three things to initialize my JDBC tutorial, 1.MySQL 2.Eclipse and a nice plugin as an option 3.JDBC driver, for me it is mysql driver mysql.com/products/connector
use the @PM 77-1 provided tutorial to set up the project to manipulate the database.
But if you need a database GUI in Eclipse like me, you will need a plugin like DBview, my initial one database explorer is no longer in Eclipse. And remember to download the JDBC driver with .jar as the end. It can be find at platform independent version.
Ok that's all.
-29589230 0 Why wont my loop within a loop in Javascript work?This is suppose to store the chosen answer for multiple questions. When I use this code, it only checks the first question and disregards the other questions.
for(i = 0; i < questions.length-1; i++){ radios = document.getElementsByName(questions[i]); for (var t = 0; length < radios.length; t++) { if (radios[t].checked) { var qResults = JSON.parse(localStorage["qResults"]); num = radios[t].value; checked = num.toString(); var temp = (id[0] + ";" + questions[i] + ";" + checked); alert(temp); qResults.push(temp); localStorage["qResults"] = JSON.stringify(qResults); } } alert("question finished"); }
-31814343 0 The reason I believe this isn't working is you have no comparison try this. Other wise it will return 0 which is True.
KeepActive = "no match" For i = 1 To 500 If InStr(catchAll, Sheet4.Cells(i, 1).Value) > 0 Then KeepActive= "match" exit for End If Next i
-27093872 0 You can use nlargest from heapq module
import heapq heapq.nlargest(1, sentence.split(), key=len)
-25979649 0 dgrid editor with a dijit.form.Select I have a column in my dgrid that uses a digit.form.Select.
var gl = {}; gl.coverTypeEditorData = [{label: "C", value: "C"}, {label: "F", value: "F"}, {label: "G", value: "G"}, {label: "S", value: "S"}, {label: "P", value: "P"}]; ... ,editor({ 'label': 'Type', 'field': 'TYPE', 'editor': Select, 'editorArgs': { options: gl.coverTypeEditorData } } ) The select drop down displays the correct value, but when it closes the value in the cell gets changed to whatever value was last chosen.
Row 1: Change the value to S.
Row 2: Has value C. I select the dd but do not change the value. Display changes to S. Change row event does not fire. The cell has a S displaying but its actual value is C, which will be the selected value if I open the drop down again.
What do I need to add to get the cell to display the correct value?
-36282002 0 Handling option groups in Access form- runtime error 2427I have an option group on a form. I want the form to process code based on which button is selected. The snippet I have for now is:
If Me.Option18.Value = True Then DoCmd.OpenQuery "Logbook Query all available" End If Option 18 is the radio button on the form.
On the If line, I get 'run time error 2427: You entered an expression that has no value'
I tried different uses of me.option 18, and get the same error. I also tried replacing 'true' with 1, same result.
Is there a better way to execute code based on an option group selection. or is this simply a syntax error?
-9447184 0 Contactable pluginI'm using this plugin link
My question is, i want to remove the button (feedback) and instead use a normal link in my html page > < a href="#">Contact< /a> that trigger the plugin
I deleted this tag from .js file: < div id="contactable_inner">< /div> and now i want to attach my < a> link to the plugin
i don't know jQuery, can anyone help me plz?
I am trying to parse some JSON that I get via a web service. The logic is :
id jsonObject = ....; //This can be string or array if([jsonObject class] == [NSString class] || [jsonObject class] == [NSMutableString class]{ // DO some thing } else if([jsonObject class] = [NSArray class] || [jsonObject class] == [NSMutableArray class]{ // Do some thing else } However for one of the elements I ran into a weird problem. The class of this element should be NSArray but when I run the code I see the class as __NSArrayM. This does not match the second if block.
Can some one tell me what I am doing wrong
-28646088 0For anyone having the same issue with CocosSharp (the Xamarin C# port of Cocos2D):
To convert a CCColor3B to a CCColor4F, you can pass in the CCColor3B as a argument to the constructor of CCColor4F. For example:
var color = new CCColor4F (CCColor3B.Red); CCColor4B doesn't have a constructor with CCColor3B as an argument, so you have to pass in the individual values for Red, Green, and Blue, as follows:
var sourceColor = CCColor3B.Red; var color = new CCColor4B (sourceColor.R. sourceColor.G, sourceColor.B); I like to create extension methods to encapsulate the above, as follows:
public static class ColorExtensions { public static CCColor4F ToColor4F(this CCColor3B sourceColor) { return new CCColor4F (sourceColor); } public static CCColor4B ToColor4B(this CCColor3B sourceColor) { return new CCColor4B (sourceColor.R, sourceColor.G, sourceColor.B); } } So you can then perform conversions using the following:
var bColor = CCColor3B.ToColor4B(); var fColor = CCColor3B.ToColor4F();
-31093166 0 Polymer 1.0 Dom-Repeat Bind Array In my try to update to Polymer 1.0 I got the following problem with Data-Binding:
My Polymer 0.5 Webapp uses a Repeat-Template to generate Checkboxes for some Categories. All checked values are bound to an array (sortedCatsArray) with the category-ids as key. Here is my first attempt to update that part to Polymer 1.0, but it doesn't work...
<template is="dom-repeat" items="{{sortedCatsArray}}" as="category"> <paper-checkbox for category$="{{category.id}}" checked="{{filterChkboxes[category.id]}}"></paper-checkbox> </template> As you may read in the docs, it is no longer possible to bind to Array-Properties with square-brackets (now that way: object.property). May anybody tell me if it's still possible to bind all generated checkbox-values in one array?
Update #1
As you may read in the docs, Array-Binding by index is not supported. So I tried to use that example from the docs for my case and wrote the following code. If I run this code, it seems to work as expected: the first and third checkbox is checked. But I also want the array to be changed if I manual check/uncheck a checkbox. That does not happen, only if I change the array (in the ready-function) the checkbox gets checked...
<dom-module id="my-index"> <link rel="import" type="css" href="/css/index.css"> <template> <template is="dom-repeat" items="{{sortedCatsArray}}" as="category"> <paper-checkbox for category$="{{category.id}}" checked="{{arrayItem(filterChkboxes.*,category.id)}}" on-change="test"></paper-checkbox> </template> </template> </dom-module> <script> Polymer({ is: "my-index", properties: { filterChkboxes: { type: Array, notify: true, observer: "filterChkboxesChanged", value: function(){return[true,false,true,false];} }, sortedCatsArray: { type: Array, value: function(){return[{id: 0}, {id: 1},{id: 2},{id: 3}]}, notify: true }, }, ready: function(){ this.set('filterChkboxes.1',true); }, test: function(){ console.log(this.filterChkboxes); }, observers: [ 'filterChkboxesChanged(filterChkboxes.*)' ], arrayItem: function(array, key){ return this.get(key, array.base); }, filterChkboxesChanged: function(changes){ console.log(changes); }, }); </script>
-31041329 0 Kendo combobox not show the Text corresponding to value from modal I have a partial view with a combobox. When try to render partial view with modal(contains data from database), it shows only the value field. i want to show the text field of that value field. Help me please.
@(Html.Kendo().ComboBoxFor(m => m.divCode) .DataTextField("Name") .DataValueField("ID") .HtmlAttributes(new { style = "width:160px" }) .SelectedIndex(0) .AutoBind(false) .Placeholder("Select Div Code") .Filter(FilterType.Contains) .DataSource(source => { source.Read(read => { read.Action("GetDivision", "AssetTransaction"); }); }) )
-3258909 0 Collection of Property=>Value? I would like to create a collection of key, value pairs in C# where the key is a property of an ASP.net control (e.g. ID) and the value is the value of that property. I would like to do this so I may later iterate through the collection and see if a given control has the properties in my collection (and the values of the properties in the control match the values defined in my collection). Any suggestions as to the best way to do this? Thanks for any help.
Pseudo-code example:
Properties[] = new Properties[] {new Property(){name="ID",value="TestControl1"}, new Property(){name = "Text",value="Type text here"}} private bool controlContainsProperties(Control control){ foreach(Property Property in Properties[]) { if((control does not contain property) || (control property value != Property.Value)) return false; } return true; }
-22534739 0 The panel's update function expects a HTML string instead of a DOM object:
// using a HTML string Ext.getCmp('treeContainer').update("<div class='NodeContent'>" + node.displayText + "</div>"); // using a DOM object Ext.getCmp('treeContainer').update(nodeDiv.outerHTML); Note, that using this function will always replace all existing HTML content in the panel.
If you really want to append HTML (i.e. preserve existing HTML content), you need to get a target element to append your HTML/DOM node to.
This could be the panel's default render target element:
var panel = Ext.getCmp('treeContainer'), renderEl = panel.isContainer ? panel.layout.getRenderTarget() : panel.getTargetEl(); // using a DOM node renderEl.appendChild(nodeDiv); // using a HTML string renderEl.insertHtml('beforeEnd', "<div class='NodeContent'>" + node.displayText + "</div>"); Or - as this may change depending on your panel's layout - you just create a containg element in your initial html config:
{ xtype: 'panel', id: 'treeContainer', html: '<div class="html-content"></div>' } and append your content there:
Ext.getCmp('treeContainer').getEl().down('.html-content').appendChild(nodeDiv); In any of the latter two cases, you should update the panel's layout afterwards, as you changed it's content manually:
Ext.getCmp('treeContainer').updateLayout();
-39483032 0 One simple mistake in your approach.
The values from JSON are read as string and you are passing a string to element() and not a locator(not a by object)
var webElement = element(test.yourName); // Incorrect. test.yourName returns string Change it way and voila ! You should be good. Use eval(). Refer here
var webElement = element(eval(test.yourName));
-6183877 0 Javascript Patterns is a good book to learn object oriented programming and advanced concepts in javascript.
-3152493 0You may want to look unto how the rsync protocol works on Unix. It essentially computes the differences between two files and uses that to create a compressed delta used to compute the changes.
You may be able to adapt that to what you're trying to do.
-38442568 0 Problems with NSTokenView (again) - using objectvalueIn my Swift Application for Mac OS X, I'm using a NSTokenField. I'm using, among others, the delegate methods tokenField(tokenField: NSTokenField, representedObjectForEditingString editingString: String) -> AnyObject and tokenField(tokenField: NSTokenField, displayStringForRepresentedObject representedObject: AnyObject) -> String? to work with represented objects. My represented objects are instances of a custom class.
From the Apple Documentation, I know that objectValue can be used to access the represented objects of a NSTokenView as a NSArray:
To retrieve the objects represented by the tokens in a token field, send the token field an
objectValuemessage. Although this method is declared byNSControl,NSTokenFieldimplements it to return an array of represented objects. If the token field simply contains a series of strings,objectValuereturns an array of strings. To set the represented objects of a token field, use thesetObjectValue: method, passing in an array of represented objects. If these objects aren’t strings,NSTokenFieldthen queries its delegate for the display strings to use for each token.
However, this doesn't seem to work for me. let tokenArray = self.tokenField.objectValue! as! NSArray does return a NSArray, but it is empty, even though the delegate method required to return a represented object has been called the appropriate amount of times before.
NSTokenView doesn't seem like a particularly strong tool to work with tokenization, but, lacking an alternative, I hope that you guys can help me making my implementation work.
Thanks in advance!
-27766128 0Just add weight_1 and weight_2. igraph does not currently have a way to combine vertex/edge attributes from multiple graphs, except by hand. This is usually not a big issue, because it is just an extra line of code (per attribute). Well, three lines if you want to remove the _1, _2 attributes. So all you need to do is:
E(g3)$weight <- E(g3)$weight_1 + E(g3)$weight_2 and potentially
g3 <- remove.edge.attribute(g3, "weight_1") g3 <- remove.edge.attribute(g3, "weight_2") I created an issue for this in the igraph issue tracker, but don't expect to work on it any time soon: https://github.com/igraph/igraph/issues/800
-20129332 0 How to remove a directory when the cron job is within the child directoryI am new at Linux and I need to setup a script that after the work has been done using a cron job needs to delete the working directory.
The directory that I am in straight after the job is :
working/dealer/network/db/scripts I am doing this within the job to delete this whole path:
cd ~/working cd .. rm -rf working As I am new I am sure there is a better way of deleting the working directory and its subfolders. Please can someone help with this?
Thanks
-31685162 0You seem to be using JQuery correctly. The Javascript to extract the value and the send the GET request should be working.
Your misunderstanding lies in how you check if the PHP file has received the request. This redirect
location.href = "leaderprofile.php"; Will not provide you any information about the GET request that you just made. Instead you can try:
location.href = "leaderprofile.php?lname=" + $("#gopal").val() To verify that your PHP and Javascript is performing as expected. If you see the values that you expect then I believe you have confirmed two things:
A simple solution should be using the css3 transition. You can do something like this:
In Your CSS
#facebook_icon li{ -moz-transition: background-position 1s; -webkit-transition: background-position 1s; -o-transition: background-position 1s; transition: background-position 1s; background-position: 0 0; } #facebook_icon li:hover{ background-position: 0 -119px; }
-12610734 0 filter "items" with Jquery via a Dropdown I currently have Dropdown at the top of the page and a long list (83 boxes in rows of 4) underneath it.
Here is the scenario:
I select a state from the list of states in the dropdown, and the item in the list that do not match the state fade out allowing the matching items to "pop up" to the top. Once you go back to the default, all the others fade back in.
If there are no matching items to a state, I would display a message "no options found"
I am pretty sure I have seen this done on portfolios somewhere, but I really have no clue on how to achieve this. Does anyone have an idea on how to implement this, or can point me in the right direction?
<select id="filter" name="filter"> <option value="-1">Filter items</option> <option value="sc">South Carolina</option> <option value="nc">North Carolina</option> </select> <div id="container"> <div class="box state-nc"></div> <div class="box state-sc"></div> <div class="box state-nc"></div> <div class="box state-sc"></div> <div class="box state-nc"></div> <div class="box state-sc"></div> <div class="box state-nc"></div> <div class="box state-sc"></div> </div>
-24406553 0 Automatically send SCORM data to LMS I have this code so far...
function sendData() { // this work out where I am and construct the 'cmi.core.lesson.location' variable computeTime(); var a = "" + (course.length - 1) + "|"; for (i = 1; i < course.length; i++) { a = a + qbin2hex(course[i].pages).join("") + "|"; if (iLP == 1) { a = a + course[i].duration + "|"; a = a + course[i].timecompleted + "|" } } SetQuizDetails(); a = a + course[0].quiz_score_running + "|0|0|0|0|0|0|"; objAPI.LMSSetValue("cmi.core.lesson_location", "LP_AT7|" + a); bFinishDone = (objAPI.LMSCommit("") == "true"); objAPI.LMSCommit(""); console.log("Data Sent!"); } setTimeout(sendData(), 1000); However, it doesn't seem to work as intented. Data should be sent off to the server every 1000ms, but that's not happening. What am I missing here?
As I side note, this is SCORM 1.2.
-25743133 0 Are stack float array ops faster than heap float ops on modern x86 systems?On C float (or double) arrays small enough to fit in L1 or L2 cache (about 16k), and whos size I know at compile time, is there generally a speed benefit to define them within the function they are used in, so they are stack variables? If so is it a large difference? I know that in the old days heap variables were much slower than stack ones, but nowadays with the far more complicated structure of cpu addressing and cache, I don't know if this is true.
I need to do repeated runs of floating point math over these arrays in 'chunks', over and over again over the same arrays (about 1000 times), and I wonder if I should define them locally. I imagine keeping them in the closest / fastest locations will allow me to iterate over them repeatedly much faster but I dont understand the implications of caching in this scenario. Perhaps the compiler or cpu is clever enough to realize what I am doing and make these data arrays highly local on the hardware during the inner processing loops without my intervention, and perhaps it does a better job than I can at this.
Maybe I risk running out of stack space if I load large arrays in this way? Or is stack space not hugely limited on modern systems? The array size can be defined at compile time and I only need one array, and one CPU as I need to stick to a single thread for this work.
-20211261 0You need to store the locale of the language that was selected on the login form and then make use of it when you generate your UIs after login. So instead of using
ResourceBundle.getBundle("basic", new Locale("en", "US")); you then would use
ResourceBundle.getBundle("basic", classWhereTheLocaleIsStores.getLocale());
-1537279 0 window.location.href = "someurl";
-16581881 0 You need to have the executable bit set on the script:
chmod +x /path/to/your/script
-25158487 0 rendering partial using jquery in js.erb file giving error. render is not a function below is code in file 'app_erb.js.erb'
$(function(){ $('.add_more_element').click(function(e){ e.preventDefault(); $(this).siblings('.remove_this_element').show('slow'); $(this).hide('slow'); $(this).closest('.form-group').add('<%=j render 'resumes/resume_certification' %>'); }); }); and i have partial views/resumes/_resume_certification.html.erb
but when i load my app it gives me NoMethodError at /resumes/new undefined method `render'.
What i am missing in the whole process for rendering a partial using javascript.
-19038964 0It's not entirely clear what you're asking in the question and the comments, but it sounds like you might be looking for a full join with a bunch of coalesce statements, e.g.:
-- create view at your option, e.g.: -- create view combined_query as select coalesce(a.id, b.id) as id, coalesce(a.delta, b.delta) as delta, a.metric1 as metric1, b.metric2 as metric2, coalesce(a.metric1,0) + coalesce(b.metric2,0) as combined from (...) as results_a a full join (...) as results_b b on a.id = b.id -- and a.delta = b.delta maybe?
-37371727 0 Same code in Codepen giving diffferent results I have this pen: https://codepen.io/dteiml/full/PNMwZo with the following javascript code:
$('#getWeather').on('click', function() { navigator.geolocation.getCurrentPosition(success); function success(pos){ // get longitude and latitude from the position object passed in var lng = pos.coords.longitude; var lat = pos.coords.latitude; // and presto, we have the device's location! console.log("test"); $('body').html('You appear to be at longitude: ' + lng + ' and latitude: ' + lat); } }); and html code:
<button id="getWeather"> Get my location </button> <body> </body> that I forked from somebody that works and one that I created myself http://codepen.io/dteiml/full/aNevrE with the same exact code and settings that doesn't work. What might be the problem?
-15882930 0$(this).addClass('myClass'); would work but use:
var img = $("<img />", { "src" : '/images/favicon.png', "class" : 'myClass' }) .error(function(){ console.log('error'); }) .load(function(){ img.appendTo( theParent ); });
-12545561 0 How can I use HTML5 to both record audio (speech) and convert the recorded speech into text? I have a project in mind where I want users to record speech in a browser. I know that for recording audio I can use getUserMedia and for speech to text input I can use x-webkit-speech. I'm OK with the browser limitation. Is there a way that I can do this in a single step?
I'd prefer an HTML5 solution, but I'm willing to go with javascript if that's the only way to do it. I'm also willing to consider server side solutions if necessary (LAMP environment). This would likely be only accessed on a laptop/desktop browser, but if I can also make it compatible with mobile devices, that would be great, too.
-25083419 0You can do
CREATE FOREIGN TABLE cases( id varchar(50) PRIMARY KEY, CaseId varchar(50), CaseAddressString varchar(50), CaseOpenDatetime date, CaseBeginDatetime date, CaseDescription varchar(200), RequestorFirstName varchar(50), RequestorLastName varchar(50), CaseCurrentStatus varchar(25), age integer, gender varchar(20), CaseLat float, CaseLong float, ServiceName varchar(50) ) OPTIONS(UPDATABLE 'TRUE'); CREATE FOREIGN TABLE CasePhoneNumbers ( caseid varchar, type string, number string, FOREIGN KEY (caseid) REFERENCES cases (_id) ) OPTIONS(UPDATABLE 'TRUE', "teiid_mongo:MERGE" 'cases') You can see more documentation at https://docs.jboss.org/author/display/TEIID/MongoDB+Translator
https://issues.jboss.org/browse/TEIID-3040 removes th verbose IDREF fields, but this will be in Teiid 8.9
-21932583 0 Codeigniter error Unable to load the requested file 0.php but theres no such fileI am new to Codeigniter and it is throwing the error: unable to load the requested file 0.php
But there's no such file! I don't understand why its doing this?
As a result of this error, the homepage of my site has vanished. All the other pages are accessible and work except for the homepage.
I don't know where I'm supposed to look, whether its the view files or the controller files?
Can anyone shed any light on this?
-38060747 0Change this to (Best Practices)
if ($this->form_validation->run() == TRUE) this
if ($this->form_validation->run() == FALSE) Since you haven’t told the Form Validation class to validate anything yet, it returns FALSE (boolean false) by default.
The run()method only returns TRUE if it has successfully applied your rules without any of them failing.
Add this in controller
$this->form_validation->set_error_delimiters('<div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>', '</div>'); and remove this
echo validation_errors('<div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>', '</div>'); Add this in form below the respective input fields
echo form_error('usuario'); echo form_error('senha'); Or add
<?php echo validation_errors(); ?> CodeIgniter Form Validation Example
-15721987 0 flash website content box hiding the menuMy website is: http://harringtonplanningdesign.com When I move the cursor on the flash box the menu is disappearing. How can I keep the menu from hiding when the cursor is on the flash content box? That means I do not want to hide the menu when the mouse is moved.
The home page code is here:
<html> <head> <title>Harrington Planning + Design</title> <script type="text/javascript" src="com/swfobject/swfobject.js"></script> <script type="text/javascript" src="com/swfaddress/swfaddress.js"></script> <script type="text/javascript" src="com/pixelbreaker/swfmacmousewheel.js"></script> <style type="text/css"> html { height: 100%; overflow: hidden; overflow-y: hidden; } #flashcontent { height: 100%; } body { height: 100%; margin: 0; padding: 0; background-color: #FFFFFF; overflow-y: hidden; } </style> </head> <body> <div id="flashcontent"> </div> <script type="text/javascript"> // <![CDATA[ var so = new SWFObject('container.swf', 'container', '100%', '100%', '9', '#FFFFFF'); so.useExpressInstall('com/swfobject/expressinstall.swf'); so.addParam('allowFullScreen','true'); so.addParam('menu','false'); if( so.write('flashcontent') ) { var macmousewheel=new SWFMacMouseWheel(so); } // ]]> </script> </body>
-28110474 0 Should I add publish_actions for review after migrating old app to Graph API v2.2? I've been updating few web apps to the latest Facebook Graph API - v2.2. Those sites work and some of them have opengraph action video.watches ("Watch"). It's approved and works.
Recently I got a generic Facebook email that one or more of my apps are using permissions that have to be reviewed or they will stop working on some date. As those apps are quite old they don't have publish_actions in the review set (and that's the only extra permission in that video.watches websites). So now - does Facebook wants that publish_actions to be added to the review or it's something else (they could be more specific)?
-4616971 0You should be able to do this with mechanize. It emulates a real broswer, and is quite powerful. About the only major feature lacking is a javascript engine, so it won't work if the blog uses javascript in its authentication.
-20888726 0Well, if your old one is working then the problem will be in your rewrite. Don't pay too much notice to the error messages, they're pretty much par for the course, and can be triggered by something as benign as a cache miss. Unless you're actually getting an error callback somewhere, the log messages are meaningless.
As for your problem, I can't really make any guesses without seeing your code. One thing to check and is the most common course of a permanent error is to make sure you're actually logged in. The login process is asynchronous, and any functionality that requires you to be logged in (searching is one of them) will fail before login is completed.
-22814123 0 How to correctly affect multiple css properties in jqueryBelow is an example of how I currently would affect two css properties for the same div in jquery:
$('#mydiv').css("width",myvar+"px"); $('#mydiv').css("margin-left",myvar+"px"); I don't believe this to be the most efficient method as it requires two lines of code for one div, can somebody please show me a more susinct (tidier) method of writing the same thing?
-21164629 0To use recursion you should have a stop test and be sure to always launch the next step on a smaller problem.
Try this : (Not sure if Array.SubArray(int) is a real function but that is the idea.
static void Main(string[] args) { int[] Array=new int[]{10,233,34}; int _MaxVal = CalculateMax(Array); Console.WriteLine(_MaxVal); Console.ReadKey(); } private static int CalculateMax(int[] Array) { if (Array.Length > 0) { int maxSubArray = CalculateMax(Array.SubArray(1)); // Use recursive function on the SubArray starting at index 1 (that the smaller problem) if (maxSubArray > Array[0]) { return maxSubArray; } else { return Array[0]; } } else { return 0; // Stop test } } Note : it will not work with negative value.
-17935206 0 How to layout correctlyI just try to create my own layout. I used UITableView for my UIViewController. I have some JSON response from server. This is like detailed publication. Also i calculate my UITableViewCell height because my publication contain mix of images and text. I wrote own layout and recalculate when device in rotation.
for (UIView * sub in contentSubviews) { if([sub isKindOfClass:[PaddingLabel class]]) { PaddingLabel *textPart = (PaddingLabel *)sub; reusableFrame = textPart.frame; reusableFrame.origin.y = partHeight; partHeight += textPart.frame.size.height; [textPart setFrame:reusableFrame]; } else if([sub isKindOfClass:[UIImageView class]]) { UIImageView * imagePart = (UIImageView *)sub; reusableFrame = imagePart.frame; reusableFrame.origin.y = partHeight; reusableFrame.origin.x = screenWidth/2 - imageSize.width/2; reusableFrame.size.width = imageSize.width; reusableFrame.size.height = imageSize.height; [imagePart setFrame:reusableFrame]; partHeight += imagePart.frame.size.height; } } But I have some issue. When device change orientation state UIScrollView offset is same as was. I don't know how to change it. Before rotation:

After rotation:

I want to save visible elements in rect. Suggest pls.
-20421720 0consumer reads for a while and then shuts down due to any reason
Not sure what exactly are you referring to as the consumer is supposed to run infinitely unless it is stopped explicitly.
Now assuming you are using the storm's KafkaSpout implementation, there is a config called forceStartOffsetTime which is used to force the spout to rewind to a previous offset. The way to use it as follows
spoutConfig.forceStartOffsetTime(-2); As seen in the doc page
It will choose the latest offset written around that timestamp to start consuming. You can force the spout to always start from the latest offset by passing in -1, and you can force it to start from the earliest offset by passing in -2.
so setting it to -2 will always force it to read from the start what is the configuration you are using, would be great if you could post some code
-27720368 0Make sure socket.io script is included and define sensor var for get it working as
var socket = io('http://localhost'); And finally get sure clicked function is getting called when event is fired.
Hope it helps!
-17081069 0 Encryption password algorithms on OpenLDAPa question about OpenLDAP. Where can I find some informations about OpenLDAP supported password encryption algorithms on last version (2.4.35)?
-14250715 0 servicestack ormlite sqlite DateTime getting TimeZone adjustment on inserti'm trying ormlite. i'm finding that when i insert an object with a DateTime property, it is getting -8:00 (my timezone is +8) applied by ormlite. It should be inserted with literally what the time is. in my case it is already UTC.
however reading the values out of ormlite, the +8 is not getting re-applied.
is this a known bug?
thanks
-2512863 0 Have you been in cases where TDD increased development time?I was reading TDD - How to start really thinking TDD? and I noticed many of the answers indicate that tests + application should take less time than just writing the application. In my experience, this is not true. My problem though is that some 90% of the code I write has a TON of operating system calls. The time spent to actually mock these up takes much longer than just writing the code in the first place. Sometimes 4 or 5 times as long to write the test as to write the actual code.
I'm curious if there are other developers in this kind of a scenario.
-3998271 0There is no difference in reading standard input from threads except if more than one thread is trying to read it at the same time. Most likely your threads are not all calling functions to read standard input all the time, though.
If you regularly need to read input from the user you might want to have one thread that just reads this input and then sets flags or posts events to other threads based on this input.
If the kill character is the only thing you want or if this is just going to be used for debugging then what you probably want to do is occasionally poll for new data on standard input. You can do this either by setting up standard input as non-blocking and try to read from it occasionally. If reads return 0 characters read then no keys were pressed. This method has some problems, though. I've never used stdio.h functions on a FILE * after having set the underlying file descriptor (an int) to non-blocking, but suspect that they may act odd. You could avoid the use of the stdio functions and use read to avoid this. There is still an issue I read about once where the block/non-block flag could be changed by another process if you forked and exec-ed a new program that had access to a version of that file descriptor. I'm not sure if this is a problem on all systems. Nonblocking mode can be set or cleared with a 'fcntl' call.
But you could use one of the polling functions with a very small (0) timeout to see if there is data ready. The poll system call is probably the simplest, but there is also select. Various operating systems have other polling functions.
#include <poll.h> ... /* return 0 if no data is available on stdin. > 0 if there is data ready < 0 if there is an error */ int poll_stdin(void) { struct pollfd pfd = { .fd = 0, .events = POLLIN }; /* Since we only ask for POLLIN we assume that that was the only thing that * the kernel would have put in pfd.revents */ return = poll(&pfd, 1, 0); } You can call this function within one of your threads until and as long as it retuns 0 you just keep on going. When it returns a positive number then you need to read a character from stdin to see what that was. Note that if you are using the stdio functions on stdin elsewhere there could actually be other characters already buffered up in front of the new character. poll tells you that the operating system has something new for you, not what C's stdio has.
If you are regularly reading from standard input in other threads then things just get messy. I'm assuming you aren't doing that (because if you are and it works correctly you probably wouldn't be asking this question).
-37585406 0I think your message.string is nil when passed to UIAlertController. Check it twice.
Print message after getting so you know that what you get in it.
You can put breakpoints also to check that you are getting data or not.
-3093790 0normally you use Number() or parseInt("", [radix]) to parse a string into a real number.
I am guessing you are asking about what happens when the string you parse is above the int - threshold. in this case it greatly depends on what you are trying to accomplish.
There are some libraries that allow working with big numbers such as http://www.leemon.com/crypto/BigInt.js (did not test it, but it looks ok). Also try searching for BigInt javascript or BigMath.
In short: working with VERY large number or exact decimals is a challenge in every programming language and often requires very specific mathematical libraries (which are less convenient and often a lot slower then when you work in "normal" (int/long) areas) - which obviously is not an issue when you REALLY want those big numbers.
-18251196 0oracle docs provide a good answer to this. Bottom line: finally gets called always! Even when you catch only one kind of exception (not the global catch), then finally gets called (after which your application probably breaks if there is no other catch)
-4108113 0 php fopen: failed to open stream: HTTP request failed! HTTP/1.0 403I am receiving an error message in PHP 5 when I try to open a file of a different website. So the line
fopen("http://www.domain.com/somefile.php", r) returns an error
-6051726 0Warning: fopen(www.domain.com/somefile.php) [function.fopen]: failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden in D:\xampp\htdocs\destroyfiles\index.php on line 2
You probably want to check if the device supports WPD, the replacement of WIA in Vista or later. If the device does not support WPD, then try access the device with WIA Automation Layer. It can't handle WIA device-specific problems for sure, but at least it is good for standardized behavior. If neither WPD nor WIA is supported, I am afraid you have to deal with the old TWAIN interface.
The WIA documentation in Windows Driver Kit is on par with the documentation in Windows SDK. Don't be surprised if a driver developer fails to follow the WIA driver guidelines. If you travel WIA scanner trees, make sure you are aware of the difference of tree layout for Windows XP, Vista and Windows 7.
There is a discussion about wrappers of these APIs for .Net applications at .NET Scanning API.
-31892188 0You can overcome this easily by using the ChoiceMode option CHOICE_MODE_MULTIPLE for the ListView as used in the API Demo -
public class List11 extends ListActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, GENRES)); final ListView listView = getListView(); listView.setItemsCanFocus(false); listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); } private static final String[] GENRES = new String[] { "Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama", "Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller" }; } EDIT Alternate for your context- Have an extra boolean object with your HashMap<String, Object> isChecked and initialize it to false when you populate your list.
Set your CheckBox in getView() method as-
check.setChecked(Boolean.parseBoolean(dataMap.get("isChecked")); Now in the listener OnCheckedChangeListener() set the value of your dataMap true or false accordingly.
Doesn't look like the ShareTarget/DataTransfer APIs are available in the API set that's tagged as being okay to use from Desktop so it looks like you're out of luck for now.
-30158254 1 Storing an object of a class then calling a function in that objectI have a class like this (scaled down)
class FileAndWriter(object): def __init__(self, symbol, start_dt_str): self.data = [] self.fileName = symbol.replace("/", "") + '-' + start_dt_str + '.csv' self.file = open(self.fileName, 'ab') self.csvWiter = csv.writer(self.file, delimiter=',') # , quoting=csv. QUOTE_ALL def write_rows(self): self.csvWiter.writerows(self.data) self.file.flush() def appendData(dataMsg): try: self.data.append(dataMsg) if len(self.data) > 100: self.write_rows(self.data) self.data = [] except: print "appendData error:", sys.exc_info()[0] I have another class that composes that class like this. update is a callback function of Observer:
class SymbolWriter(Observer): def __init__(self, symbol, sd, ed): self.writers = {} self.symbol = symbol self.start_date = sd self.end_date = ed for single_date in daterange(self.start_date, self.end_date): single_date_str = single_date.strftime('%Y%m%d') faw = FileAndWriter(self.symbol, single_date_str) print 'FAW ', single_date_str self.writers[single_date_str] = faw def update(self, dataMsg): try: today = datetime.datetime.utcnow() today_str = today.strftime('%Y%m%d') print today_str if today_str in self.writers: #print 'Writting' faw = self.writers[today_str] if faw is not None: faw.appendData(dataMsg) except: print "update error:", sys.exc_info()[0] It excepts on faw = self.writers[today_str] with update error: <type 'exceptions.TypeError'>
How does one store an object in a dictionary and call a member function? Or is there something else I am not noticing?
-7790366 0If you run your regex snippet in a C# program, I have the solution for you:
Regex regex = new Regex(@"(?<=\{{1}[\s\r\n]*)((?<Attribute>[^}:\n\r\s]+):\s+(?<Value>[^;]*);[\s\r\n]*)*(?=\})"); regex.Replace(input, match => { var replacement = string.Empty; for (var i = 0; i < match.Groups["Attribute"].Captures.Count; i++) { replacement += string.Format(CultureInfo.InvariantCulture, "{0}: {1}\r\n", match.Groups["Attibute"].Captures[i], match.Groups["Value"].Captures[i]); } return replacement; });
-22901149 0 if ($contract['Contract']['contract_maandag'] = 1){ if ($contract['Contract']['contract_dinsdag'] = 1){ This won't work. You're doing an assignment (=), so it's always true. But you want a comparison (===). It is recommended to do always (except required otherwise) to use strict (===) comparison.
-8849649 0For subdomains in routes check this guide to domain routing
When you have it set up. for a specific redirection you can use this:
return RedirectToAction("SpecificAction", "SpecificController", new { subdomain = "blahblah"); As for the post part, you can just use the TempData dictionary (TempData["varName"]) to pass the data to the next controller/action
-30076155 0 Refresh Index after redirecting to it from AJAX callI have a situation where I am setting a user value and trying to reload the index page. This is only a sample page and I cannot user any kind of user controls, like ASP.NET. Each user is in the database and the role is retrieved from there. My index is this:
[HttpGet] public ActionResult Index(long? id) { AdminModel admin = new AdminModel(); UserModel usermodel = new UserModel(); if (id != null) { admin.UserModel = usermodel; admin.UserModel.UserId = id.ToString(); admin.UserModel = UserAndRoleRepository.GetOrStoreUserProfile(admin.UserModel.UserId); } else { admin.UserModel = usermodel; admin.UserModel = UserAndRoleRepository.GetOrStoreUserProfile(currentUser); } return View(admin); } This works fine when first loaded. In the page I am setting values based upon the user role:
$(document).ready(function () { debugger; user = function () { return @Html.Raw(Json.Encode(Model)) }(); if (user.UserModel != null) { if (user.UserModel.UserRole == 'ADMIN') { $("#btnAdmin").show(); $("#btnTran").show(); $("#btnNew").show(); $("#btnAdjust").show(); $("#btnReports").show(); } if (user.UserModel.UserRole == 'TRANS') { $("#btnReports").show(); $("#btnTran").show(); } if (user.UserModel.UserRole == 'REPORTS') { $("#btnReports").show(); } } }); The AJAX call is this:
$.ajax({ type: 'POST', dataType: 'json', url: '@Url.Action("SetUser")', data: { userid: ui.item.value }, success: function (data) { if (data == null) { } else { } }, error: function (xhr) { //var err = xhr.responseText; //alert('error'); } }); And the SetUser action:
[HttpPost] public ActionResult SetUser(string userid) { return RedirectToAction("Index", new { id = Convert.ToInt64(userid) }); } This works fine in that the Index method is fired with the chosen ID, but the page does not reload to be able to set the buttons. Any ideas?
-33070119 0I assume that you have the models Show and User connected by a Following model for the n:m relation.
When you retrieve the shows, you can left join the Followings with a user_id of current-user. The result set will have the fields for Following set if there is such a following, and not if the user is not following.
Note you need to select the fields from Following model explicitly, otherwise the join will only return fields from the Show model
You should use ArrayList rather than Vector. There is no simple way to convert though. One way is
ArrayList<String> list = new ArrayList<String>(); for (char a : x) list.add(String.valueOf(a)); Arrays.asList works for arrays of object references, not arrays of primitives like char.
If you are using Java 8, another way is
List<String> list = IntStream.range(0, x.length) .mapToObj(i -> String.valueOf(x[i])) .collect(Collectors.toList());
-5093338 0 Thinking in high level, this is what I'd do:
Develop a decorator function, with which I'd decorate every event-handling functions.
This decorator functions would take note of thee function called, and its parameters (and possibly returning values) in a unified data-structure - taking care, on this data structure, to mark Widget and Control instances as a special type of object. That is because in other runs these widgets won't be the same instances - ah, you can't even serialize a toolkit widget instances, be it Qt or otherwise.
When the time comes to play a macro, you fill-in the gaps replacing the widget-representating object with the instances of the actually running objects, and simply call the original functions with the remaining parameters.
In toolkits that have an specialized "event" parameter that is passed down to event-handling functions, you will have to take care of serializing and de-serializing this event as well.
I hope this can help. I could come up with some proof of concept code for that (although I am in a mood to use tkinter today - would have to read a lot to come up with a Qt4 example).
-36256630 0 Angular ng-options doesn show all elementsI am working in some app with AngularJS and I am using the ng-options directive, but I have one problem. When I select the "Provincia", the "Cantón" select only shows the last element in the array.
Anyone knows what is the problem?
This is my HTML code:
<div class="form-group"> <select class="form-control" ng-model="selected.provincia" ng-options="p.provincia for p in geografiaCR"> <option value="" disabled selected hidden>Seleccione una provincia</option> </select> </div> <div class="form-group"> <select class="form-control" ng-model="selected.nombre" ng-options="n.nombre for n in selected.provincia.cantones"> <option value="" disabled selected hidden>Seleccione un cantón</option> </select> </div> And this is the Angular code:
$scope.selected = {}; $scope.geografiaCR = [ { provincia: 'San José', cantones: [{nombre: 'San José',nombre: 'Escazú',nombre: 'Desamparados',nombre: 'Puriscal',nombre: 'Tarrazú', nombre: 'Aserrí',nombre: 'Mora',nombre: 'Goicochea',nombre: 'Santa Ana', nombre: 'Alajuelita', nombre: 'Acosta',nombre: 'Tibás',nombre: 'Moravia',nombre: 'Montes de Oca',nombre: 'Turrubares', nombre: 'Dota',nombre: 'Curridabat',nombre: 'Perez Zeledón', nombre: 'León Cortes'}] }, { provincia: 'Limón', cantones: [{nombre: 'Limón',nombre: 'Pocosí',nombre: 'Siquirres',nombre: 'Talamanca',nombre: 'Matina', nombre: 'Guácimo'}] } ];
-12873142 0 invalid application of 'sizeof' to incomplete type 'struct array[]' I am trying to organize my project by splitting commands up into separate files for easier maintenance. The issue I am having is trying to iterate over the array of commands defined at compile time. I have created a dumbed down example that reproduces the error I am getting.
. ├── CMakeLists.txt ├── commands │ ├── CMakeLists.txt │ ├── command.c │ ├── command.h │ ├── help_command.c │ └── help_command.h └── main.c PROJECT(COMMAND_EXAMPLE) SET(SRCS main.c) ADD_SUBDIRECTORY(commands) ADD_EXECUTABLE(test ${SRCS}) SET(SRCS ${SRCS} command.c help_command.c) #ifndef COMMAND_H #define COMMAND_H struct command { char* name; int (*init)(int argc, char** argv); int (*exec)(void); }; extern struct command command_table[]; #endif #include "command.h" #include "help_command.h" struct command command_table[] = { {"help", help_init, help_exec}, }; #ifndef HELP_COMMAND_H #define HELP_COMMAND_H int help_command_init(int argc, char** argv); int help_command_exec(void); #endif #include "help_command.h" int help_command_init(int argc, char** argv) { return 0; } int help_command_exec(void) { return 0; } #include <stdio.h> #include "commands/command.h" int main(int argc, char** argv) { printf("num of commands: %d\n", sizeof(command_table) / sizeof(command_table[0])); return 0; } If you run this
mkdir build && cd build && cmake .. && make the following error occurs
path/to/main.c:6:40: error: invalid application of 'sizeof' to incomplete type 'struct command[]' So, how do I iterate over command_table if I can't even determine the number of commands in the array?
I realize there are other posts out there with this same error, but I've spent a while now trying to figure out why this doesn't work and continue to fail:
This returns the sequence you look for:
var result = MyList .Select(s => s.Split('-').OrderBy(s1 => s1)) .Select(a => string.Join("-", a.ToArray())) .Distinct(); foreach (var str in result) { Console.WriteLine(str); } In short: split each string on the - character into two-element arrays. Sort each array, and join them back together. Then you can simply use Distinct to get the unique values.
Update: when thinking a bit more, I realized that you can easily remove one of the Select calls:
var result = MyList .Select(s => string.Join("-", s.Split('-').OrderBy(s1 => s1).ToArray())) .Distinct(); Disclaimer: this solution will always keep the value "A-B" over "B-A", regardless of the order in which the appear in the original sequence.
-15242260 0 Error in installing ATF in eclipseIn eclipse JUNO->install new software->http://download.eclipse.org/tools/atf/updates/0.3.0
but it gives me this error
Cannot complete the install because one or more required items could not be found. Software being installed: AJAX Tools Framework Webtools Integration (Incubation) 0.3.0.v201006041600-15-7zCN3HbXIOZQuUeDRRMG (org.eclipse.atf.feature.feature.group 0.3.0.v201006041600-15-7zCN3HbXIOZQuUeDRRMG) Missing requirement: AJAX Tools Framework Mozilla IDE (Incubation) 0.3.0.v201006041600-17K-DZRDIXEqJdCQQLF (org.eclipse.atf.mozilla.ide.feature.feature.group 0.3.0.v201006041600-17K-DZRDIXEqJdCQQLF) requires 'org.mozilla.xpcom.feature.feature.group 1.8.1' but it could not be found Cannot satisfy dependency: From: AJAX Tools Framework Webtools Integration (Incubation) 0.3.0.v201006041600-15-7zCN3HbXIOZQuUeDRRMG (org.eclipse.atf.feature.feature.group 0.3.0.v201006041600-15-7zCN3HbXIOZQuUeDRRMG) To: org.eclipse.atf.mozilla.ide.feature.feature.group [0.3.0.v201006041600-17K-DZRDIXEqJdCQQLF]vCannot complete the install because one or more required items could not be found. Software being installed: AJAX Tools Framework Webtools Integration (Incubation) 0.3.0.v201006041600-15-7zCN3HbXIOZQuUeDRRMG (org.eclipse.atf.feature.feature.group 0.3.0.v201006041600-15-7zCN3HbXIOZQuUeDRRMG) Missing requirement: AJAX Tools Framework Mozilla IDE (Incubation) 0.3.0.v201006041600-17K-DZRDIXEqJdCQQLF (org.eclipse.atf.mozilla.ide.feature.feature.group 0.3.0.v201006041600-17K-DZRDIXEqJdCQQLF) requires 'org.mozilla.xpcom.feature.feature.group 1.8.1' but it could not be found Cannot satisfy dependency: From: AJAX Tools Framework Webtools Integration (Incubation) 0.3.0.v201006041600-15-7zCN3HbXIOZQuUeDRRMG (org.eclipse.atf.feature.feature.group 0.3.0.v201006041600-15-7zCN3HbXIOZQuUeDRRMG) To: org.eclipse.atf.mozilla.ide.feature.feature.group [0.3.0.v201006041600-17K-DZRDIXEqJdCQQLF]
thanks
It sounds like an encoding issue. You're probably saving down as a different encoding to the original document, and different from what the target application is expecting. Hence the change in file size.
It's possible to change the encoding used for the save as described by dbc above:
-20393637 0 SQL - Display all empty rows with Count() Group ByCreate an XmlWriterSettings, set XmlWriterSettings.Encoding as appropriate, then create an XmlWriter and pass it to XDocument.Save().
These are my tables:
Categories table ================ id (fk) category_name Items table =========== id (pk) item_name category_id (pk) One category has many Items
One item have one category
Let's say I have these data:
Categories ========== id category_name ----------------------- 1 Foods 2 Beverages 3 Computer 4 Cats Items ===== id item_name category_id(fk) 1 Rice 1 2 Chicken 1 3 Mouse 3 4 Keyboard 3 Query that I used to count items grouped by category name:
SELECT categories.id, categories.category_name, COUNT(items.item_name) AS items FROM items INNER JOIN categories ON items.category_id = categories.id GROUP BY category_name I've tried the above query to display the counting, but it doesn't show all rows from Categories table. Well, of course some item might not be in a category, but how do I show the empty Category as well?
-38134865 0 Copying specific struct members to another structureso I have a file from which I have to load a number of tracks, find tracks longer than 3:30 and find the average bpm of those tracks.
Here's the code I have.
Main file:
#include <stdio.h> #include "functions.h" int main(void) { Playlist *all, *long_tracks; float avg_bpm; all = load_tracks("tracks.txt"); long_tracks = get_tracks_longer_than(3,30,all); print_playlist(long_tracks); avg_bpm = get_avg_bpm(long_tracks); printf("Average BPM of the playlist is: %.2f\n", avg_bpm); return 0; } Header:
#ifndef FUNCTIONS_H #define FUNCTIONS_H typedef struct track { char track[250]; float bpm; int mm, ss; } Track; typedef struct playlist { int count; Track **tracks; } Playlist; void print_playlist(Playlist *list); Playlist* load_tracks(char *filename); Playlist* get_tracks_longer_than(int mm, int ss, Playlist* all); float get_avg_bpm(Playlist *list); #endif Functions:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "functions.h" void print_playlist(Playlist *list) { int i; for (i = 0; i < list->count; i++) { printf("%s (%d:%d) [%f]\n", list->tracks[i]->track, list->tracks[i]->mm, list->tracks[i]->ss, list->tracks[i]->bpm); } } Playlist* load_tracks(char *filename) { int n,i; Playlist *list = (Playlist*) malloc(sizeof(Playlist)); Track *tracks; FILE *f = fopen(filename, "r"); fscanf(f, "%d", &n); printf("Tracks: %d\n", n); tracks = (Track*) malloc(n*sizeof(Track)); list->tracks = (Track**) malloc(n*sizeof(Track*)); for (i = 0; i < n; i++) { fscanf(f, "%d:%d", &tracks[i].mm, &tracks[i].ss); fscanf(f, "%f", &tracks[i].bpm); fgetc(f); fgets(tracks[i].track, 250, f); tracks[i].track[strlen(tracks[i].track)-1] = '\0'; list->tracks[i] = &tracks[i]; } list->count = n; return list; } Playlist* get_tracks_longer_than(int mm, int ss, Playlist* all) { Playlist *longSongs = (Playlist*) malloc(sizeof(Playlist)); Track *tracks; tracks = (Track*) malloc(all->count*sizeof(Track)); longSongs->tracks = (Track**) malloc(all->count*sizeof(Track*)); int i, n = 0; for(i=0;i<all->count;i++) { if(all->tracks[i]->mm>mm) { n++; memcpy ( &longSongs, &all, sizeof(all) ); //I also tried longSongs[i]=all[i]; } else if(all->tracks[i]->mm==mm) { if(all->tracks[i]->ss>ss) { n++; memcpy ( &longSongs, &all, sizeof(all) ); } } } longSongs->count=n; return longSongs; } float get_avg_bpm(Playlist *list) { float avg_bpm=0; int i; for(i=0;i<list->count;i++) { avg_bpm+=list->tracks[i]->bpm; } return avg_bpm/=list->count; } Problem is in my get_tracks_longer_than function, in which I don't really know how to copy the struct member I want from source structure to the destination structure, I only managed to copy all members from one structure to the other. My n counter counts number of tracks correctly, and my function which calculates bpm seems to work, but I don't know how to get the exact data I want. I tried using memcpy function, tried assigning it like this: longSongs[i]=all[i], and I tried manually assigning values, e.g:
longSongs->tracks[i]->mm = all->tracks[i]->mm; longSongs->tracks[i]->ss = all->tracks[i]->ss; longSongs->tracks[i]->bpm = all->tracks[i]->bpm; but nothing works, it always copies all members of the source structure, ignoring my if statements.
-20498360 0 Android logcat errors on projectI'm trying to run a project in Android but it crashes upon trying to execute it: I don't really understand the logCat messages I get so I wanted to see if someone could help me out in understanding them.
Here are some of my errors:
FATAL EXCEPTION: MAIN java.lang.RunTimeException: Unable to start activity componentInfo (com.example.logger/com.example.logger.ThirdActivity):java.lang.RuntimeException: your content must have a ListView whose id attribe is 'android.R.id.list'; Caused by: java.lang.RuntimeException: your content must have a ListView whose id attribute is 'android.R.id.list'; at.com.example.logger.ThirdActivity.onCreate (ThirdActivity:java:18) Android Manifest
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.logger" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.logger.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.example.logger.SecondActivity" android:label="@string/title_activity_second" ></activity> <activity android:name="com.example.logger.ThirdActivity" android:label="@string/title_activity_third" > </activity> </application> </manifest> End manifest
Main Activity
package com.example.logger; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; public class MainActivity extends Activity implements OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); attachHandlers(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } private void attachHandlers() { findViewById(R.id.login).setOnClickListener(this); } @Override public void onClick(View arg0) { if(arg0.getId() == R.id.login) { Intent i = new Intent(this, SecondActivity.class); startActivity(i); } } }
End Main Activity
SecondActivity
package com.example.logger; import android.os.Bundle; import android.annotation.SuppressLint; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.widget.ImageView; import android.view.ViewGroup; public class SecondActivity extends Activity { private static final int NUM_PAGES = 10; private ViewPager mpager; private MyPagerAdapter mPagerAdapter; private int [] pics = {R.drawable.android_interfaz_layout_estructura_final, R.drawable.baixa, R.drawable.baixada, R.drawable.greenprogressbar, R.drawable.layout_keyboard, R.drawable.linerlay, R.drawable.merge1, R.drawable.o2zds, R.drawable.regbd, R.drawable.s7qrs}; @SuppressLint("NewApi") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); mPagerAdapter = new MyPagerAdapter(null); mpager = (ViewPager) findViewById(R.id.viewer); mpager.setAdapter (mPagerAdapter); } public void showImage (int position, View view) { //View is your view that you returned from instantiateItem //and position is it's position in array you can get the image resource id //using this position and set it to the ImageView } private class MyPagerAdapter extends PagerAdapter { SecondActivity activity; public MyPagerAdapter (SecondActivity activity){ this.activity=activity; } @Override public int getCount() { // TODO Auto-generated method stub return pics.length; } @Override public boolean isViewFromObject(View arg0, Object arg1) { // TODO Auto-generated method stub return false; } @Override public Object instantiateItem(View collection, int position) { ImageView view = new ImageView (SecondActivity.this); view.setImageResource (pics[position]); ((ViewPager) collection).addView(view, 0); return view; } @Override public void setPrimaryItem (ViewGroup container, int position, Object object) { super.setPrimaryItem (container, position, object); activity.showImage(position,(View)object); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.second, menu); return true; } private OnClickListener mPageClickListener = new OnClickListener() { public void onClick (View v) { // TODO Auto-generated method stub //aquí anirà la funció per traslladar la image de la gallery a la pantalla Integer picId = (Integer) v.getTag(); mpager.setVisibility(View.VISIBLE); mpager.setCurrentItem(v.getId()); } @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }; }
End Second Activity
Third Activity
package com.example.logger; import android.os.Bundle; import android.app.Activity; import android.app.ListActivity; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; public class ThirdActivity extends ListActivity implements OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_third); final ListView listview = (ListView) findViewById(android.R.id.list); String[] values = new String[] {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty"}; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.activity_third, android.R.id.list, values); setListAdapter(adapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.third, menu); return true; } public void attachButton() { findViewById(R.id.add).setOnClickListener(this); } @Override public void onClick(View v) { // TODO Auto-generated method stub } }
End Third Activity
Activity_Main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" tools:context=".MainActivity" > <Button android:id="@+id/login" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/Login" android:layout_alignParentBottom="true" android:background="@drawable/shapes" android:textColor="@color/text" /> <EditText android:id="@+id/username" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/input_u" android:layout_marginTop="10dp" android:textColor="@color/text" /> <EditText android:id="@+id/password" android:layout_below="@+id/username" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/input_p" android:layout_marginTop="10dp" android:textColor="@color/text" /> </RelativeLayout> End Activity_Main.xml
Activity_Second.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".SecondActivity" > <android.support.v4.view.ViewPager android:padding="16dp" android:id="@+id/viewer" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_weight="0.70" /> <ImageView android:id="@+id/big_image" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_below="@+id/viewer" android:layout_weight="0.30" /> </RelativeLayout> End Activity_Second.xml
**Activity_Third.xml** <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".ThirdActivity" > <Button android:id="@+id/add" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:text="@string/add" /> <ListView android:id="@+id/list" android:layout_width="match_parent" android:layout_below="@+id/add" android:layout_height="wrap_content" ></ListView> </RelativeLayout> End Activity_Third.xml
I'd very grateful if someone could help me figure out what I'm doing wrong on this project.
Yours sincerely,
Mauro.
-31657878 0I think you basically have the right idea. You should listen for collaborator leave/join events and update what is being tracked appropriately. As you say, its OK for multiple people to make the changes for leave, as they will do the same thing.
The Realtime Playground has an example of this.
-661733 0If you are running Time Machine on Leopard (OS X 10.5) then you have a chance that the files are in the backup. By default Time Machine backs up every hour so unless the files were created and deleted between backups then you should have something.
-28711174 0 Showing message after customer is redirected to logout page magentoI have a problem here. I want to show a message to the customer after his/her session is out. Let me explain in detail. I have a case, at first the customer is logged in when the customer clicks the "My Account" he/she is redirected to customer login page.Here i want to show the message that "your session is out please log in again".
One method i tried is to check the customer session in indexAction() in AcountController.php but this redirection is not taking place from this indexAction().
I am guessing that this redirection is taking somewhere from the block because "My Account" link is added through the xml file using "addLink" method.But i couldn't figure it out.
Has anyone faced such problem and has solved it. Can anyone provide me with some insights so i can fix it.
-40587641 0 How can I start/stop a stop watch with only the spacebar?I want to start/stop a stop watch only using the spacebar. I already made the KeyListeners, and that they only get activated when you press/release the spacebar.
What I tried so far:
I tried creating a stopwatch class, which SHOULD calculate the time difference between me pressing space for the first time, and second time. I tried it as follows:
public class Stopwatch { public Stopwatch(int i) { long time = System.currentTimeMillis(); if(i%2==1){ System.out.println("Timer Started at: " + time); }else{ System.out.println("Timer stopped at: " + System.currentTimeMillis()); System.out.println("Time diff: " + (time - System.currentTimeMillis())); } }} int i increases with every second spacebar press.
I know the problem here is that everytime I start this class, time is getting reset to System.currentTimeMillis() because I only press Spacebar. Thus the difference is always 0.
How can I change this so that I can somehow save the time I first pressed space?
Here is the class with the Keylisteners. Ignore the Scrambler class, it has nothing to do with my Problem.
import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.*; public class StoppuhrFrame extends JFrame { JLabel time, scramble; public StoppuhrFrame() { time = new JLabel("00:00:00"); time.setBounds(162, 45, 325, 80); time.setFont(new Font("Arial", 100, 80)); add(time); scramble = new JLabel("Scramble: "); scramble.setBounds(165, 15, 370, 16); add(scramble); //Scrambler scrambler = new Scrambler(scramble); addKeyListener(new timer()); setTitle("Cube Timer"); setLayout(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setResizable(false); setSize(650, 270); setVisible(true); } int i = 1; public class timer implements KeyListener { @Override public void keyPressed(KeyEvent keyEvent) { if(keyEvent.getKeyCode()==32){ new Stopwatch(i); i++; } @Override public void keyReleased(KeyEvent arg0) { if (arg0.getKeyCode() == 32) { if(i%2==0){ //new Scrambler(scramble); } } } @Override public void keyTyped(KeyEvent arg0) { // TODO Auto-generated method stub } }} Thanks in advance.
-19942426 0Use RegExpTxt.test(Fname.value) instead of RegExpTxt(Fname.value)
Javascript should end up being:
function form_onchange(){ var Fname = document.getElementById('Fname'); var RegExpTxt = /^([a-zA-Z ]){2,30}$/; if (!RegExpTxt.test(Fname.value)) { alert('Please provide a valid name'); Fname.focus(); Fname.select(); return false; } }
-19502896 0 I loaded this exact file onto my WAMP server locally and everything worked perfectly fine: You might want to change this at the bottom of the page: src="http://code.jquery.com/jquery.js" There is nothing wrong with your code and the HTML5 shiv and respond.js has nothing to do with your menu not working...
You might however want to use Google Chrome and use the inspect element to make sure your reference points are correct.
Hover doesn't work out of the box in BS3, you can use a custom javascript to get that working... I use it here: http://thisamericanjourney.com/ hover over the about menu item: //This allows the user to hover over the menu without clicking on it
$(function() { $('ul.nav li.dropdown').hover(function() { $('.dropdown-menu', this).fadeIn('fast'); }, function() { $('.dropdown-menu', this).fadeOut('fast'); }); });
-32731041 0 You should create a variable containing the \n:
(bind ?newline " ") and then use it in str-cat or sym-car or other places.
(bind ?a (sym-cat ?a ?newline))
-37233302 0 You are misunderstanding in and out parameters.
This:
CallableStatement cStmt = dbConnection.prepareCall(sql); cStmt.registerOutParameter(1, Types.DECIMAL); cStmt.execute(); Is declaring that your ratio parameter is an output from the procedure, but it's not.
You should be doing something like:
CallableStatement cStmt = dbConnection.prepareCall(sql); cStmt.setObject(1, theRatio, Types.DECIMAL); cStmt.execute();
-33874881 0 I don't know why you want to keep the unidirectional relation here, because making it bidirectional would make your life much easier.
First, CascadeType.ALL on the parent mapping in your example means that if you delete the subfolder, its parent will be deleted also. And this will propagate all the way up to the root folder which is probably not what you want.
With bidirectonal mapping it would look like this
@ManyToOne @JoinColumn(name = "parent_folder_id") protected Folder parentFolder; @OneToMany(mappedBy = "parentFolder", cascade = {CascadeType.ALL}) protected Set<Folder> children; Without this, you should implement the cascade yourself. This will get complicated for more complicated folder structures (when checking the children of a folder before deletion, you'll have to check grandchildren... and so on). It could be done with one recursive method, but definitely a lot more work than with bidirectional relation.
/* pseudo code */ public void deleteFolder(Folder f) { Set<Folder> children = session.createQuery("from Folder where parentFolder.id = :parentId").setParameter("parentId", f.getId()).list(); for each child { deleteFolder(child) } session.delete(f) }
-8676801 0 Try this...
String s3 = s1 + s2 if(s3.equals("onetwo")) { ... == compares if they refer to the same object, and the result of s1+s2 isn't in this case, and the .equals() method on string compares that the values are the same. In general, you only use == for primitive value comparisons. Although you can do it for objects iff you intend to check to make sure that two references point to the same object.
Use:
/*/Result/*/Flight [count(*/*)=count(/*/Request/*/FlightId) and not(*/*/FlightNumber[not(. = /*/Request/*/FlightId)]) ] Here is the complete transformation:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="/"> <xsl:variable name="vHits" select= "/*/Result/*/Flight [count(*/*)=count(/*/Request/*/FlightId) and not(*/*/FlightNumber[not(. = /*/Request/*/FlightId)]) ]"/> <FilterResult> <ResultCount><xsl:value-of select="count($vHits)"/></ResultCount> <Response> <xsl:copy-of select="$vHits"/> </Response> </FilterResult> </xsl:template> </xsl:stylesheet> When this transformation is applied on the provided XML document:
<Response> <Request> <RequestedFlights> <FlightId>2121</FlightId> <FlightId>2584</FlightId> </RequestedFlights> </Request> <Result> <Flights> <Flight> <Segments> <Segment> <Id>1</Id> <FlightNumber>2121</FlightNumber> </Segment> <Segment> <Id>2</Id> <FlightNumber>1121</FlightNumber> </Segment> </Segments> </Flight> <Flight> <Segments> <Segment> <Id>3</Id> <FlightNumber>2121</FlightNumber> </Segment> <Segment> <Id>4</Id> <FlightNumber>2584</FlightNumber> </Segment> </Segments> </Flight> <Flight> <Segments> <Segment> <Id>5</Id> <FlightNumber>2121</FlightNumber> </Segment> <Segment> <Id>6</Id> <FlightNumber>2584</FlightNumber> </Segment> <Segment> <Id>7</Id> <FlightNumber>2023</FlightNumber> </Segment> </Segments> </Flight> </Flights> </Result> </Response> the wanted, correct result is produced:
<FilterResult> <ResultCount>1</ResultCount> <Response> <Flight> <Segments> <Segment> <Id>3</Id> <FlightNumber>2121</FlightNumber> </Segment> <Segment> <Id>4</Id> <FlightNumber>2584</FlightNumber> </Segment> </Segments> </Flight> </Response> </FilterResult> Explanation:
Proper use of the double negation law.
-2935604 0 Qt cross thread callI have a Qt/C++ application, with the usual GUI thread, and a network thread. The network thread is using an external library, which has its own select() based event loop... so the network thread isn't using Qt's event system.
At the moment, the network thread just emit()s signals when various events occur, such as a successful connection. I think this works okay, as the signals/slots mechanism posts the signals correctly for the GUI thread.
Now, I need for the network thread to be able to call the GUI thread to ask questions. For example, the network thread may require the GUI thread to request put up a dialog, to request a password.
Does anyone know a suitable mechanism for doing this?
My current best idea is to have the network thread wait using a QWaitCondition, after emitting an object (emit passwordRequestedEvent(passwordRequest);. The passwordRequest object would have a handle on the particular QWaitCondition, and so can signal it when a decision has been made..
Is this sort of thing sensible? or is there another option?
-32405867 0Here's the answer, a simple sub-select:
declare @t1 table (Id int not null primary key) declare @t2 table (Id int not null primary key, Table1Id int not null, SomeValue int not null)
INSERT @t1 VALUES (100), (101), (102), (103), (104), (105), (106), (107), (108), (109), (110), (111), (112), (113)
INSERT @t2 VALUES (1,100,1),(5,100,2),(9,100,4),(10,100,5), (2,101,1),(6,101,2),(11,101,4),(13,101,7), (3,102,1),(7,102,2),(12,102,4),(14,102,6), (15,103,1),(17,103,2), (16,104,1),(18,104,2),(19,104,4), (20,105,1),(25,105,2),(27,105,4),(28,105,7), (21,106,1), (22,107,1),(29,107,2), (23,108,1),(30,108,2), (31,109,1), (32,110,1),(36,110,2),(40,110,3), (33,111,1),(37,111,2),(44,111,3), (34,112,1),(38,112,2),(43,112,4), (35,113,1),(41,113,2),(42,113,4)
select * from ( select Table1Id, max (SomeValue) AS SomeValue from @t2 group by Table1Id ) t where SomeValue = 4
-31291447 0Use addClass() and removeClass() then store the styles in there:
CSS
.my-checkbox-class { // styles } JQuery
$('.single-checkbox:checked').addClass('my-checkbox-class'); $('.single-checkbox:checked').removeClass('my-checkbox-class'); You can add any styles to any element like this and remove them too. It's a good, clean solution that makes your css re-usable and keeps the style and functionality separate.
Note that the add and remove class methods don't need a . to denote a class, this can be a gotcha
I want to resize the bitmap height & width into same as the user device width & height.So please help me if u know the code.Thank You !
This is my code:
Bitmap bm = BitmapFactory.decodeResource(getResources(),R.drawable.nature); DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics(); width = metrics.widthPixels; height=metrics.heightPixels; But it was not working
-663380 0This is going to sound strange, but does the view/table have a column named "1"?
-2297810 0You would expose it as an IEnumerable<T>, but not just returning it directly:
public IEnumerable<object> Objects { get { return obs.Select(o => o); } } Since you indicated you only wanted traversal of the list, this is all you need.
One might be tempted to return the List<object> directly as an IEnumerable<T>, but that would be incorrect, because one could easily inspect the IEnumerable<T> at runtime, determine it is a List<T> and cast it to such and mutate the contents.
However, by using return obs.Select(o => o); you end up returning an iterator over the List<object>, not a direct reference to the List<object> itself.
Some might think that this qualifies as a "degenerate expression" according to section 7.15.2.5 of the C# Language Specification. However, Eric Lippert goes into detail as to why this projection isn't optimized away.
Also, people are suggesting that one use the AsEnumerable extension method. This is incorrect, as the reference identity of the original list is maintained. From the Remarks section of the documentation:
TheAsEnumerable<TSource>(IEnumerable<TSource>)method has no effect other than to change the compile-time type of source from a type that implementsIEnumerable<T>toIEnumerable<T>itself.
In other words, all it does is cast the source parameter to IEnumerable<T>, which doesn't help protect referencial integrity, the original reference is returned and can be cast back to List<T> and be used to mutate the list.
LESS provides the ability to use previously defined classes as mixins in other contexts. Try this:
.theme-dark { .navbar { .navbar-inverse; } }
-36227521 0 There is no Children property on Parent, there is a Child property. But the Binding attribute says Children. Change the attribute to...
public ActionResult Edit([Bind(Include="ParentId,ZmiennaParent1, Child")] Parent parent)
-24717590 0 This removes the list of services:
tasklist /v|find /v /i " services "
-29805037 0 There are couple of things you could do easily. First point is
you could use Positive integer field in Django, if you want only positive integer in this model
if you want to do the custom way, please raise an exception or use the assert statement for it. Then in the test case could check whether exception or assertion Error is raised
You only have to use this-> if you have a symbol with the same name in two potential namespaces. Take for example:
class A { public: void setMyVar(int); void doStuff(); private: int myVar; } void A::setMyVar(int myVar) { this->myVar = myVar; // <- Interesting point in the code } void A::doStuff() { int myVar = ::calculateSomething(); this->myVar = myVar; // <- Interesting point in the code } At the interesting points in the code, referring to myVar will refer to the local (parameter or variable) myVar. In order to access the class member also called myVar, you need to explicitly use "this->".
-1328836 0 How can I include line numbers in a stack trace without a pdb?We are currently distributing a WinForms app without .pdb files to conserve space on client machines and download bandwidth. When we get stack traces, we are getting method names but not line numbers. Is there any way to get the line numbers without resorting to distributing the .pdb files?
-9307528 0This is very normal, since each time you are closing the form and opening it again you are having a new instance from the form MyPropsX, so the best way would be to save your properties in any kind of a database (sql, access, textfiles,...)
-40861684 0Assuming the strings are all in column A:
As you will only want to split where there are 2 or more characters, just to start you off. In Column C is the formula (this is only in column C):
=IF(LEN(A1)>1,CONCATENATE(LEFT($A1,1),"_",MID($A1,2,1),"_"),"") In Column D and dragged across is the formula:
=IF(LEN($A1)>COLUMN(C:C),CONCATENATE(C1,MID($A1,COLUMN(C:C),1),"_"),IF(LEN($A1)=COLUMN(C:C),CONCATENATE(C1,RIGHT($A1,1)),"")) That will build the string for you but the results will be all over the place so in Column B I have the formula:
=INDEX(1:1,1,LEN(A1)+1) To gather all the results in to one column for you. Feel free to ask how any of this works, I hope this helps.
-1812405 0A VM is a big task to consider. Have you considered basing your VM on something like LLVM?
LLVM will provide a good base to start from and there are plenty of example projects which you can use for understanding.
-23845436 0On Button Click You can use one of the following :
editText.setTextColor(Color.RED); editText.setTextColor(Color.parseColor("#FFFFFF")); editText.setTextColor(Color.rgb(200,0,0)); editText.setTextColor(Color.argb(0,200,0,0)); editText.setTextColor(getResources().getColor(R.color.editTextColor)); editText.setTextColor(0xAARRGGBB); You can also try this pure CSS method:
font-size: calc(100% - 0.3em);
-18552693 0 No, it checks everything in database. Cookies would be too dangerous (users can modify their rights)
You can cache data with Cache class in Laravel 4 to compensate too many queries to your database.
-32392463 0well, you want to hide the fields in the gridfield detail form? that cannot be done in your pages getCMSFields(), as the grid is responsible for generating the detail form. Two possible solutions:
1) tell the grid to hide that fields with a custom component. I dunno how to do it
2) tell your Rotator class to show the fields ONLY if the related page is a homepage:
public function getCMSFields() { $fields = parent::getCMSFields(); //...other stuff.... $isOnHomePage = ($this->Page() && $this->Page()->ClassName == 'HomePage'); //put in your own classname or conditions if(!$isOnHomePage) { //remove the fields if you're not on the HomePage $fields->removeByName('Body'); //we need to suffix with "ID" when we have a has_one relation! $fields->removeByName('BackGroundImageID'); } return $fields; }
-31238631 0 Refreshing html table using Jquery Java built on Codeigniter Guys I have a data coming from an outsource table which I'm presenting in table. The original data coming in Json which I'm decoding using PHP function and displaying.
I have been googling for auto refreshing that data and found this Auto refresh table without refreshing page PHP MySQL
I have managed to built what is suggested in the Ticked answers and seems like working for the first time but it doesn't refresh. So when page is loaded
I'm calling this
$(document).ready (function () { var updater = setTimeout (function () { $('div#user_table').load ('get_new_data', 'update=true'); /* location.reload(); */ }, 1000); }); Which loads a function named get_new_data from controller file and loads on to
<div class="container-fluid" id="user_table"> </div> Codeigniter controller function is
public function get_new_data(){ $url = 'https://gocleanlaundry.herokuapp.com/api/users/'; $result = $this->scripts->get_data_api($url); $data_row = $result; $tbl = ''; $tbl .= '<table class="table table-striped table-responsive" id="tableSortableRes"> <thead> <tr> <th>Name</th> <th>Email Address</th> <th>Role</th> <th>Status</th> <th>Action</th> </tr> </thead> <tbody>'; foreach($data_row as $row){ $tbl .= '<tr class="gradeX"> <td>' . $row->name . '</td> <td>' . $row->email . '</td> <td>' . $row->role . '</td> <td><p id="' . $row->_id. '_status">'.( $row->alive == true ? 'Active' : 'Banned').' </p></td> <input id="' . $row->_id . 'status_val" value="' . $row->alive . '" type="hidden"> <td class="center"> <a href="#" id="' . $row->_id . '_rec" onclick="UpdateStatus(' . $row->_id . ')" class="btn btn-mini ">' . ($row->alive == '1' ? '<i class="fa fa-thumbs-o-up fa-fw"></i>' : '<i class="fa fa-thumbs-o-down fa-fw"></i>' ) . '</a> </td> </tr> '; } $tbl .= '</tbody> </table>'; echo $tbl; } As I said when page loads is showing data so something is working but when I add new data to the database is doesn't automatically show up. I want function to call and refresh the data. Sorry I'm very new to javascript and jQuery so please go easy on me :)
Thank you guys
-32653879 0From: Why does the ObjectStateManager property not exist in my db context?
var manager = ((IObjectContextAdapter)db).ObjectContext.ObjectStateManager;
-21494582 0 <select> <option selected="selected" class="Country">Country Name</option> <option value="1">India</option> <option value="2">us</option> </select>
.country { display:none; } </style>
-36579174 0 Is not reusing created SOAP client object Can anyone tell me why the SOAP client is not being re-used? It keeps getting initialized where it should have been reused from the last call.
When I print out the SOAP client object after it was initialized it is there but it is forgotten at the next call.
So the php script keeps initializing the connection.
My code:
class EcoAPI { private $client; public function getClient() { if (empty($this->client)) { echo "<br>initializing..."; $this->initClient(); } return $this->client; } private function initClient() { $settingsOld = Settings::GetOld(); $this->client = new SoapClient("https://api.e-conomic.com/secure/api1/EconomicWebservice.asmx?WSDL", array("trace" => 1, "exceptions" => 1)); $this->client->ConnectWithToken(array('token' => $settingsOld->economic_token_secret, 'appToken' => $settingsOld->economic_token_app)); } } I connect by:
$ecoApi = new EcoAPI(); $result = $ecoApi->getClient()->Account_GetVatAccount(array('accountHandle' => (object) array('Number' => (string) $VatAccount)));
-39680169 0 Error on VS 2013 for WP Silverlight 8.1 applications I explain my error in this video: error
I'm doing this because I tried to ask a question for my error in past and I didn't get any answers. (first question)
If anyone can help me with this problem please leave a comment because I can't get rid of it. Thanks!
-2667345 0This looks correct.
Note that MailMessage does not override ToString, so your logs will simply say [MailMessage] Send cancelled.
You might want to use the Subject proeprty (or some other property) instead.
Exercise 3-3 in Accelerated C++ has led me to two broader questions about loop design. The exercise's challenge is to read an arbitrary number of words into a vector, then output the number of times a given word appears in that input. I've included my relevant code below:
string currentWord = words[0]; words_sz currentWordCount = 1; // invariant: we have counted i of the current words in the vector for (words_sz i = 1; i < size; ++i) { if (currentWord != words[i]) { cout << currentWord << ": " << currentWordCount << endl; currentWord = words[i]; currentWordCount = 0; } ++currentWordCount; } cout << currentWord << ": " << currentWordCount << endl; Note that the output code has to occur again outside the loop to deal with the last word. I realize I could move it to a function and simply call the function twice if I was worried about the complexity of duplicated code.
Question 1: Is this sort of workaround is common? Is there a typical way to refactor the loop to avoid such duplication?
Question 2: While my solution is straightforward, I'm used to counting from zero. Is there a more-acceptable way to write the loop respecting that? Or is this the optimal implementation?
-38638442 0As a workaround, download data per day and define weeks in alignment with your measurements from the other dataset. Now Aggregate the Trends data. In case you are dealing with more than 3 months worth of data, consider to rescale your segments beforehand as described here: http://erikjohansson.blogspot.de/2014/12/creating-daily-search-volume-data-from.html http://erikjohansson.blogspot.de/2014/05/daily-google-trends-data-using-r.html
-5407453 0 JSF 2 LifecycleI have this code for BookModel.java:
@Entity @Table(name = "BOOK") @NamedNativeQuery(name = "BookModel.findBookTitle", query = "SELECT @rownum:=@rownum+1 'no', m.title, m.author, REPLACE(SUBSTRING_INDEX(m.content, ' ', 30), '<br>', ' '), m.viewed, m.hashid FROM book m, (SELECT @rownum:=0) r WHERE m.title like 'a%'") public class BookModel implements Serializable { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "MY_SEQ_GEN") @Column(name = "id", unique = true, nullable = false) private Long id; @NotNull @Size(min = 1, max = 255) @Column(name = "title") private String title; @NotNull @Size(min = 1, max = 255) @Column(name = "author") private String author; } And BookService.java for the business layer:
@Stateless public class BookService { @SuppressWarnings("unchecked") public List<BookModel> getBook() { Query query = entityManager.createNamedQuery("BookModel.findBookTitle"); List<BookModel> result = query.getResultList(); return result; } } And BookBean.java for the presentation layer:
@ManagedBean(name = "BookBean") @RequestScoped public class BookBean implements Serializable { @EJB private BookService bookService; private DataModel<BookModel> book; public DataModel<BookModel> getBook() { return book; } } And the page book.xhtml:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.prime.com.tr/ui"> <p:dataTable id="bookList" value="#{BookBean.book}" var="book"> ... </p:dataTable> </html> My question is: How can I restrict the method getBook() in BookBean to be executed only once instead of six times - presumably for each phase of JSF lifecycle. Has anyone else come across this before? Please help. Have been stuck on this for the last day without any success.
-14778756 0There are several ways to achieve that, see Ant FAQ
One possible solution via macrodef simulates the antcontrib / propertycopy task but doesn't need any external library.
You need to use a (derived) table of values. Here is a solution using left join instead of not in:
select n.n from (select 1 as n union all select 2 union all select 4 union all select 5 union all select 6 union all select 7 ) n left join tablename t on t.id = n.n where t.id is null;
-4442587 0 Simple jQuery problem This one should be easy
I've got this HTML
<table class="PageNumbers"> <tr> <td colspan="3">text3 </td> </tr> <tr> <td colspan="2">text </td> <td>text2 </td> </tr> <tr> <td>moretext </td> <td>moretext2 </td> <td>moretext3 </td> </tr> </table> I need to change the colspan of the first rows first column to one
This is what i've got
$('.PageNumbers tr:first td:first').attr('colspan') = '1' Doesn't seem to work though
Any ideas?
Thanks
-21423604 0Without reading all to much of your stuff,
def check_dict(first, second): for key in first: for keyTwo in second: if type(first[key]) == dict and type(second[keyTwo]) == dict: return check_dict(first[key], second[keyTwo]) if not first[key] == second[keyTwo]: return false Don't have access for a python interpreter at the moment but something along the lines of this should work. It's just a start for an idea but hopefully this is enough information to spark something.
-9271901 0That's definitely an error with getdisc not being visible to the linker but, if what you say is correct, that shouldn't happen.
The gcc command line you have includes graph1.c which you assure use contains the function.
Don't worry about the object file name, that's just a temprary name created by the compiler to pass to the linker.
Can you confirm (exact cut and paste) the gcc command line you're using, and show us the function definition with some context around it?
In addition, make sure that graph1.c is being compiled as expected by inserting immediately before the getdisc function, the following line:
xyzzy plugh twisty; If your function is being seen by the compiler, that should cause an error first. It may be something like ifdef statements causing your code not to be compiled.
By way of testing, the following transcript shows that what you are trying to do works just fine:
pax> cat shells2.c #include "graph2.h" int main (void) { int x = getdisc (); return x; } pax> cat graph2.h int getdisc (void); pax> cat graph1.c int getdisc (void) { return 42; } pax> gcc -o rr4 shells2.c graph1.c pax> ./rr4 pax> echo $? 42 We have to therefore assume that what you're actually doing is something different, and that's unusually tactful for me :-)
What you're experiencing is what would happen with something like:
pax> gcc -o rr4 shells2.c /tmp/ccb4ZOpG.o: In function `main': shells2.c:(.text+0xa): undefined reference to `getdisc' collect2: ld returned 1 exit status or if getdisc was not declared correctly in graph1.c.
That last case could be for many reasons including, but not limited to:
getdisc.#ifdef type statements meaning the definition is never seen (though you seem to have discounted that in a comment).#define to change getdisc to something else (unlikely, but possible).I am creating a game like Doodle Jump (without the accelerometer).
I have been trying to figure this out, but I can't seem to make it run as smoothly as I've been hoping.
Here is my code for my touches functions:
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { for touch: AnyObject in touches { let touchLocation = touch.locationInNode(self) lastTouch = touchLocation } } override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) { for touch: AnyObject in touches { let touchLocation = touch.locationInNode(self) lastTouch = touchLocation } } override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) { lastTouch = nil } override func update(currentTime: CFTimeInterval) { if let touch = lastTouch { let impulseVector = CGVector(dx: 400, dy: 400) player.physicsBody?.applyImpulse(impulseVector) } }
-15120243 0 Easiest example I can think of would be a method that sends some content to a JMS server. If you are in the context of a transaction, you want the message to be coupled to the transaction scope. But if there isn't already a transaction running, why bother calling the transaction server also and starting one just to do a one-off message?
Remember these can be declared on an API as well as an implementation. So even if there isn't much difference for your use case between putting it there and putting nothing there, it still adds value for an API author to specify what operations are able to be included in a transaction, as opposed to operations that perhaps call an external system that does not participate in transactions.
This is of course in a JTA context. The feature doesn't really have much practical use in a system where transactions are limited to resource-local physical database transactions.
-37505779 0I use following code fix:
require 'nokogiri' d = Nokogiri::HTML(%Q(<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> </head> <body> </body> </html> )) d.css('body')[0].add_child(Nokogiri::XML::Comment.new(d, "doc")) puts d.to_s
-16129329 0 This is all you need:
... <key>cell</key> <string>PSButtonCell</string> <key>action</key> <string>buttonCellClicked:</string> ... This will make a button cell and send the buttonCellClicked: message on the preferences view controller.
I am trying to work on getting better at making HTML forms using PHP and Mysql databases so I decided to make a little mock-up website to do some experiments and things like that.
I decided that the first thing I would need to do was to create a login and register page for users who want to sign on to the website. I had no idea how to do this so I did a little research online and I found some pre-built scripts that would do exactly what I wanted to do. In the end I decided to go with this script: http://www.html-form-guide.com/php-form/php-registration-form.html
On my website (hosted with hostgator using cPanel) I set up a Mysql database called ljbaumer_gifts (website is a gift website) and I added a table with 2 columns. The first one a login column which was set to int with auto increment and 25 characters. The second one is a password one which was set to var_char and 25 characters.
I filled in all of the information on the setup scripts from the website I linked to earlier completely correctly but every single time I try to register I get this error code:
Database Login failed! Please make sure that the DB login credentials provided are correct mysqlerror:Access denied for user 'ljbamer_root'@'my_server_adress' (using password: YES) Database login failed!
I used an account that has complete privileges on my server but it still doesn't work!
-3814533 0sorry for question... are you sure that you check between 2 integer values?... and if yes... in the html that you have, do you have the background color in the TD elements of the table? If you have the color code in the html code, maybe it's a problem of css style definition.
-35502612 0 How to grow computational thinkingAs a beginner java programmer,I found how I think in terms of solving a problem is more important than how much of the language and built in methods/shortcuts I know.My worst enemy in learning the programming language is when I get stuck and don't know how to approach.I was wondering is there any good book that will enhance my computation thinking and problem solving abilities?I can persevere and solve problems but I feel I lack tools/insights required.
-31562696 0It appears that in case of using impersonated async http calls via httpWebRequest
HttpWebResponse webResponse; using (identity.Impersonate()) { var webRequest = (HttpWebRequest)WebRequest.Create(url); webResponse = (HttpWebResponse)(await webRequest.GetResponseAsync()); } the setting <legacyImpersonationPolicy enabled="false"/> needs also be set in aspnet.config. Otherwise the HttpWebRequest will send on behalf of app pool user and not impersonated user.
Guys I have some silly struct let's call it X and I also have a fnc (not a member of it) returning a pointer to this struct so it looks like so:
struct X { bool operator==(const X* right) { //... } }; X* get(X* another) { //... } I also have line in code which 'tries' to compare pointers to those structs but the real intention is to compare those structs pointed to:
if (get(a) == get(b))//here obviously I have two pointers returned to be compared { //... } I also defined member of X operator==(const X* right) which suppose to work in situations aforementioned but for reason I do not understand it doesn't. How to make it work (I CANNOT change the line if (get(a) == get(b)) and also get MUST return pointer).
I was wondering what language the CLion IDE was written in, and what Library is used to make the graphics for it.
-19678530 0It's somewhat subjective. I personally would prefer the latter, since it does not impose the cost of copying the vector onto the caller (but the caller is still free to make the copy if they so choose).
-901893 0Try doing
GridView1.DataSource = users.ToList(); or
GridView1.DataSource = users.ToArray(); Is possibly that the query isn't executing at all, because of deferred execution.
-14212199 0The other answers seem to have missed the source-control history side of things.
From http://forums.perforce.com/index.php?/topic/359-how-many-lines-of-code-have-i-written/
Calculate the answer in multiple steps:
1) Added files:
p4 filelog ... | grep ' add on .* by <username>' p4 print -q foo#1 | wc -l 2) Changed files:
p4 describe <changelist> | grep "^>" | wc -l Combine all the counts together (scripting...), and you'll have a total.
You might also want to get rid of whitespace lines, or lines without alphanumeric chars, with a grep?
Also if you are doing it regularly, it would be more efficient to code the thing in P4Python and do it incrementally - keeping history and looking at only new commits.
-37023081 0The Recycle View supports AutofitRecycleView.
You need to add android:numColumns="auto_fit" in your xml file.
You can refer to this AutofitRecycleViewLink
-40493624 0The solution to your question depends highly on the device you are using. If you have a phone with a dedicated PTT button, the manufacturer of the phone almost certainly has made an Intent available for app developers such as yourself to intercept PTT down and up events, but you'll need to contact the manufacturer for more information.
For instance, phones from Kyocera, Sonim, and Casio have such Intents available, and you'd simply need to put a receiver declaration in your AndroidManifest.xml, like this for a Kyocera phone:
<receiver android:exported="true" android:name="com.myapp.receiver.KeyReceiverKyocera"> <intent-filter android:priority="9999999"> <action android:name="com.kodiak.intent.action.PTT_BUTTON" /> <action android:name="com.kyocera.android.intent.action.PTT_BUTTON" /> </intent-filter> </receiver> Then, a simple BroadcastReceiver class that receives the up and down intents:
public class KeyReceiverKyocera extends BroadcastReceiver { private static boolean keyDown = false; @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (keyDown) processPTTDown(); else processPTTUp(); keyDown = !keyDown; } } Hope this helps,
Shawn
-9253056 0Yes. It's possible. Use plpython for example. Use this in trigger.
CREATE OR REPLACE FUNCTION move_file(old_path text, new_path text) RETURNS boolean AS $$ import shutil try: shutil.move(old_path, new_path) return True except: return False $$ LANGUAGE 'plpythonu' VOLATILE;
-13092533 0 ZSH auto_vim (like auto_cd) zsh has a feature (auto_cd) where just typing the directory name will automatically go to (cd) that directory. I'm curious if there would be a way to configure zsh to do something similar with file names, automatically open files with vim if I type only a file name?
-24097047 0As Craig said, indexes are only used internally to the database so the index names are not important - but in PostgreSQL they must be unique.
-375895 0 Techniques for building HTML in codeAn html template is compiled into the application as a resource. A fragment of the HTML template looks like:
<A href="%PANELLINK%" target="_blank"> <IMG border="0" src="%PANELIMAGE%" style="%IMAGESTYLE%"> </A><BR> %CAPTIONTEXT% i like it like this because the larger resource HTML file contains styling, no-quirks mode, etc.
But as is always the case, they now want the option that the Anchor tag should be omitted if there is no link. Also if there is no caption, then the BR tag should be omitted.
Given that i don't want to have to build entire HTML fragments in C# code, i considered something like:
%ANCHORSTARTTAGPREFIX%<A href="%PANELLINK%" target="_blank">%ANCHORSTARTTAGPOSTFIX% <IMG border="0" src="%PANELIMAGE%" style="%IMAGESTYLE%"> %ANCHORENDTAGPREFIX%</A>%ANCHORENDTAGPOSTFIX%CAPTIONPREFIX%<BR> %CAPTIONTEXT%%CAPTIONPOSTFIX% with the idea that i could use the pre and postfixes to turn the HTML code into:
<!--<A href="%PANELLINK%" target="_blank">--> <IMG border="0" src="%PANELIMAGE%" style="%IMAGESTYLE%"> <!--</A>--><!--<BR> %CAPTIONTEXT%--> But that is just rediculous, plus one answerer reminds us that it wastes bandwith, and can be buggy.
Wholesale replacement of tags:
%AnchorStartTag% <IMG border="0" src="%PANELIMAGE%" style="%IMAGESTYLE%"> %AnchorEndTag%%CaptionStuff% and doing a find-replace to change
%AnchorStartTag% with
"<A href=\"foo\" target=\"blank\"" i considered giving an ID to the important HTML elements:
<A id="anchor" href="%PANELLINK%" target="_blank"> <IMG border="0" src="%PANELIMAGE%" style="%IMAGESTYLE%"> </A><BR id="captionBreak"> %CAPTIONTEXT% and then using an HTML DOM parser to programatically delete nodes. But there is no easy access to a trustworthy HTML DOM parser. If the HTML was instead xhtml i would use various built-in/nativly available xml DOM parsers.
What i actually have so far is:
private const String htmlEmptyTemplate = @"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01//EN\"""+Environment.NewLine+ @" ""http://www.w3.org/TR/html4/strict.dtd"">"+Environment.NewLine+ @"<HTML>"+Environment.NewLine+ @"<HEAD>"+Environment.NewLine+ @" <TITLE>New Document</TITLE>"+Environment.NewLine+ @" <META http-equiv=""X-UA-Compatible"" content=""IE=edge"">"""+Environment.NewLine+ @" <META http-equiv=""Content-Type"" content=""text/html; charset=UTF-8"">"+Environment.NewLine+ @"</HEAD>"+Environment.NewLine+ @""+Environment.NewLine+ @"<BODY style=""margin: 0 auto"">"+Environment.NewLine+ @" <DIV style=""text-align:center;"">"+Environment.NewLine+ @" %ContentArea%"+Environment.NewLine+ @" </DIV>" + Environment.NewLine + @"</BODY>" + Environment.NewLine + @"</HTML>"; private const String htmlAnchorStartTag = @"<A href=""%PANELLINK%"" target=""_blank"">"; //Image is forbidden from having end tag private const String htmlImageTag = @"<IMG border=""0"" src=""%PANELIMAGE%"" style=""%IMAGESTYLE%"">"; private const String htmlCaptionArea = @"<BR>%CAPTIONTEXT%"; And i already want to gouge my eyeballs out. Building HTML in code is a nightmare. It's a nightmare to write, a nightmare to debug, and a nightmare to maintain - and it will makes things difficult on the next guy. i'm hoping for another solution - since i am the next guy.
-24122695 1 Interate through a Pandas dataframeI want to upsample my data. It is hourly data that I want to turn into 5 minute data by resampling and filling in the missing data with a linear interpolation between the hours.
Wind_locations.csv, the data frame has a column called 'CH'. I want to iterate through each row of 'CH' and subtract the next row from the current. This is how I think it should work, but it is not, any suggestions?
I tried using
data = pd.read_csv('Wind_Locations.csv')
data.CH.resample('5min', how='sum')
But I get the error TypeError: Only valid with DatetimeIndex or PeriodIndex
Any suggestions?
-22904103 0You have a shadowing problem. You declare...
private JButton findnext; private JButton replace; private JButton delete; private JButton upper; But in your constructor you do...
JButton findnext = new JButton("FindNext"); //... JButton replace = new JButton("Replace"); //... JButton delete = new JButton("Delete"); //... JButton upper = new JButton("Upper"); Which is re-declaring those variables.
This means that when you try and do...
if (source == findnext) { It's always false
You're also adding the ActionListener (this) to the findnext button four times...I think you mean to be adding it to each of the other buttons
Beware, there is already a class called Window in AWT, which could cause confusion for people. It's also discouraged to extend directly from a top level container like JFrame and instead should start with a JPanel and the add it to an instance of JFrame (or what ever container you like)
From here:
When you open catalina.sh / catalina.bat, you can see :
Environment Variable Prequisites JAVA_HOME Must point at your Java Development Kit installation. So, set your environment variable JAVA_HOME to point to Java 7. Also make sure JRE_HOME is pointing to the same target, if it is set.
You may not have this same issue, but if you do, it could be helpful to know ; )
-37791208 0 Knockout JS - How to initialize a complex object as observable?I have a ViewModel and have an observable property that will have a complex object after an edit link is clicked. This is a basic example of managing a set of Groups. User can click on the 'edit' link and I want to capture that Group in SelectedGroup property.
But I'm not sure how should I initialize the SelectedGroup and make every peoperty in this object as observable to begin with.
function ManageGroupsViewModel() { var self = this; self.Groups = ko.observableArray(); self.IsLoading = ko.observable(false); self.SelectedGroup = ko.observable(); }
-4794788 0 I'm writing a (not really) simple project in C++ (my first, coming from plain C). I was wondering if there is a way to simplify the definition for multiple functions having the same template pattern. I think an example would be better to explain the problem.
Let's assume I have a "Set" class which represents a list of numbers, defined as
template <class T> class Set { static_assert(std::is_arithmetic<T>(), "Template argument must be an arithmetic type."); T *_address; ... } So if I have an instance (say Set<double>) and an array U array[N], where U is another arithmetic type and N is an integer, I would like to be able to perform some operations such as assigning the values of the array to those of the Set. Thus I create the function template inside the class
template <class U, int N> void assign(U (&s)[N]) { static_assert(std::is_arithmetic<U>(), "Template argument must be an arithmetic type."); errlog(E_BAD_ARRAY_SIZE, N == _size); idx_t i = 0; do { _address[i] = value[i]; } while (++i < size); } As far as my tests went the code above works perfectly fine. However I find it REALLY REALLY ugly to see since I need the static_assert to ensure that only arithmetic types are taken as arguments (parameter U) and I need a way to be sure about the array size (parameter N). Also, I'm not done with the assign function but I need so many other functions such as add, multiply, scalar_product etc. etc.!
I was wondering then if there is a prettier way to write this kind of class. After some work I've come up with a preprocessor directive:
#define arithmetic_v(_U_, _N_, _DECL_, ...) \ template <class U, idx_t N> _DECL_ \ { \ static_assert(std::is_arithmetic<U>(),"Rvalue is not an arithmetic type."); \ errlog(E_BAD_ARRAY_SIZE, N == _size); \ __VA_ARGS__ \ } thus defining my function as
arithmetic_v(U, N, void assign(U (&value)[N]), idx_t i = 0; do { _address[i] = value[i]; } while (++i < _size); ) This is somehow cleaner but still isn't the best since I'm forced to lose the brackets wrapping the function's body (having to include the static_assert INSIDE the function itself for the template parameter U to be in scope).
The solution I've found seems to work pretty well and the code is much more readable than before, but... Can't I use another construct allowing me to build an even cleaner definition of all the functions and still preserving the static_assert piece and the info about the array size? It would be really ugly to repeat the template code once for each function I need...
I'm just trying to learn about the language, thus ANY additional information about this argument will be really appreciated. I've searched as much as I could stand but couldn't find anything (maybe I just couldn't think of the appropriate keywords to ask Google in order to find something relevant). Thanks in advance for your help, and happy new year to you all!
Gianluca
-9047551 0They devided c with m*2 and assigned the value to c, then made sure h is not nothing:
c/=m*2;h!= In other words: he did everything. The ultimate everything!
Or maybe the cat sat on the keyboard and produced a random glob of characters. Cats are very good at that.
I'm just kidding. ♥
Important bit: If anything, this "attack" has nothing to do with jQuery. Maybe they tried to make the web server error, somehow? Which they did, but I doubt it could do any damage. So, it's not really a threat.
-34710985 0For autocompletion of dynamically created objects (if its type is not recognized automatically) most IDEs support type-hinting comments.
For example:
/** @var Car $car */ See http://www.phpdoc.org/docs/latest/references/phpdoc/tags/var.html
-11831870 0The fact that it is hidden changes nothing. The problem is probably that the js code is before the button HTML. Either put it after, or put it in a listener like $(document).ready() to make sure it has been processed when your try to access it.
Try doing the select after casting the join result to a list.
public IEnumerable<MergeObj> QueryJoin() { List<TableObj1> t1 = conn.Table<TableObj1>().ToList(); List<TableObj2> t2 = conn.Table<TableObj2>().ToList(); return t1.Join(t2, outer => outer.Id, inner => inner.Id, (outer, inner) => new MergeObj { Obj1 = outer, Obj2 = inner }); } Edit : Since your database don't seems to support join, you can extract the result of your database in two distinct List and then join them using LINQ.
-29059295 0Your print_values method is an instance method, though it does not use the instance in it.
I believe you meant to use the instance data for your implementation:
class LinkedListNode attr_accessor :value, :next_node def initialize(value, next_node = nil) @value = value @next_node = next_node end def print_values print "#{value} --> " if next_node.nil? print "nil" return else next_node.print_values end end end node1 = LinkedListNode.new(37) node2 = LinkedListNode.new(99, node1) node3 = LinkedListNode.new(12, node2) node3.print_values Another option is to make the method a static method, which does not need an instance, which will look like:
class LinkedListNode attr_accessor :value, :next_node def initialize(value, next_node = nil) @value = value @next_node = next_node end def self.print_values(list_node) print "#{list_node.value} --> " if list_node.next_node.nil? print "nil" return else print_values(list_node.next_node) end end end node1 = LinkedListNode.new(37) node2 = LinkedListNode.new(99, node1) node3 = LinkedListNode.new(12, node2) LinkedListNode.print_values(node3) Both options will be considered recursive, since the method calls itself. There are no rules about recursion (calling another method is allowed), but there are things you need to be aware of, like if you don't have a good stopping condition, your method might "explode" with a stack overflow exception.
-26563776 0KDevelop, QtCreator, XCode and many other editors offer this feature. And more will come, as nowadays it's rather trivial to implement in some way based on Clang.
-22297215 0don't look for bug free query here because you haven' provided enough info and sample data. So start pointing out one be one,
Declare @i varchar='Jan-13' declare @upto int=11 Declare @FromDate date=convert(varchar(12),'1-'+'Jan-13',120) Declare @Todate date =dateadd(month,@upto,@FromDate) select convert(char(6),@FromDate,107) ,@ToDate Declare @StringDate varchar(2000)='' select @StringDate= stuff((select ','+'['+convert(char(6),ODLN.DocDate ,107)DocDate+']' from ODLN inner join DLN1 on odln.DocEntry = ODLN.DocEntry where ODLN.DocDate between between @FromDate and @Todate for xml path('')),1,1,'') --@StringDate will have value like [Jan-13],[Dec-12] and so on Declare @qry varchar(max)='' set @qry='select CardName,'+@StringDate+' from (select CardName,CardCode ,DLN1.Quantity,convert(char(6),ODLN.DocDate ,107)DocDate from ODLN inner join DLN1 on odln.DocEntry = ODLN.DocEntry where ODLN.DocDate between between '+@FromDate+' and '+@Todate+')tbl pivot( max(Quantity) for DocDate in('+@StringDate+'))pvt' exec @qry
-27665257 0 The result being a Hash, you can call values on it:
res = ActiveRecord::Base.connection.execute(q_cmd) res.values This will give you just the values in an array!
Reference documentation: Hash#values.
No answer yet has explained why NASM reports
Mach-O 64-bit format does not support 32-bit absolute addresses The reason NASM won't do this is explained in Agner Fog's Optimizing Assembly manual in section 3.3 Addressing modes under the subsection titled 32-bit absolute addressing in 64 bit mode he writes
32-bit absolute addresses cannot be used in Mac OS X, where addresses are above 2^32 by default.
This is not a problem on Linux or Windows. In fact I already showed this works at static-linkage-with-glibc-without-calling-main. That hello world code uses 32-bit absolute addressing with elf64 and runs fine.
@HristoIliev suggested using rip relative addressing but did not explain that 32-bit absolute addressing in Linux would work as well. In fact if you change lea rdi, [rel msg] to lea rdi, [msg] it assembles and runs fine with nasm -efl64 but fails with nasm -macho64
Like this:
section .data msg db 'This is a test', 10, 0 ; something stupid here section .text global _main extern _printf _main: push rbp mov rbp, rsp xor al, al lea rdi, [msg] call _printf mov rsp, rbp pop rbp ret You can check that this is an absolute 32-bit address and not rip relative with objdump. However, it's important to point out that the preferred method is still rip relative addressing. Agner in the same manual writes:
There is absolutely no reason to use absolute addresses for simple memory operands. Rip- relative addresses make instructions shorter, they eliminate the need for relocation at load time, and they are safe to use in all systems.
So when would use use 32-bit absolute addresses in 64-bit mode? Static arrays is a good candidate. See the following subsection Addressing static arrays in 64 bit mode. The simple case would be e.g:
mov eax, [A+rcx*4] where A is the absolute 32-bit address of the static array. This works fine with Linux but once again you can't do this with Mac OS X because the image base is larger than 2^32 by default. To to this on Mac OS X see example 3.11c and 3.11d in Agner's manual. In example 3.11c you could do
mov eax, [(imagerel A) + rbx + rcx*4] Where you use the extern reference from Mach O __mh_execute_header to get the image base. In example 3.11c you use rip relative addressing and load the address like this
lea rbx, [rel A]; rel tells nasm to do [rip + A] mov eax, [rbx + 4*rcx] ; A[i]
-32782201 0 Have you checked that the account running the app pool is in the IIS_IUSRS group in User Manager (lusrmgr.msc)
Cheers
-630604 0If you're using SQL Server 2005 or newer then your best option is to create a user-defined CLR function and use a regular expression to remove all non-numeric characters.
If you don't want to use a CLR function then you could create a standard user-defined function. This will do the job although it won't be as efficient:
CREATE FUNCTION dbo.RemoveNonNumerics(@in VARCHAR(255)) RETURNS VARCHAR(255) AS BEGIN DECLARE @out VARCHAR(255) IF (@in IS NOT NULL) BEGIN SET @out = '' WHILE (@in <> '') BEGIN IF (@in LIKE '[0-9]%') SET @out = @out + SUBSTRING(@in, 1, 1) SET @in = SUBSTRING(@in, 2, LEN(@in) - 1) END END RETURN(@out) END And then select from your table like so:
SELECT dbo.RemoveNonNumerics(your_column) AS your_tidy_column FROM your_table
-9440032 0 I have seen this before. What solved the problem for me was to re-export my PNGs. For some reason, some of them get metadata in them (like Fireworks stuff) which causes it to bug out in certain situations. I've seen that happen mostly with Internet Explorer, but have seen it with MKMapView as well. Even more strange, it worked in the simulator but not on the device.
-1710248 0 Does anyone have parsing rules for the Notepad++ Function List plugin for Ruby and RakeI'me using Notepad++ for editing rake files and I'd like to be able to use the function list plugin.
I've been unable to find any parsing rules on line, and the "Language Parsing Rules" dialog is not very clearly documented.
I'm parsing methods into the list with the following, but would like to also display tasks.
Function Begin: [ \t]*def[ \t]+ Function List Name: [a-zA-Z0-9_\.]* This isn't very clean, and won't capture functions that end with ? or !, but it is a start.
My task rule, which isn't working is:
Function Begin: [ \t]*task[ \t]+ Function List Name: :[a-zA-Z0-9_\.]* Function End: [ \t]+do Any suggestions most welcome.
thanks
-40009351 0If they don't provide an argument, set that argument in args to 0. Then ls won't receive an empty string as its first argument, it won't get any arguments at all.
args[0] = arg1; if (strlen(arg2) == 0) { args[1] = 0; } else { args[1] = arg2; args[2] = 0; } You also need to check for this in the loop that prints all the arguments.
for(i=0;i<MAX && arg[i];i++) { printf("Value of arg[%d] =%s\n",i, args[i]); }
-20710003 0 You can use GridBagLayout in netBeans . this layout is stable way for complex form and panel .
-14020775 0You have chose wrong selector, :td is not correct. You need to attach event directly on tr. You may use mouseenter instead of mouseover as mouseover will fire again and again as mouse moves on it, it will cause needless execution of code. You need to change the class only once so mouse enter would be do that for you.
$(document).ready(function() { $('#gvrecords tr').mouseenter(function() { $(this).addClass('highlightRow'); }).mouseout(function() { $(this).removeClass('highlightRow'); }) })
-18666043 0 Selecting even rows through it class name Problem selecting even rows through it class name:
$(".recDetails table tr").each(function() { if( !($(this).css("display") == "none")){ $(this).addClass("block"); }; }); $(".recDetails table").each(function(i) { $(this).find("tr.block:even").css("background-color", "#fff"); $(this).find("tr.block:odd").css("background-color", "#efefef"); }); It is taking into the count all of the "tr" so:
(1) tr class="block" (2) tr (3) tr class="block"
-38009704 0 You need to provide full path to the .trx file. With below changes in begin analysis and try it again.
Change
/d:sonar.cs.vstest.reportsPaths=../TestResults/*.trx To
/d:sonar.cs.vstest.reportsPaths=../TestResults/Mytest.trx
-18988050 0 If the form is posting a field with a parameter of name, a 404 will result.
I solved the problem!
I'm developing this app using Flash Builder 4.5, and I made a debug/run configuration for iPhone4.
Now, when you're specifying a run/debug configuration, you can select a checkbox 'Clear application data on each launch'. This checkbox needs to be UNCHECKED, because this will clear your SharedObject on each application launch!
To access this configuration screen in Flash Builder 4.5, click the tiny arrow next to your run/debug button and click Run/Debug Configurations. Navigate to your specified configuration, and uncheck the checkbox!
Voila! Enjoy your iOS SharedObject awesomeness!
-33194823 0That's right. PriorityQueue of Java does not offer a method to update priority and it seems that deletion is taking linear time since it does not store objects as keys, as Map does. It in fact accepts same object multiple times.
I also wanted to make PQ offering update operation. Here is the sample code using generics. Any class that is Comparable can be used with it.
class PriorityQueue<E extends Comparable<E>> { List<E> heap = new ArrayList<E>(); Map<E, Integer> map = new HashMap<E, Integer>(); void insert(E e) { heap.add(e); map.put(e, heap.size() - 1); bubbleUp(heap.size() - 1); } E deleteMax() { if(heap.size() == 0) return null; E result = heap.remove(0); map.remove(result); heapify(0); return result; } E getMin() { if(heap.size() == 0) return null; return heap.get(0); } void update(E oldObject, E newObject) { int index = map.get(oldObject); heap.set(index, newObject); bubbleUp(index); } private void bubbleUp(int cur) { while(cur > 0 && heap.get(parent(cur)).compareTo(heap.get(cur)) < 0) { swap(cur, parent(cur)); cur = parent(cur); } } private void swap(int i, int j) { map.put(heap.get(i), map.get(heap.get(j))); map.put(heap.get(j), map.get(heap.get(i))); E temp = heap.get(i); heap.set(i, heap.get(j)); heap.set(j, temp); } private void heapify(int index) { if(left(index) >= heap.size()) return; int bigIndex = index; if(heap.get(bigIndex).compareTo(heap.get(left(index))) < 0) bigIndex = left(index); if(right(index) < heap.size() && heap.get(bigIndex).compareTo(heap.get(right(index))) < 0) bigIndex = right(index); if(bigIndex != index) { swap(bigIndex, index); heapify(bigIndex); } } private int parent(int i) { return (i - 1) / 2; } private int left(int i) { return 2*i + 1; } private int right(int i) { return 2*i + 2; } } Here while updating, I am only increasing the priority (for my implementation) and it is using MaxHeap, so I am doing bubbleUp. One may need to heapify based on requirement.
-930920 0If you are able to use LINQ,
void Main() { Dictionary d1 = new Dictionary<int, string>(); Dictionary d2 = new Dictionary<int, string>(); d1.Add(1, "1"); d1.Add(2, "2"); d1.Add(3, "3"); d2.Add(2, "2"); d2.Add(1, "1"); d2.Add(3, "3"); Console.WriteLine(d1.Keys.Except(d2.Keys).ToArray().Length); } This prints 0 to the console. Except tries to find the difference between two lists in the above example.
You can compare this with 0 to find if there is any difference.
EDIT: You could add the check for comparing the length of 2 dictionaries before doing this.
i.e. You can use Except, only if the length differs.
I try to get the map from Google APIS, my link is: https://maps.googleapis.com/maps/api/geocode/json?address=%E3%80%92106-6108%E6%9D%B1%E4%BA%AC%E9%83%BD%E6%B8%AF%E5%8C%BA%E5%85%AD%E6%9C%AC%E6%9C%A8%E5%85%AD%E6%9C%AC%E6%9C%A8%E3%83%92%E3%83%AB%E3%82%BA%E6%A3%AE%E3%82%BF%E3%83%AF%E3%83%BC%EF%BC%98%E9%9A%8E+JP
address = 〒106-6108東京都港区六本木六本木ヒルズ森タワー8階 but the result return "formatted_address" : "Roppongi Hills Mori Tower, 6 Chome-10-1 Roppongi, Minato-ku, Tōkyō-to 106-0032, Japan",
Why I inputed 106-6108, but Google return 106-0032 ?
Please help me, how can I fix that ? Thank you
-14283665 0Would a linq query like this be faster:
var matches = ( from f in family_list join b in busy_list on f.color == b.color && f.name == b.name select new {f, b} );
-21927505 0 Does DBCursor.getServerAddress work as I expect? I expect getServerAddress to return the address of the Mongo server (one of replica set nodes), which actually handles the query.
I am logging output of getServerAddress and see only the primary address although I am pretty sure that some queries are handled by secondary.
I am a little bit confused since I see queries (having set profillingLevel) in the secondary while getServerAddress returns the primary. Maybe I am mistaken though ...
Can it be a bug in the API ? Does anybody encounter such a problem ? Is it possible that getServerAddress always returns the primary while some queries are actually handled by secondaries ?
-30681861 1 python socket json -- no JSON object could be decodeMy python version is 2.7, and I encounter a problem as below picture 
This is the client
name = raw_input("Please enter your username: ") passwd = raw_input("Please enter you password: ") data = {"username": name, "password": passwd} sock.connect((HOST,PORT)) sock.sendall(bytes(json.dumps(data)) And this is the server
rcv_msg = json.loads(self.client_socket.recv(1024).strip()) print rcv_msg username = rcv_msg['username'] password = rcv_msg['password'] print "username: " + username print "password: " + password However, I still get the username and password... Please someone help me to clean this bug~ Thanks
-15963140 0I have done the same swipe to delete functionality using MCSwipeTableCell
For deleting a particular row from table with animation do this:
//I am passing 0,0 so you gotta pass the row that was deleted. NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0] [self.yourTable deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; For deleting from core data do this:
YourCustomModel *modelObj; NSManagedObjectContext *context= yourmanagedObjectContext; NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setEntity:[NSEntityDescription entityForName:@"YourCustomModel" inManagedObjectContext:context]]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"yourField == %@", passTheFieldValueOfTheRowDeleted]; [request setPredicate:predicate]; NSError *error = nil; NSArray *results = [context executeFetchRequest:request error:&error]; if ([results count]>0) { modelObj = (Customers *)[results objectAtIndex:0]; } [context deleteObject:modelObj]; if (![context save:&error]) { NSLog(@"Sorry, couldn't delete values %@", [error localizedDescription]); }
-17195288 0 remove "+" or "0" from a telephone number string i need in php a regular expression to remove from a string of telephone numbers the + or the 0 at the beginning of a number
i have this function to remove every not-number characters
ereg_replace("[^0-9]", "", $sPhoneNumber) but i need something better, all these examples should be...
$sPhoneNumber = "+3999999999999" $sPhoneNumber = "003999999999999" $sPhoneNumber = "3999999999999" $sPhoneNumber = "39 99999999999" $sPhoneNumber = "+ 39 999 99999999" $sPhoneNumber = "0039 99999999999" ... like this
$sPhoneNumber = "3999999999999" any suggestions, thank you very much!
-27573303 0I used this reference to implement DataTables with row details in MVC 4 using the Razor engine (I initially wanted to pass JSON, but found another approach that provides the functionality that I was looking for and felt along the lines of what I usually do in MVC).
I assume that DataTables is already implemented, a means for data retrieval is implemented, and MVC 4 with the Razor engine is being used. I will only be focusing on how to implement DataTables with row details in MVC.
My models:
public class Advisor { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Discipline { get; set; } } public class Student { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Major { get; set; } public int AdvisorId { get; set; } } Given my models, I have a view that displays a table of advisors:
@model IEnumerable<DataTablesMvcExample.Models.Advisor> @{ ViewBag.Title = "Index"; //eg, [url]/Advisor Layout = "~/Views/Shared/_Layout.cshtml"; //will explain later } <table id="sort"> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Discipline</th> </tr> </thead> <tbody> @foreach (var item in Model) { <tr> <td>@item.FirstName</td> <td>@item.LastName</td> <td>@item.Discipline</td> </tr> } </tbody> </table> I would like to display the students each advisor advises. To do this:
1) In my controller, with respect to the view in which the table above lies, I add the code below:
public ActionResult AdvisorStudents(int advisorId) { var advisorStudents = //retrieve students based on their advisor return View(advisorStudents); } 2) I create a view called AdvisorStudents.cshtml (eg, [url]/Advisor/AdvisorStudents)
@model IEnumerable<DataTablesMvcExample.Models.Student> @{ Layout = null; //Using a layout will cause this table to not open as row details. I was at a loss until I explicitly defined this. } <table> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Major</th> </tr> </thead> <tbody> @foreach (var item in Model) { <tr> <td>@item.FirstName</td> <td>@item.LastName</td> <td>@item.Major</td> </tr> } </tbody> </table> 3) In the view the table of advisors lie, I add the JavaScript below, DISCLAIMER: I borrowed a lot of this from the aforementioned reference.
<script type="text/javascript"> var oTable; $(document).ready(function () { $('#sort tbody td img').click(function () { var nTr = this.parentNode.parentNode; /* close image is displayed while viewing row details*/ if (this.src.match('close')) { //ie, match "~/[directory]/*close*.png" /* close this row as it is open */ this.src = //path of open image oTable.fnClose(nTr); } /* open image is displayed to view row details */ else { /* open this row */ this.src = //path of close image var advisorId = $(this).attr("rel"); $.get("Advisor/AdvisorStudents?AdvisorId=" + advisorId, function (students) { oTable.fnOpen(nTr, students, 'row_details'); }); } }); /* Initialize datatable and make column that opens/closes non-sortable*/ oTable = $('#sort').dataTable({ "bJQueryUI": true, "aoColumns": [ { "bSortable": false, "bSearchable": false }, null, null, null ] }); }); </script> When I initialize the DataTables for the table of advisors above, I specify four columns, with the first column not sortable or searchable. The table of advisors specified three columns above. The column not specified, which will become my first column, is where my open/close display will go. I add a header cell <th></th> and a standard cell <td><img src=//path of open image alt="expand/collapse" rel="@item.Id"/></td> as the first column to achieve this.
NOTE: You can have the open/close display in any column you'd like. To do so:
Javascript
td in $('#sort tbody td img') to td:nth-child(x) or td:last-child.HTML
<th> and <td> cells match which column you wish to have your open/close display on
Hope this helps someone. I have a SSCCE by request. I know this is a necrobump, but I couldn't find a suitable example (aside from the one I reference above) to suit my needs. This question asks for an example, here is mine.
Because typeof will only return string, so it is safe to compare two strings with ==.
It should be pretty easy with list comprehensions
[ f for f in sftp.listdir("path_to_files") if f.endswith(".csv") ]
-30413134 0 rails bundle install sqlite3 failed in kali linux Please help me to resolve this problem I use kali linux os!! root@artisla:~/Documents/Adilet/Programming/blog# gem install sqlite3 -- --with-sqlite3-dir=/opt/local Building native extensions with: '--with-sqlite3-dir=/opt/local' This could take a while... ERROR: Error installing sqlite3: ERROR: Failed to build gem native extension.
/usr/local/rvm/rubies/ruby-2.2.2/bin/ruby -r ./siteconf20150523-10092-2alrq5.rb extconf.rb --with-sqlite3-dir=/opt/local checking for sqlite3.h... no sqlite3.h is missing. Try 'port install sqlite3 +universal', 'yum install sqlite-devel' or 'apt-get install libsqlite3-dev' and check your shared library search path (the location where your sqlite3 shared library is located). * extconf.rb failed * Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options.
Provided configuration options: --with-opt-dir --without-opt-dir --with-opt-include --without-opt-include=${opt-dir}/include --with-opt-lib --without-opt-lib=${opt-dir}/lib --with-make-prog --without-make-prog --srcdir=. --curdir --ruby=/usr/local/rvm/rubies/ruby-2.2.2/bin/$(RUBY_BASE_NAME) --with-sqlite3-dir --with-sqlite3-include --without-sqlite3-include=${sqlite3-dir}/include --with-sqlite3-lib --without-sqlite3-lib=${sqlite3-dir}/lib
extconf failed, exit code 1
Gem files will remain installed in /usr/local/rvm/gems/ruby-2.2.2/gems/sqlite3-1.3.10 for inspection. Results logged to /usr/local/rvm/gems/ruby-2.2.2/extensions/x86-linux/2.2.0/sqlite3-1.3.10/gem_make.out
-31749735 0 request only htaccess auth for one of many domainsI have a system where x domains could lead to the same folder on the server.
(content is shown by the Database for the given domain)
Now I want to develop a new page but I would need a htaccess auth only for this domain.
example1.com ok
example2.com auth
example3.com ok
Any idea?
-10595090 0 Derelict2 on Mac OS X 10.7: SDL failing to buildI'm trying to build Derelict2 on Lion as per the included installation instructions. When I run the command make -fmac.mak DC=dmd the following libraries build fine:
Unfortunately once the script gets up to DerelictSDL it spits out the following:
make -C DerelictSDL all PLATFORM=mac dmd -release -O -inline -I../DerelictUtil -c derelict/sdl/sdl.d derelict/sdl/sdlfuncs.d derelict/sdl/sdltypes.d -Hd../import/derelict/sdl dmd -release -O -inline -I../DerelictUtil -c derelict/sdl/macinit/CoreFoundation.d derelict/sdl/macinit/DerelictSDLMacLoader.d derelict/sdl/macinit/ID.d derelict/sdl/macinit/MacTypes.d derelict/sdl/macinit/NSApplication.d derelict/sdl/macinit/NSArray.d derelict/sdl/macinit/NSAutoreleasePool.d derelict/sdl/macinit/NSDictionary.d derelict/sdl/macinit/NSEnumerator.d derelict/sdl/macinit/NSEvent.d derelict/sdl/macinit/NSGeometry.d derelict/sdl/macinit/NSMenu.d derelict/sdl/macinit/NSMenuItem.d derelict/sdl/macinit/NSNotification.d derelict/sdl/macinit/NSObject.d derelict/sdl/macinit/NSProcessInfo.d derelict/sdl/macinit/NSString.d derelict/sdl/macinit/NSZone.d derelict/sdl/macinit/runtime.d derelict/sdl/macinit/SDLMain.d derelict/sdl/macinit/selectors.d derelict/sdl/macinit/string.d -Hd../import/derelict/sdl/macinit derelict/sdl/macinit/NSString.d(134): Error: cannot implicitly convert expression (this.length()) of type ulong to uint derelict/sdl/macinit/NSString.d(135): Error: cannot implicitly convert expression (str.length()) of type ulong to uint derelict/sdl/macinit/NSString.d(140): Error: cannot implicitly convert expression (cast(ulong)(selfLen + aStringLen) - aRange.length) of type ulong to uint make[1]: *** [dmd_mac_build_sdl] Error 1 make: *** [DerelictSDL_ALL] Error 2
-16822317 0 getText between tags with Selenium I'm trying to parse the following XML file so that I can get some attributes. One thing I need to do is verify that the content between tags is not empty. To do this, I though I would be able to use the getText method provided for web elements.
The XML file:
<results> <result index="1"> <track> <creator>Cool</creator> <album>Amazing</album> <title>Awesome and Fun</title> </track> </result> </results> My code for parsing through and getting what I want is as follows (keep in mind there is more than one result):
boolean result = false; driver.get(url); List<WebElement> result_list = driver.findElements(By.xpath(".//result")); if (result_list.size() == num_results) { try { for (int i = 0; i < result_list.size(); i++) { WebElement track = result_list.get(i).findElement(By.xpath(".//track")); WebElement creator = track.findElement(By.xpath(".//creator")); System.out.println(creator.getText()); track.findElement(By.xpath(".//album")); track.findElement(By.xpath(".//title")); } result = true; } catch (Exception e) { result = false; } } return result; The problem is that the System.out.println call returns an empty string when there is clearly text between the creator tags. Any help would be greatly appreciated!
-2018121 0At the Microsoft 2009 Mix Web developer conference, all the presentations that I attended included code examples in C#, not VB.
In StackOverflow, notice how questions tagged c# largely outnumber vb.net and vb.
John Skeet wrote C# in Depth, not VB in Depth.
I have a TextField for a username named username and a PasswordTextField named password. I declared two local string variables, user and pass. I have a database but I still can't get into the "welcome" part. This is my code.
try { Class.forName("com.mysql.jdbc.Driver"); //making a connection through the driver connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/login", "root", "123456"); //System.out.println("Connected to database"); statement = connection.createStatement(); rs = statement.executeQuery("SELECT * FROM login.credentials"); while (rs.next()) { String user = rs.getString("username"); String pass = rs.getString("password"); if (username.equals(user) && password.equals(pass)){ System.out.println("Welcome!"); } else { System.out.println("Invalid password!"); } } }
-29661021 0 Simply replace:
.filter_by(year=year) .filter_by(month=month) with:
from sqlalchemy.sql.expression import func # ... .filter(func.year(Logs.timestamp) == year) .filter(func.month(Logs.timestamp) == month) Read more on this in SQL and Generic Functions section of documentation.
-16229840 0 android - required layout_attribute is missing<shape xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" > <gradient android:layout_width="match_parent" android:angle="270" android:centerColor="#4ccbff" android:endColor="#24b2eb" android:startColor="#24b2eb" /> <corners android:radius="5dp" /> </shape> The above code shows " required layout_height attribute is missing" on the line no 4
&
"required layout_height and layout_width attribute is missing" on the line no 11.
Your selectors are incorrect, you're using the hash to indicate and id. Also you're prefixing your classes with an element notation that is not correct.
This
if($('#tr').hasClass('tr_group')) should be:
if($('tr').hasClass('group'))
-10751059 0 I'm pretty sure that is not how JavaScript scoping works...
In your example there are 2 ways to do what you would want to do:
//this is the bad way imo, since its not really properly scoped. // you are declaring the planeEarth and tpl globally // ( or wherever the scope of your define is. ) var plantetEarth = { name: "Earth", mass: 1.00 } var tpl = new Ext.Template(['<tpl for".">', '<p> {name} </p>', '</tpl>'].join('')); tpl.compile(); Ext.define('casta.view.Intro', { extend: 'Ext.tab.Panel', //alias: 'widget.currentDate', //this makes it xtype 'currentDate' //store: 'CurrentDateStore', initComponent: function(){ this.callParent(arguments); }, html:tpl.apply(planetEarth) }); or
//I would do some variation of this personally. //It's nice and neat, everything is scoped properly, etc etc Ext.define('casta.view.Intro', { extend: 'Ext.tab.Panel', //alias: 'widget.currentDate', //this makes it xtype 'currentDate' //store: 'CurrentDateStore', initComponent: function(){ this.tpl = new Ext.Template(['<tpl for".">', '<p> {name} </p>', '</tpl>'].join('')); this.tpl.compile(); this.tpl.apply(this.planetEarth); this.html = this.tpl.apply(this.planetEarth) this.callParent(arguments); }, });
-24510945 0 Save is meant to insert one document. Update can be used over several documents that match the criteria in the first parameter.
Under certain circumstances (specifying a unique id as the criteria, upsert:true, and not using multi: true) both can serve the same purpose.
-28559864 0 Comparing values of two promisesI wish to achieve the following:
var textPromise1 = element(by.id('id1')).getText(); var textPromise2 = element(by.id('id2')).getText(); if(textPromise1.SOMELOGIC == textPromise2.SOMELOGIC ) console.log('These are equal') I know the promise is resolved using .then(). However, I want to know if there exists some way with which above can be achieved!
Thanks,
-10692147 0 Error while installing caldecottI am getting this error while running this command on windows prompt> gem insatll caldecott. I have downloaded the development kit but the error is still the same.
Please update your PATH to include build tools or download the DevKit from 'http://rubyinstaller.org/downloads' and follow the instructions at 'http://github.com/oneclick/rubyinstaller/wiki/Development-Kit'
-6300010 0All of your questions can be solved very easy if you use a DFS for each relationship and then use your function calculate() again if you want it more detailed.
-27574155 0You can open the file feat.params in model folder and look for -upperf parameter. In 8khz model -upperf is usually 3500 or 4000. For 16khz model -upperf is more than 4000, usually 6800.
I stumbled upon this question after searching for a similar thing. Since (sadly) I didn't find a CSS-only solution for this problem, I ended up using jQuery to do the job.
function hrExpand() { var windowWidth = $(window).width(); $('hr').width(windowWidth).css('margin-left', function(){ return '-' + ($(this).offset().left) + 'px'; }); } Just make sure to run the function both onload and onresize.
Example: http://codepen.io/anon/pen/qEOoGb
(You could replace $('hr') with e.g. $('.content > hr') to increase performance a bit and prevent it from replacing ALL the hr's on your page)
-40600786 0 Change value of character pointed by a pointerI would like to know why my code giving me error when run.
I am trying to change the character value pointed by a pointer variable.
#include <stdio.h> int main() { char amessage[] = "foo"; char *pmessage = "foo"; // try 1 amessage[0] = 'o'; // change the first character to '0' printf("%s\n", amessage); // try 2 *pmessage = 'o'; // This one does not work printf("%s\n", pmessage); } The first attempt works, and prints ooo. But the second one gives me:
[1] 9677 bus error ./a.out Any ideas?
-8896015 0Make sure you use Symfony\Component\Security\Core\SecurityContextInterface; in your controller. Without it, the SecurityContextInterface type hint in the constructor won't resolve.
Also, make sure your controller is actually being called as a service. The error you posted is complaining that nothing was sent to the constructor, which sounds to me like you're using your controller the 'default' way. See this cookbook page on how to setup a controller as a service.
-16059073 1 How to change file_extension internally in Blender 2.65I am writing a python script for Blender and I am quite new. I want to change output file format in render option internally. For example, context.scene.render.file_extension = "PNG" . But it is a read-only variable so I get an error. Is there a way to change it in code?
I am using Blender-2.65.
-28643732 0 SQL Server : trigger on not inserted rowI have two tables. I have defined a trigger on Table A that updates Table B when a row is inserted into Table A.
I want to prevent inserting into table A and allow updating in table B if a data with certain values is sent to Table A.
Can anyone help me?
-17384146 0 CSS tables: changing background on hover, including alternative rowsI have created a sample page with a table. Should the page get deleted in the future, here's the code on Pastebin.
I want to highlight table rows on hover. It works for normal tr but it doesn't work for tr.alt (odd rows).
Code for highlighting:
tr:hover,tr.alt:hover { background: #f7dcdf; } Code for making odd rows different colour:
tr.alt td { background: #daecf5; } Any ideas how this could be fixed? Thank you very much in advance!
-28818282 0You can make regular expression groups by using ( and ) and reference then in replace using $N, which will access N-th group.
So in your case, you can do this regex: ([^: ]+:[^:]+:([^:]+):[^:]+:[^:]+)(:[^: ]+) replace: \1<\2>\3 or on some implementation $1<$2>$3
You can try it yourself here: https://www.regex101.com/r/hY8pY9/1
-32955667 0I think I have an answer for you. In this you do not have to flip the y-axis, and I can get the names in the x-axis, but I still use a hierarchy. I'm not sure it's more efficient, but here goes.
First, I created a Hierarchy defined as:
CREATE NESTED HIERARCHY [New hierarchy (2)] [yearsOfExp] AS [yearsOfExp], [name] AS [name] This allowed me to order the category axis by years of experience.
Secondly, I created a calculated column defined as:
Sum([yearsOfExp]]) over (AllNext([yearsOfExp]])) I then created a line chart. The hierarchy is the x axis and the calculated column is the y axis. When setting the x axis, be sure to "reverse scale". 
I hope this does what you're looking for. Good luck. Any questions, just ask.
-38428541 0 How to erase rows in a data frame RI have a data frame that look like this:
Quality Data Name 1 667 green 3 647 white 1 626 Blue 2 345 yellow 1 550 Blue 5 730 green i want a code that goes through a for loop and takes the one less the 600 and greater than 700 and delete the row && all the ones with the same name and saves the ones that were deleted in another data frame
example
for i in nrow(df){ if (df$Data[i]<=600 || df$Data[i]>=700){ Subset_by_name=subset(df,df$Name==df$Name[i]) (saves bad samples) (delete from data) Subset_by_name=data.frame(Subset_by_name) bad_sample=rbind(Subset_by_name) (saves all the bad data in a data frame) } } result
bad_sample
Quality Data Name 1 667 green 1 626 Blue 2 345 yellow 1 550 Blue 5 730 green data
Quality Data Name 3 647 white help please????
-28101792 0I think you should set a UINavigationController to rootviewController , there will be a navigation bar. So you can also set the firstView as rootViewController, but set the viewcontrollers attribute to put the Test viewcontroller that clears before viewcontrollers.
-22191064 0 Post a status in facebook and tag friendsI am trying to post a status on users own wall and tag the friends on it. I tried FeedDialogBuilder but i can't tag friends with it.Please help me if anyone know how to do it.
Bundle params = new Bundle(); params.putString("tags","8768XXX787,"1111XXXX222,"565XXX566565"); WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(getActivity(), Session.getActiveSession(),params)) .setOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(Bundle values, FacebookException error) { if (error == null) { final String postId = values.getString("post_id"); if (postId != null) { Toast.makeText(getActivity(),"Posted story, id: "+postId, Toast.LENGTH_SHORT).show(); } else { // User clicked the Cancel button Toast.makeText(getActivity(), "Publish cancelled", Toast.LENGTH_SHORT).show(); } } else if (error instanceof FacebookOperationCanceledException) { // User clicked the "x" button Toast.makeText(getActivity(), "Publish cancelled", Toast.LENGTH_SHORT).show(); } else { // Generic, ex: network error Toast.makeText(getActivity(), "Error posting story", Toast.LENGTH_SHORT).show(); } } }).build(); feedDialog.show();
-20856099 0 Meteor Js , Store images to mongoDB I want to store an image browsed by a file input to database. I am browing the image using redactor plugin using this code
$('.editor').redactor({ imageUpload:"/uploads" }); Using this when i select or browse an image i am directly sending that image to server using meteor HTTP-methods
HTTP.methods({ '/uploads': function(data) { console.log(data) Meteor.call("uploadImage",data) return JSON.stringify({'Hello':"hello"}); } }); Here when i am doing console.log data I am getting the 64bit binary code for the image. Now i want to save this data to the mongodb database.
I am using meteor-collection 2 for defining fields and their types. But i couldn't get which data type i have to use to store image to the mongo db.
I am trying to use mongodb gridfs to store the image. Tell me how can i store image in mongodb ? Thanx
The brackets in the search pattern make that a "group". What $_ =~ /regex/returns is an array of all the matching groups, so my ($tmp) grabs the first group into $tmp.
You're telling Gson it's looking for a list of maps of Strings to Objects, which essentially says for it to make a best guess as to the type of the Object. Since Float/Double is more generic than Integer, it's a logical option for it to use.
Gson is fundamentally built to inspect the type of the object you want to populate in order to determine how to parse the data. If you don't give it any hint, it's not going to work very well. One option is to define a custom JsonDeserializer, however better would be to not use a HashMap (and definitely don't use Hashtable!) and instead give Gson more information about the type of data it's expecting.
class Response { int id; int field_id; ArrayList<ArrayList<Integer>> body; // or whatever type is most apropriate } responses = new Gson() .fromJson(draft, new TypeToken<ArrayList<Response>>(){}.getType()); Again, the whole point of Gson is to seamlessly convert structured data into structured objects. If you ask it to create a nearly undefined structure like a list of maps of objects, you're defeating the whole point of Gson, and might as well use some more simplistic JSON parser.
-29881208 0As in any method call, it just a question of what happens where. If you don't want [self.aMutableArray objectAtIndex:0] evaluated now, don't include it in the invocation expression! Instead, make the invocation expression a call to a method where that method will call [self.aMutableArray objectAtIndex:0]:
[[self.undoManager prepareWithInvocationTarget:self] doSomethingWithObjectAtIndex:0]; ...where doSomethingWithObjectAtIndex: is where [self.aMutableArray objectAtIndex:0] is called.
I have a selection list which in HTML looks like this:
<select id="language-list"> <option value="English">English</option> <option value="German">German</option> <option value="French">French</option> </select> With jQuery I would like to achieve that ONLY the currently selected option gets a red color. When you click on the selection list to see the other options, the other options shall keep their original color.
My current jQuery code looks like that:
$('#language-list').css('color', 'red'); How do I achieve that only the currently selected option gets a red color?
-37706079 0 Prevent HTML Removing Successive spacesI have an issue in a JSP page where I have to display a generated message onscreen based on a string. It all works fine until one of the account numbers contains two spaces.
So, I have this HTML:
<logic:notEqual name="migrationsMessage" value=""> <div style="color:Red;font-weight:bold"> <bean:write name="solasDetailsForm" property="migrationsMessage"/> </div> </logic:notEqual> When the field migrationsMessage contains this:
<input type="hidden" name="migrationsMessage" value="A 123456W has migrated to A 123456."> The output on the screen is this:
“A 123456W has migrated to A 123456.” The second space after the first A is removed. I tried to alter the style to be this but it didn't help:
<logic:notEqual name="migrationsMessage" value=""> <div style="color:Red;font-weight:bold;white-space:pre"> <bean:write name="solasDetailsForm" property="migrationsMessage"/> </div> </logic:notEqual> Any ideas what is going wrong?
-26221440 0Add a listener when inflating the group layout. And you can distinguish which group's switch was clicked by setting a tag that corresponds to that group position.
Here's an example:
@Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { if (convertView == null) { ... // Add a switch listener Switch mySwitch = (Switch) convertView.findViewById(R.id.mySwitch); mySwitch.setTag(groupPosition); mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { Log.e("TAG", "Clicked position: " + buttonView.getTag()); } }); } else { convertView.findViewById(R.id.mySwitch).setTag(groupPosition); } ... return convertView; } Note that you need to set the tag each time getGroupView is called.
As a sidenote: you should use a Holder pattern so you don't have to call findViewById (which is costly) in getGroupView.
Try changing the type of AO from IEnumerable<SelectListItem> to string.
public string AO { get; set; } Thanks!
-33102488 0 Installation's object default ACL and security issueI see on Data Browser that every new Installation's object has default ACL 'Public read and write' permissions. What is a security risk? And, if it is a security risk, how is possible solve it?
-29900158 0You can get min and max per user , then the rest you need to do from the client side -
{ "aggs": { "users": { "terms": { "field": "Name" }, "aggs": { "maxAge": { "max": { "field": "age" } }, "minAge": { "min": { "field": "age" } } } } } } Here , you need to make a bucket per name using terms aggregation. Per bucket , you need to get max and min value using max and min aggregation.
Rest you need to take care on the client side.
-24945371 0The MSDN says in the docs about RowIndex property
When the RowIndex property returns -1, the cell is either a column header, or the cell's row is shared.
So you need to handle the e.RowIndex == -1 when you receive the event
(...The index must not be negative....)
private void firearmView_CellClick(object sender, DataGridViewCellEventArgs e) { if(e.RowIndex == -1) return; if (!firearmView.Rows[e.RowIndex].IsNewRow) { selectedFirearmPictureBox.Image = Image.FromFile(firearmView.Rows[e.RowIndex].Cells[12].Value.ToString(), true); } }
-17387295 0 You don't need to use Regex, you can just use .length to search for the longest string.
i.e.
function longestWord(string) { var str = string.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g,"").split(" "); longest = str[0].length; longestWord = str[0]; for (var i = 1; i < str.length; i++) { if (longest < str[i].length) { longest = str[i].length; longestWord= str[i]; } } return longestWord; } EDIT: You do have to use some Regex...
-25815403 0Once you have the duration,
call this routine (but I am sure there are more elegant ways).
public String convertDuration(long duration) { String out = null; long hours=0; try { hours = (duration / 3600000); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return out; } long remaining_minutes = (duration - (hours * 3600000)) / 60000; String minutes = String.valueOf(remaining_minutes); if (minutes.equals(0)) { minutes = "00"; } long remaining_seconds = (duration - (hours * 3600000) - (remaining_minutes * 60000)); String seconds = String.valueOf(remaining_seconds); if (seconds.length() < 2) { seconds = "00"; } else { seconds = seconds.substring(0, 2); } if (hours > 0) { out = hours + ":" + minutes + ":" + seconds; } else { out = minutes + ":" + seconds; } return out; }
-12911179 0 You must specify the following property
sonar.host.url=http://localhost:9100 , if you want Sonar batch to connect to the correct URL.
You can set it either as a property in your Ant script or a JVM parameter.
-4666017 0You can access faster to local vars, also you can shorten the variable name "window" (and even "document") with something like:
(function(w, d)(){ // use w and d var })(window, document)
-11979266 0 A common approach that works well is to use a work queue like Resque.
Managing the code
For ease of management, keep the processing code and the app "in the app". Deploy two app-servers but run resque workers on the processing server.
State changes
If the processing jobs relate to ActiveRecord persisted objects you can poll state from the front-end and periodically update it from the backend during the encoding process.
You might find it useful to use state machine.
Your problems have moved
Now you're cloud-scale™ :D More processing hosts running workers can be added if your queue gets too long. If your front-end is the only web-accessible host you can set up a rack middleware or run rainbows to proxy the processed results through the frontend to the client.
Sounds like an interesting project. Good luck!
-13233222 0In the wording in which you've posed the problem, the only correct solution is a double iteration over A and B and filter, as you've suggested. That's because you've stated the problem as to "construct the set C", which lacking other information, generally means to enumerate the set C. The only way to do that and get the exact enumeration of C, at least with the information provided, is to evaluate F on each element in A × B.
In another way of interpreting the problem, you can say you have a definition of C if you have a characteristic function, but that's just F. So I'll assume that's not what you mean.
The key seems to be that you need to elucidate the relevant properties of F, since that's the algorithmic hook for an enumeration of C. What I mean by this is that you should propose an axiom about F that allows you some shortcut over direct filtration. That could mean, for example, the existence of some auxiliary function G that allows a shorter algorithm. Assuming such a G, an enumeration algorithm would evaluate both F and G, rather than F alone.
-29545552 0How can Interface be implemented, by which it can be accessible from all the activities, and called from any of the activity to call SDK API...
The interface instance can be made a context singleton (lazily instantiated). So you may have a static getInstance(Context) to get an implementation of the interface.
OR you can be using a Dependency injection framework (Roboguice, Dagger etc) and just annotate the class with @Singletonetc. This is useful if you would like to switch implementations of same interface dynamically.
OR you can extend Application class with your own App class, mention the same in manifest's <application> tag. Now App class will become app wide singleton and can one-time initialize and expose global objects from its onCreate() method.
.., and also it provides response to calling activity only (Synchronous or Asynchronous).
I'd advise to stick with single a pattern. Also UI components like Activities, Fragments and View are exposed to a risk of being frequently destroyed and re-created. So, It is a great responsibility of notifying the SDK to not to call back for a UI that is going away.
RequestHandle handle = mySDK.doSomeAsyncReqyest(myInputParameters, new Callback<Data>(){ @Override public void onResult(Data d, Exception e){ // handle results } }); And always track the requests and remember to :
handle.cancel(); How can Interface be kept alive and on going when application is not active or in background (Service not proffered), so that it can get notification from SDK.
As of now, a "sticky" Service equipped with a boot receiver is the only way you can let android not permanently destroy a background process of an app. Even then, the process will still be stopped if resources are low, and re-started when resources are free.
This service can post notifications in status bar (by becoming a foreground service), from where, user can again be re-directed to a specific part of your app.
How can Interface broadcast notifications received from SDK to all the available activities (is Broadcast Receiver mechanism ok for this?)?
Android offers LocalBroadcastManager to broadcast events local to the app. Also there are "bus" implementations such as EventBus and Otto that can help send events from one object to another without them having direct references of each other.
If you are looking for overall async architecture hints, you can explore how the framework called RoboSpice is implemented.
It turns out there is H_SAVE_FP which saves files to an opened file pointer.
The code then looks like:
FILE* fp = fopen("historyfile", "w"); ... cap_enter(); ... history(inhistory, &ev, H_SAVE_FP, fp);
-8374923 0 They doesn't really reset the wait_timeout value but they do reset the "time since last command" so doing SHOW SESSION VARIABLES often enough would prevent the server to close the connection. So would SELECT 1.
I did it like this - it works in IE8, Fx3.6, Safari4, Chrome as opposed to the un-edited string which works in Fx but not in several other browsers:
new Date('2001-01-01T12:00:00Z'.replace(/\-/g,'\/').replace(/[T|Z]/g,' ')) but I am sure someone will post a REGEX with backreferencing :)
-34587113 0My opinion is that you can remove the george_holiday_passengers and add the type,age,gender columns to the george_holiday_users as looking to it; its only a extended data of the holiday_users table and build query with your new database tables.
$query = $this->db->select('u.*, p.package_name, p.description') ->from('george_holiday_users u') ->join('george_packges p', 'u.package_id = p.id', 'left') ->get(); return $query->result(); anyway, you can achieved the result using this query.
$query = $this->db->select('u.*, hp.type, hp.name AS passengers_name, hp.age, hp.gender, p.package_name, p.description') ->from('george_holiday_users u') ->join('george_holiday_passengers hp', 'hp.user_id = u.id', 'left') ->join('george_packges p', 'u.package_id = p.id', 'left') ->get(); return $query->result(); you should be careful about the column names because on your database there are a lot of columns with the same names, It might affect your query when your using joins, etc.
Hope that helps.
-23446458 0Do you really use command dir in your batch file or another command, a command which itself is enclosed in double quotes because of a space in path or has a parameter in double quotes?
If the output of a command should be processed within the loop and the command itself must be specified in double quotes or at least one of its parameters, the following syntax using back quotes is required:
for /f "usebackq delims=" %%a in (`"command to run" "command parameter"`) do echo %%a An example:
for /f "usebackq delims=" %%a in (`dir "%CommonProgramFiles%"`) do echo %%a %CommonProgramFiles% references the value of environment variable CommonProgramFiles which is a directory path containing usually spaces. Therefore it is necessary to enclose the parameter of command dir in double quotes which requires the usage of usebackq and back quotes after the opening and before the closing round bracket.
Further I suggest to look on value of environment variable PATH. There are applications which add their program files directory to PATH during installation, but not by appending the directory to end of the list of directories, but by inserting them at beginning. That is of course a bad behavior of the installer of those applications.
If you call in your batch file standard Windows commands not located in cmd.exe, but in Windows system directory which is usually the first directory in PATH, like the command find, and the installed application by chance has also an executable with same name in the program files directory of the application, the batch file might not work on this computer because of running the wrong command.
It is safer to use instead of just find in a batch file %SystemRoot%\system32\find.exe to avoid problems caused by bad written installer scripts of applications modifying the PATH list on wrong end.
I am using wkhtmltopdf (which uses the Webkit rendering engine) to convert HTML files to PDF documents. The generated PDFs are A4. In other words, they have fixed dimensions, and thus a limited width.
One of the tables in my PDF contains images, which are intricately pieced together in a puzzle-like fashion, and which sometimes take up a lot of room.
To fit the resulting puzzle in the constraints of an A4 PDF, I am applying the CSS property -webkit-transform: scale(...);
This scales the puzzle beautifully, and it is still clearly legible, but for some reason it also pushes the table containing the puzzle to the right. It seems to be adding a significant margin to the left of the puzzle table, despite my explicitly setting its left margin to 0.
Interestingly enough, the smaller the scale in my webkit transformation, the bigger the margin on the left. So for example, if I use scale(0.75) the resulting left margin is around 200 pixels. If I use scale(0.5) the resulting left margin is around 400 pixels.
I've tried aligning the puzzle table to the left using absolute, fixed and relative positioning with left: 0. I've also tried floating it to the left, as well as sticking it in a container with text-align set to left. None of these techniques work.
Any ideas where this left margin is coming from and how I can remove it / work around it?
-40826413 0 Issue about the return value of sengmsg for udpis there a partially-sent data when calling sendmsg for udp non block socket? when i want to data with a length of 5000, is there any possibility the sendmsg api just sent out 3000 or just return -1 with a errno EMSGSIZE? thanks
-38672248 0Ok, so i found the answer my self. before Triggering the animation event Rebind the Animator.
Animator anim = player.GetComponent<Animator>(); anim.Rebind();
-3156892 0 peer to multi-peer interprocess communication What is the best method for peer to multi-peer interprocess communication in windows. ( One application will send interrupts to many listeners ) One method comes to my mind is to use SendMessage with the HWND_BROADCAST parameter. What else I can do?
-1924360 0You might set DoubleBuffered to true on your control / form. Or you could try using your own Image to create a double buffered effect.
My DoubleBufferedGraphics class:
public class DoubleBufferedGraphics : IDisposable { #region Constructor public DoubleBufferedGraphics() : this(0, 0) { } public DoubleBufferedGraphics(int width, int height) { Height = height; Width = width; } #endregion #region Private Fields private Image _MemoryBitmap; #endregion #region Public Properties public Graphics Graphics { get; private set; } public int Height { get; private set; } public bool Initialized { get { return (_MemoryBitmap != null); } } public int Width { get; private set; } #endregion #region Public Methods public void Dispose() { if (_MemoryBitmap != null) { _MemoryBitmap.Dispose(); _MemoryBitmap = null; } if (Graphics != null) { Graphics.Dispose(); Graphics = null; } } public void Initialize(int width, int height) { if (height > 0 && width > 0) { if ((height != Height) || (width != Width)) { Height = height; Width = width; Reset(); } } } public void Render(Graphics graphics) { if (_MemoryBitmap != null) { graphics.DrawImage(_MemoryBitmap, _MemoryBitmap.GetRectangle(), 0, 0, Width, Height, GraphicsUnit.Pixel); } } public void Reset() { if (_MemoryBitmap != null) { _MemoryBitmap.Dispose(); _MemoryBitmap = null; } if (Graphics != null) { Graphics.Dispose(); Graphics = null; } _MemoryBitmap = new Bitmap(Width, Height); Graphics = Graphics.FromImage(_MemoryBitmap); } /// <summary> /// This method is the preferred method of drawing a background image. /// It is *MUCH* faster than any of the Graphics.DrawImage() methods. /// Warning: The memory image and the <see cref="Graphics"/> object /// will be reset after calling this method. This should be your first /// drawing operation. /// </summary> /// <param name="image">The image to draw.</param> public void SetBackgroundImage(Image image) { if (_MemoryBitmap != null) { _MemoryBitmap.Dispose(); _MemoryBitmap = null; } if (Graphics != null) { Graphics.Dispose(); Graphics = null; } _MemoryBitmap = image.Clone() as Image; if (_MemoryBitmap != null) { Graphics = Graphics.FromImage(_MemoryBitmap); } } #endregion } Using it in an OnPaint:
protected override void OnPaint(PaintEventArgs e) { if (!_DoubleBufferedGraphics.Initialized) { _DoubleBufferedGraphics.Initialize(Width, Height); } _DoubleBufferedGraphics.Graphics.DrawLine(...); _DoubleBufferedGraphics.Render(e.Graphics); } ControlStyles I generally set if I'm using it (you may have different needs):
SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.DoubleBuffer, true); Edit:
Ok since the data is static you should paint to an Image (before your OnPaint) and then in the OnPaint use the Graphics.DrawImage() overload to draw the correct region of your source image to the screen. No reason to redraw the lines if the data isn't changing.
I encountered this issue as you did. I got an error that's something like "couldn't find package Emacs-24.4". This inspired me to install Emacs-24.4 on my Ubuntu, instead of older version 24.3 which is the newest I can get from apt-get. (A convincing fact is that the newer version 24.5 provided by Homebrew works well with Purcell's package on my Mac.)
Under Emacs 24.4, slime proved to run well with Purcell's .emacs.d/. But it really costs me a lot of time to install Emacs-24.4 on my Ubuntu. First, I had to solve the problems of dependencies. Using aptitude, I get rid of the problem which apt-get failed to solve:
sudo apt-get install aptitude sudo aptitude install build-essential sudo aptitude build-dep emacs24 When the dependency issue pops out, aptitude will give you some suggestions including downgrading your current packages. I chose solutions of downgrade without leaving over any unsolved dependency problem (select 'no' until you find an acceptable one). During reinstalling build packages, Ubuntu iso cdrom may be required.
Then install Emacs 24.4:
wget http://open-source-box.org/emacs/emacs-24.4.tar.xz tar xvf emacs-24.4.tar.xz cd emacs-24.4 ./configure --prefix=$HOME/.local LDFLAGS=-L$HOME/.local/lib --without-pop --without-kerberos --without-mmdf --without-sound --without-wide-int --without-xpm --without-jpeg --without-tiff --without-gif --without-png --without-rsvg --without-xml2 --without-imagemagick --without-xft --without-libotf --without-m17n-flt --without-xaw3d --without-xim --without-ns --without-gpm --without-dbus --without-gconf --without-gsettings --without-selinux --without-gnutls --without-x make && make install References:
https://gist.github.com/tnarihi/6054dfa7b4ad2564819b
http://linuxg.net/how-to-install-emacs-24-4-on-ubuntu-14-10-ubuntu-14-04-and-derivative-systems/
-8716961 0Have you verified that tableViewController is not nil?
your @property should definitely be strong as the view controller is taking ownership of the entity. A weak reference will definitely nil out.
Likewise I would also put a breakpoint in the debugger and confirm that [self booking] does indeed point to a valid object at that point in the code.
This uses the codename as a String
Sub CodeIt() Dim CodeName As String CodeName = "Sheet1" Dim WS As Worksheet, GetWorksheetFromCodeName As Worksheet For Each WS In ThisWorkbook.Worksheets If StrComp(WS.CodeName, CodeName, vbTextCompare) = 0 Then Set GetWorksheetFromCodeName = WS Exit For End If Next WS MsgBox GetWorksheetFromCodeName.Name End Sub
-27489169 0 Dynamic StringGrid C++ Builder I created a program in C++Builder 6 and I have a problem now.
I have 6 files: Unit1.cpp, Unit1.h, Unit2.cpp, Unit2.h, Unit3.cpp, Unit3.h.
Unit1.cpp is file for main form.
Problem : I want to create in Function void __fastcall TForm3::Button1Click(TObject *Sender) a TStringGrid which will be visible in Unit1.cpp and Unit2.cpp. Next click should create new TStringGrid with new name(previous exist)
I tried to fix my problem, I wrote some code, but it is not enough for me.
In Unit1.h I added:
void __fastcall MyFunction(TStringGrid *Grid1); In Unit1.cpp I added:
void __fastcall TForm1::MyFunction(TStringGrid *Grid1) { Grid1 = new TStringGrid(Form2); Grid1->Parent = Form2; } In Unit3.cpp I added:
#include "Unit1.h" and the Button click function is:
void __fastcall TForm3::Button1Click(TObject *Sender) { Form1->MyFunction(Form1->Grid); //Grid was declarated previous in Unit1.h } Now when I used this method I dynamically create a TStringGrid, but only one. How do I create as many TStringGrids (with unique names) as the number of times the button is pressed? (Now i must declarate TStringGrid in Unit1.h).
I'm using Posture and I got error message "invalid input syntax for type timestamp with time zone" when using the following select code:
SELECT * FROM public."table1" WHERE 'registrationTimestamp' BETWEEN to_timestamp('22-10-2013 00:00', 'DD-MM-YYYY HH24:MI') AND to_timestamp('22-10-2013 23:59', 'DD-MM-YYYY HH24:MI')** While registrationTimestamp timestamp format is like following:
6/26/2012 6:43:10 PM
-14745605 0 I tried reproducing this in a simple jsbin demo to no avail. Drag and drop seems to work without losing the content. The code I've used was this:
<textarea class="editor" style="width: 400px">Editable Content</textarea> <textarea class="editor" style="width: 400px">Editable Content</textarea> <textarea class="editor" style="width: 400px">Editable Content</textarea> <textarea class="editor" style="width: 400px">Editable Content</textarea> <script> $(".editor").kendoEditor().closest(".k-widget").draggable(); </script>
-6471481 0 This may be useful:
http://gcc.gnu.org/onlinedocs/gcc-4.1.1/cpp/Search-Path.html#Search-Path
Since you also have the sql-server tag on your question, unfortunately sql-server doesn't have GROUP_CONCAT, an alternative like FOR XML / STUFF is needed:
SELECT f.id, f.movie_name, STUFF((SELECT ',' + p.person_name FROM persons p INNER JOIN films_cast fc on fc.person_id = p.id WHERE fc.film_id = f.id AND fc.type = 'director' FOR XML PATH ('')) , 1, 1, '') AS director, STUFF((SELECT ',' + p.person_name FROM persons p INNER JOIN films_cast fc on fc.person_id = p.id WHERE fc.film_id = f.id AND fc.type = 'writer' FOR XML PATH ('')) , 1, 1, '') AS writer, STUFF((SELECT ',' + p.person_name FROM persons p INNER JOIN films_cast fc on fc.person_id = p.id WHERE fc.film_id = f.id AND fc.type = 'actor' FOR XML PATH ('')) , 1, 1, '') AS cast FROM films f;
-19119752 0 So after a long profiling session, with XDEBUG, phpmyadmin and friends, I finally narrowed down what the bottleneck was: the mysql queries
I enabled
define('SAVEQUERIES', true);
to examine the queries in more detail and I output the queries array to my debug.log file
global $wpdb; error_log( print_r( $wpdb->queries, true ) ); upon examining each INSERT call to the database
wp_insert_post()
[0] => INSERT INTO wp_posts (post_author,post_date,post_date_gmt,post_content,post_content_filtered,post_title,post_excerpt,post_status,post_type,comment_status,ping_status,post_password,post_name,to_ping,pinged,post_modified,post_modified_gmt,post_parent,menu_order,guid) VALUES (...)
[1] => 0.10682702064514
update_post_meta()
[0] => INSERT INTO wp_postmeta (post_id,meta_key,meta_value) VALUES (...)
[1] => 0.10227680206299
I found that each one of those calls to the database costs, on average, ~0.1 s on my localhost server
But, since I am updating 6 custom fields per entry, it works out to
6 cf insert calls/entry * ~0.1s/cf insert call *20 000 total entries * 1 min/60s = 200 min
~2.5 hrs to process the custom fields alone for 20k posts
Now, since all the custom fields are inserted into the same table, wp_post_meta, I looked to combine all the update_post_meta calls into one call, and hence, drastically improve the performance in terms of the execution time of this import script.
I looked through the update_post_meta function in the wp core and saw there was no native option to pass an array instead of a single cf key and value, so I went through the relevant code to pinpoint the SQL INSERT line and looked how to do something along the lines of:
`INSERT INTO `wp_postmeta` (`post_id`,`meta_key`,`meta_value`) VALUES ( $post_id, 'artist_name' , $artist) ( $post_id, 'song_length' , $length ) ( $post_id, 'song_genre' , $genre ) ...` and so forth for all the 6 custom fields in my case, all rolled in inside a single $wpdb->query(); .
Tweaking my process_custom_post() function to reflect this, I ended up with:
function process_custom_post($song) { global $wpdb; // Prepare and insert the custom post $track = (array_key_exists(0, $song) && $song[0] != "" ? $song[0] : 'N/A'); $custom_post = array(); $custom_post['post_type'] = 'songs'; $custom_post['post_status'] = 'publish'; $custom_post['post_title'] = $track; $post_id = wp_insert_post( $custom_post ); // Prepare and insert the custom post meta $meta_keys = array(); $meta_keys['artist_name'] = (array_key_exists(1, $song) && $song[1] != "" ? $song[1] : 'N/A'); $meta_keys['song_length'] = (array_key_exists(2, $song) && $song[2] != "" ? $song[2] : 'N/A'); $meta_keys['song_genre'] = (array_key_exists(3, $song) && $song[3] != "" ? $song[3] : 'N/A'); $meta_keys['song_year'] = (array_key_exists(4, $song) && $song[4] != "" ? $song[4] : 'N/A'); $meta_keys['song_month'] = (array_key_exists(5, $song) && $song[5] != "" ? $song[5] : 'N/A'); $meta_keys['sample_playlist'] = (array_key_exists(6, $song) && $song[6] != "" ? $song[6] : ''); $custom_fields = array(); $place_holders = array(); $query_string = "INSERT INTO $wpdb->postmeta ( post_id, meta_key, meta_value) VALUES "; foreach($meta_keys as $key => $value) { array_push($custom_fields, $post_id, $key, $value); $place_holders[] = "('%d', '%s', '%s')"; } $query_string .= implode(', ', $place_holders); $wpdb->query( $wpdb->prepare("$query_string ", $custom_fields)); return true; } and viola! Instead of 7 INSERT calls to the database per custom post, I end up with 2 making a gynormous difference when attempting to process multiple custom fields while iterating over a large number of posts - in my case now, 20k entries are processed to completion within 15-20min (vs a situation where I would experience a dropout after ~17k posts and a few hrs of processing time)...
So the key thing I learned from this whole experience,
mind your database calls - they can quickly add up!
-119732 0 How to initialize Hibernate entities fetched by a remote method call?When calling a remote service (e.g. over RMI) to load a list of entities from a database using Hibernate, how do you manage it to initialize all the fields and references the client needs?
Example: The client calls a remote method to load all customers. With each customer the client wants the reference to the customer's list of bought articles to be initialized.
I can imagine the following solutions:
Write a remote method for each special query, which initializes the required fields (e.g. Hibernate.initialize()) and returns the domain objects to the client.
Like 1. but create DTOs
Split the query up into multiple queries, e.g. one for the customers, a second for the customers' articles, and let the client manage the results
The remote method takes a DetachedCriteria, which is created by the client and executed by the server
Develop a custom "Preload-Pattern", i.e. a way for the client to specify explicitly which properties to preload.
The extension tt_news is very useful for me but there is this little thingy called "register:newsMoreLink". This register does contain the singlePid of the contentelement (defined a single view page) and the uid of the newsarticle from the news extension.
This is the typoscript section of the "new ts" of the extension tt_news As you can see there is "append.data = register:newsMoreLink"...
plugin.tt_news { displayLatest { subheader_stdWrap { # the "more" link is directly appended to the subheader append = TEXT append.data = register:newsMoreLink append.wrap = <span class="news-list-morelink">|</span> # display the "more" link only if the field bodytext contains something append.if.isTrue.field = bodytext outerWrap = <p>|</p> } } } What is "register:newsMoreLink"? Is this like a function or something? I do not know. But "register:newsMoreLink" produces a strange link if I use this on "append.data". It produces are "More >" link. The "More >" link after a news article teaser looks like this:
http://192.168.1.29/website/index.php?id=474&tx_ttnews%5Btt_news%5D=24&cHash=95d80a09fb9cbade7e934cda5e14e00a
474 is the "singlePid" (this is what it calls in the database 24 is the "uid" of the news article (the ones you create with the tt_news plugin in the backend)
My question is: Where is the "register:newsMoreLink" defined? Is it defined generally or do I miss a fact of Typo3..? How can I add an anchor link at the end of this "More >" href? Like:
-20279340 0
Let's start from the beginning. Since fs is a List[Future[T]], you know x is a Future[T].
You need to register a callback that will fire when the result of x becomes available. The easy way to do this is with onComplete, which takes a function of type Try[T] => U.
So the underscore is a Try[T], which holds the result of x, the Future[T]. There are two possible results for a Future: Success[T], when the Future[T] worked and holds a result, and Failure[T], which holds an exception because the Future[T] didn't work.
So Try is similar to Option, a way to safely represent an outcome.
Hope that helps.
-7732831 0Assuming you want to use Ada.Text_IO and not just Put_Line specifically, and assuming that Number_Of_Rows is meant to be an integer range like Num_Char, that would be
for R in The_Chars'Range (1) loop for C in The_Chars'Range (2) loop Ada.Text_IO.Put (The_Chars (R, C)); end loop; Ada.Text_IO.New_Line; end loop;
-10704232 0 Another option is to just use Resharper's To-do Explorer window, which you probably already have and if not, should have. You can dock it right with the other windows. It parses all the files (cs, js, css, etc.).
-39537192 0 R plot.xts error barsTrying to put error bars on a time series plot using plot.xts
> myTS[1:20] [,1] 2013-07-01 29 2013-07-03 24 2013-07-03 16 2013-07-03 16 2013-07-03 12 2013-07-03 12 2013-07-03 16 2013-07-03 21 2013-07-03 21 2013-07-03 16 2013-07-05 12 2013-07-05 12 2013-07-05 12 2013-07-05 12 2013-07-08 16 2013-07-08 23 2013-07-08 16 2013-07-08 12 2013-07-09 16 2013-07-09 12 I've aggregated this using myTSquarterly = apply.quarterly(myTS,mean)
> myTSquarterly [,1] 2013-09-30 24.50829 2013-12-31 23.79624 2014-03-31 24.15170 2014-06-30 24.57641 2014-09-30 23.71467 2014-12-31 22.99500 2015-03-31 24.50423 2015-06-30 25.19950 2015-09-30 24.76330 2015-12-31 24.65810 2016-03-31 25.35616 2016-06-30 22.71066 2016-07-27 20.63636 I can plot easily using plot.xts(myTSquarterly):
I can calculate standard deviation easily as well with apply.quarterly(myTS,sd)
I would like to add these standard deviation info as error bars to the plot, but I cannot find a method for this?
-8327569 0Here:
public static bool TryConvertToInt32(decimal val, out int intval) { if (val > int.MaxValue || val < int.MinValue) { intval = 0; // assignment required for out parameter return false; } intval = Decimal.ToInt32(val); return true; }
-5709094 0 Raise an event from inside native c function? I am developing an application that does a callback to a native c function after playing a system sound. I would like to raise an event when this happens, so a subscriber on my view may handle it.
-(void) completionCallback(SystemSoundID mySSID, void* myself) { [[NSNotificationCenter defaultCenter] postNotificationName:@"SoundFinished" object: myself]; } I recieve unrecognized selector sent to instance ...
On the view, I have the following code:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(soundStopped) name:@"SoundFinished" object:nil]; ...
-(void) soundStopped: (NSNotification*) notification { NSLog(@"Sound Stopped"); } I am extremely new to objective-c, where am I going wrong?
Update The exact error is:
2011-04-18 19:27:37.922 AppName[5646:307] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[BackgroundTestViewController soundStopped]: unrecognized selector sent to instance 0x13b4b0'
-2192006 0 Failed to Map Path '/doc'. server.map path If I run the site using the internal Visual Studio web server, I get the failed to map path error.
-5838508 0The problem is likely to be at the 2nd cur = cur->next;, which follows the while loop - at that point the loop has guaranteed that cur == NULL.
I'm not sure what you're trying to do in that function (has some code been elided for the example?), so don't really have a suggesting at the moment.
Also, as your compiler warnings indicate, nothing is being returned by the function even though it's declared to do so. I would have assumed again that this is because something is removed for the purposes of the example in the question, but then again your compiler is complaining as well. Any caller that uses whatever the function is supposed to return is in for a surprise. That surprise may also be a segfault.
-35561493 0There's a few ways to clean this up in Ruby that I'll demonstrate here:
puts 'Hello mate what is thy first name?' name1 = gets.chomp # Inline string interpolation using #{...} inside double quotes puts "Your name is #{name1} eh? What is thy middle name?" name2 = gets.chomp # Interpolating a single string argument using the String#% method puts 'What is your last name then %s?' % name1 name3 = gets.chomp # Interpolating with an expression that includes code puts "Oh! So your full name is #{ [ name1, name2, name3 ].join(' ') }?" puts 'That is lovey!' # Combining the strings and taking their aggregate length puts 'Did you know there are %d letters in your full name?' % [ (name1 + name2 + name3).length ] # Using collect and inject to convert to length, then sum. puts 'Did you know there are %d letters in your full name?' % [ [ name1, name2, name3 ].collect(&:length).inject(:+) ] The String#% method is a variant of sprintf that's very convenient for this sort of formatting. It gives you a lot of control over presentation.
That last one might look a bit mind-bending but one of the powerful features of Ruby is being able to string together a series of simple transformations into something that does a lot of work.
That part would look even more concise if you used an array to store the name instead of three independent variables:
name = [ ] name << gets.chomp name << gets.chomp name << gets.chomp # Name components are name[0], name[1], and name[2] # Using collect -> inject name.collect(&:length).inject(:+) # Using join -> length name.join.length It's generally a good idea to organize things in structures that lend themselves to easy manipulation, exchange with other methods, and are easy to persist and restore, such as from a database or a file.
-30256865 0Unfortunately it is something related with a bad design of the class InputStream. If you use read() you will have that problem. You should use read(byte[]) instead. But as you say, you could also use Int. That is up to you.
I finally got the solution. The problem was with the field's verbose name - it was str instead of unicode. Moving to unicode helped.
Thanks :-)
-1666351 0You can easily invoke log4j's API programmatically, e.g.
FileAppender appender = new FileAppender(); // configure the appender here, with file location, etc appender.activateOptions(); Logger logger = getRootLogger(); logger.addAppender(appender); The logger can be the root logger as in this example, or any logger down the tree. Your unit test can add its custom appender during steup, and remove the appender (using removeAppender()) during teardown.
I'm trying to create a custom menu in drupal 7 by coding it in a custom code block, but I'm running into the issue that the links I create aren't lined up to the way my local site is setup. Is there php code or a drupal setting of some sort that can create a link relative to the local machine setup?
To give more context: My friend and I are working on creating a drupal site and have individually setup our local files differently (we are sharing the database which is on a remote server). When browsing to the site, his URL shows up: localhost/content/page. Whereas how I have it setup is: localhost/sitename/content/page.
When I create an internal link in the nav menu, I have to create it using a relative path /content/page, otherwise the link wont work on my coworkers localhost. This, in turn, makes it so that the link doesn't work on my locahost.
Is there a way I can create these links relative to the localhost so that it works on both machines? When creating a navigation menu using my Drupal theme this is not an issue, but since the link list I'm creating is custom coded, I can't seem to figure out how to mimic this same functionality.
Any ideas? Thanks!
-30407326 0When the JUnitXmlTestsListener saves an XML element with XML.save the default encoding that is used is ISO-8859-1. It should use UTF-8 instead.
You can try to remove the JUnitXmlTestsListener from your build and use specs2 to generate junit-xml reports:
libraryDependencies += "org.specs2" %% "specs2-junit" % "3.6" sbt> testOnly *MySpec -- console junitxml
-18838055 0 Embed HTML inside JSON request body in ServiceStack I've been working with ServiceStack for a while now and recently a new need came up that requires receiving of some html templates inside a JSON request body. I'm obviously thinking about escaping this HTML and it seems to work but I would prefer consumers not to bother escaping a potentially large template. I know ASP.NET is capable of handling this but I wonder if it can be done with ServiceStack.
The following JSON body is received incomplete at the REST endpoint because of the second double quote ...="test...
{ "template" : "<html><body><div name="test"></div></body></html>" }
-13749049 0 You cannot schedule IO tasks because they do not have a thread associated with them. The Windows Kernel provides thread-less IO operations. Starting these IOs does not involve managed code and the TaskScheduler class does not come into play.
So you have to delay starting the IO until you are sure you actually want the network to be hit. You could use SemaphoreSlim.WaitAsync to throttle the amount of tasks currently running. Await the result of that method before starting the individual IO and awaiting that as well.
When I try to pass a Map to a post, I get this error:
Cannot write an instance of scala.collection.immutable.Map[java.lang.String,java.lang.String] to HTTP response. Try to define a Writeable[scala.collection.immutable.Map[java.lang.String,java.lang.String]]
Here is my post example:
WS.url("http://mysql/endpoint") .post(Map("email" -> "juju@juju.com")).map { response => Logger.logger.debug("response: " + response.body) } What is happening?
-29709380 0This denotes a JSON array of three objects:
[ { ... }, { ... }, { ... } ] So you cannot deserialize this to a single object. It needs to be deserialized to an array/list by indicating the result should be a List:
List<Picture> pictures = JsonConvert.DeserializeObject<List<Picture>>(InputBox.Text);
-26895188 0 Here's a workaround:
Replace all the 0s in Z by NaN, calculate the min, then switch back to 0:
clear all clc close all Z(:,:,1) = [-5 0 5 0 0 0 1 0 3]; Z(:,:,2) = [1 0 2 0 0 0 0 0 0]; Z(:,:,3) = [0 0 0 -9 0 4 0 0 0]; Z(:,:,4) = [0 0 0 -2 0 0 0 0 0]; %// Assign NaN to 0 elements Z(Z ==0) = NaN; Zmin = min(Z,[],3); %// Switch back with 0 Zmin(isnan(Zmin)) = 0; %// Same for Z; Z(isnan(Z)) =0; The output looks like this:
Zmin Z Zmin = -5 0 2 -9 0 4 1 0 3 Z(:,:,1) = -5 0 5 0 0 0 1 0 3 Z(:,:,2) = 1 0 2 0 0 0 0 0 0 Z(:,:,3) = 0 0 0 -9 0 4 0 0 0 Z(:,:,4) = 0 0 0 -2 0 0 0 0 0
-22077268 0 The above code will only run once only which will add information to head only once. If you want to add more information in case of second run then add code for else condition. Example:-
if ( head == NULL ) { // code to insert data in case of first run }else{ // code to insert data for second run and so..... }
-4377515 0 \S matches anything but a whitespace, according to this reference.
One of the things I like most about Javascript is the way you can access the properties of an object with object.property as well as object["property"]. In Ruby you can only access the value of a hash with hash["value"].
To answer your question, you will need to find a way of converting list_key and name_key so that it works in Ruby. The best way to do that depends on how you're handling the parsing of the JSON in the first place but I it should be as simple as splitting list_key and name_key up into an array of stings and then accessing those values on the hash.
Hope that helps.
-37733893 0 Squash git commits from topic branchI have a topic branch (macaroni), and I have submitted a pull request. I had to make a change after feedback. It was requested that I squash the two commits into a single commit. This is what I have done:
git status On branch macaroni git log commit def feedback fixes commit abc fix cheddar flavor git rebase -i origin/master .. go through screen where I pick commit to squash .. .. go through screen where I update commit message .. git log commit abc fix cheddar flavor, squashing done! at this point I believe I have to push my topic branch using the -force flag, because I have changed history:
git push -f I am using the second answer from this question:
Preferred Github workflow for updating a pull request after code review
with subtitle "Optional - Cleaning commit history". The author mentions at the end that you should be using topic branches, not sure if I should have changed any of the commands since I'm already on a topic branch.
I am also concerned with accidentally force-pushing something onto the master branch with the above since I'm using -f, but since I'm on the topic branch, only that branch should be affected, right?
Thanks
-6943171 0You can get horizontal align for this image using for tag "a":
text-align: center; But for to get vertical align unfortunately you need to set margin-top for this image with hands using known height of parent div (or, with the same result, padding-top for "a" tag). You can use some jquery plugins for it (just search something like "jquery vertical align plugin" in google, there are many plugins for it) or write your own script.
-5068173 0You can implement expected behaviour with biltin features of MSBuild 4:
<ItemGroup> <DeploymentProjects Include="1_deploy" /> <DeploymentProjects Include="2_deploy" /> </ItemGroup> <Target Name="CopyMidTierBuildOutput" > <Message Text="Copying midTier Build Output" Importance="High"/> <ItemGroup> <MidTierDeploys Include="$(DeploymentRoot)**\%(DeploymentProjects.Identity)\$(Configuration)\**\*.*"> <DeploymentProject>%(DeploymentProjects.Identity)</DeploymentProject> </MidTierDeploys> </ItemGroup> <Msbuild Targets="CopyDeploymentItem" Projects="$(MSBuildProjectFile)" Properties="ItemFullPath=%(MidTierDeploys.FullPath);ItemRecursiveDir=%(MidTierDeploys.RecursiveDir);ItemDeploymentProject=%(MidTierDeploys.DeploymentProject);Configuration=$(Configuration);DestFolder=$(DestFolder)" /> </Target> <Target Name="CopyDeploymentItem" > <PropertyGroup> <ItemExcludePath>$(ItemDeploymentProject)\$(Configuration)</ItemExcludePath> <ItemDestRecursiveDirIndex>$(ItemRecursiveDir.IndexOf($(ItemExcludePath))) </ItemDestRecursiveDirIndex> <ItemExcludePathLength>$(ItemExcludePath.Length)</ItemExcludePathLength> <ItemSkippingCount>$([MSBuild]::Add($(ItemDestRecursiveDirIndex), $(ItemExcludePathLength)))</ItemSkippingCount> <ItemDestRecursiveDir>$(ItemRecursiveDir.Substring($(ItemSkippingCount)))</ItemDestRecursiveDir> </PropertyGroup> <Copy SourceFiles="$(ItemFullPath)" DestinationFolder="$(DestFolder)/MidTier/$(ItemDeploymentProject)/$(ItemDestRecursiveDir)" ContinueOnError="false" /> </Target> See Property functions for more info.
-27125961 0HTML entities like & are not a part of URI specification. As far as RFC 3986 is concerned, & is a sub-delimiting character, therefore if a server receives a query string like this:
foo=1&bar=2 and parses it to the following key-value pairs:
'foo' => '1', 'amp;bar' => '2' it is behaving correctly.
To make things even more interesting, ; is a reserved sub-delimiter, too, but:
-37154863 1 How to multiplex python coroutines( send and receive) in a websocket based chat client via an event loopif a reserved character is found in a URI component and no delimiting role is known for that character, then it must be interpreted as representing the data octet corresponding to that character's encoding in US-ASCII.
I am writing a console based chat server based on websockets and asyncio for learning both websockets and asyncio without using any other frameworks like Twisted, Tornado etc .. So far I have established the connection between client and server and am able to unicast and multicast messages between logged in users by writing send and receive in a single coroutine but this makes the clients block on either send or receive. So I tried by splitting up the send and receive coroutines but now after sending the first message to the server the client is unable to send any other message.
Problems:
Below is the code sample for the minimal client that i am using. What I have understood from asyncio till now is that when one of the coroutine is waiting over its "yield from", the other coroutine will get a chance to execute please point out if my understanding of the asyncio is correct or not:
import sys import asyncio import websockets qSend = asyncio.Queue() def got_stdin_data(qSend): asyncio.async(qSend.put(sys.stdin.readline())) def myClient_recv(): websocket = yield from websockets.connect('ws://localhost:8765/') while True: recvText = yield from websocket.recv() print(">>> {}".format(recvText)) def myClient_send(): websocket = yield from websockets.connect('ws://localhost:8765/') while True: sendText = yield from qSend.get() yield from websocket.send(sendText) loop = asyncio.get_event_loop() loop.add_reader(sys.stdin, got_stdin_data, qSend) asyncio.async(myClient_recv()) asyncio.async(myClient_send()) loop.run_forever()
-10302647 0 If you want to pass the whole list in a single parameter, use array datatype:
SELECT * FROM word_weight WHERE word = ANY('{a,steeple,the}'); -- or ANY('{a,steeple,the}'::TEXT[]) to make explicit array conversion
-7167976 0 The collection is a reference type, so other holding code onto that will see the old data.
Two possible solutions:
Instead of data = temp use data.Clear(); data.AddRange(temp) which will change the contents of the data field.
Or better delete the MyCollection property and make class implement IEnumerable. This results in much better encapsulation.
-33272926 0 Determine if two unsorted arrays are identical?Given two unsorted arrays A and B with distinct elements, determine if A and B can be rearranged so that they are identical.
My strategy was as follows:
A and Max of B, if they don't have the same Max, we can automatically declare that they are not identical, otherwise, move to step 2.C of size 2N.D of size Max(A) and scanning C and bumping the counters of the appropriate index in D (we don't actually need to complete the counting sort algorithm, we just need this intermediate step).D array, if any D[i] = 1, we know that the arrays are not identical, otherwise they are identical.Claim: Time Complexity O(N), and no constraints on space.
Is this a correct algorithm ?
-25453708 0Each any() usage is converted into it's own subquery. If you need to combine multiple conditions you will need to write the subquery yourself.
any() isn't a join alternative, but a subquery exists shortcut. Maybe that helps.
-9534072 0There is an example, if this is what you are looking for: Animated Window Opener Script
-36885038 0Just a quick shot here. Try this one, instead of existing statement
<Modal ... onAfterOpen={() => this.context.executeAction(LoadUsersByDepartment, 8)} ... > What your code does is:
when modal is opened, execute the result from this.context.executeAction(LoadUsersByDepartment, 8) call.
Adjusted code executes your action (not it's result) when modal is opened.
-37299020 0Instance types are cached in the browser's local storage. You can explicitly refresh the cache via the 'Refresh all caches' link:
If you show the network tab of your browser's console (prior to clicking 'Refresh all caches'), you should see a request to http://localhost:8084/instanceTypes.
If the response contains your instance types, you should be good to go.
-2517791 0 How can I get the GUID from a PDB file?Does anyone know how to get the GUID from a PDB file?
I'm using Microsoft's Debug Interface Access SDK
http://msdn.microsoft.com/en-us/library/f0756hat.aspx
and getting E_PDB_INVALID_SIG when passing in the GUID i expect when trying to load the PDB.
I'd just like to know the GUID of the PDB so I can be certain that it's mismatching and not just a PDB that's perhaps corrupted somehow.
Is there a tool that can do this? I've tried dia2dump and dumpbin, but with no joy...
Many thanks,
thoughton.
-16897503 0 Increasing Limit of Attached Databases in SQLite from PDOI'm working on a project that should benefit greatly from using one database file per each table, mostly because I'm trying to avoid having the database grow too large but also because of file locking issues.
I thought of using the ATTACH statement to have a "virtual" database with all my tables, but I just found out that while the upper limit of attached databases is 62 (which would be totally acceptable for me), the default limit of attached databases is in fact 10, from the SQLite limits page:
Maximum Number Of Attached Databases
The ATTACH statement is an SQLite extension that allows two or more databases to be associated to the same database connection and to operate as if they were a single database. The number of simultaneously attached databases is limited to SQLITE_MAX_ATTACHED which is set to 10 by default. The code generator in SQLite uses bitmaps to keep track of attached databases. That means that the number of attached databases cannot be increased above 62.
Since I will need to support more than 10 tables, my question is, how do I set the SQLITE_MAX_ATTACHED variable to a higher value from PHP (using PDO with SQLite 3)?
I think the 1st answer is the best though you can use images in borders now, try using a png image with transparency (via photoshop) use the border-image property, there's so many ways to use it you may find another style you prefer in the research.
http://www.css3.info/preview/border-image/
-23602373 0 Jquery Slider using div and with paginationI'm trying to create a image slider where in images are place inside a DIV.
So basically, I have 3 divs, they can be control using a href html, the first one, its function will move to the first div, second move to center div, and last move to the 3rd div the last one. I think this is called pagination? Correct me if I'm wrong. I did not place an image on the div to simplify the codes.
<a href="" id="show1">Move to first div</a> <a href="" id="show2">Move to center</a> <a href="" id="show3">Move to 3rd div</a> <div id="main-wrapper"> <div id="inner-wrapper"> <ul> <li><div id="div1" class="divstyle">this is first</div></li> <li><div id="div2" class="divstyle">this is second</div></li> <li><div id="div3" class="divstyle">this is third</div></li> </ul> </div> </div> This is how I tested it in jquery.
$(document).ready(function(){ $('#show1').click(function() { $('ul li div').animate({ left: '-=450' }, 3000, function() { // Animation complete. }); }); }); I used the selector (ul li div) and used animate(), I tested a simple moving to the left, but it is not working. Any idea on this one?
Basically this is what I'm trying to achieve.
http://theme.crumina.net/onetouch2/
This is the css ,.
<style> .divstyle { text-align: center; width:450px; height:300px; border:1px solid #000; margin: auto; } #inner-wrapper ul li { list-style:none; position:relative; float:left; } #inner-wrapper li { display: inline; } #main-wrapper { position: relative; overflow:hidden; width:100%; border:1px solid #000; height: 350px; float:left; } #inner-wrapper { display: table; /* Allow the centering to work */ margin: 0 auto; position: relative; height: 300px; width:500px; border:1px solid #000; overflow: hidden; } </style>
-31915923 0 Yash, have you made sure that your Tomcat installation is working properly? You should be able to access the manager app (usually under localhost:8080/manager/html) and see all running applications, regardless of whether you have iteraplan deployed on the server or not. Also, to run iteraplan, you need a database (details can be found in the iteraplan installation guide: http://www.iteraplan.de/wiki/display/iteraplan34/Installation+Guide). Finally, if you just want to run the application, without modifying the code, it would be simpler to download one of the bundles available in sourceforge (http://sourceforge.net/projects/iteraplan/files/iteraplan Community Edition/). They have a Tomcat server and a database included.
-11253398 0You are probably not going to like this answer but I think if you are going to this much trouble to optimise the sql that linq is outputting then it is easier just to write it in sql.
-15818586 0You can use 3rd party library to get log about crash and exception. I have used MarkedUp. Another way is to create own web service which sends crash log to some database.
-40354505 0You can manually bootstrap angular after receive data from server.
Example on jsfiddle:
var app = angular.module("myApp", []); app.controller("myController", function($scope, servicesConfig) { console.log(servicesConfig); $scope.model = servicesConfig.host; $scope.reset = function() { $scope.model = ''; }; }); angular.element(document).ready(function() { //Simulate AJAX call to server setTimeout(function() { app.constant('servicesConfig', { host: "appdev" }); angular.bootstrap(document, ['myApp']); }, 2000); }); <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-cloak> <div ng-controller="myController"> <input type="text" ng-model="model" /> {{model}} <button ng-click="reset()">Reset</button> </div> </div> As others have pointed out the problem, I thought I would suggest an easier solution
File.AppendAllText(filename, "test");
-5286116 0 If you like to learn by doing then learn by doing it in PDO and bind the parameters. This is the safe and correct way to do it these days.
-32725478 0 Retrieving original class types from anonymous classesGiven a class with an empty constructor and a var:
class MyClass() { var myVar: Int = 0 } When the class is instantiated with a closure, this yields an object with the underlying type of an anonymous class rather than MyClass:
// getClass yields type my.package.MainClass$$anonfun$1$anonfun$apply... val myNewClassInstance: MyClass = new MyClass() { myVar = 2} Is it possible to retrieve the original class type MyClass using reflection and the object myNewClassInstance, in order to create new object instances from it?
-40659647 0 Can not Update A Picture Into A Database Using PDOHaving problems updating an image into the database. If I try to update this is what comes on the screen
Notice: Undefined index: picture in C:\xampp\htdocs\churchapp\db\controller.php on line 193
Warning: getimagesize(): Filename cannot be empty in C:\xampp\htdocs\churchapp\db\db.php on line 45
if (isset($_POST['updatemember'])) { extract($_POST); $picture = $_FILES['picture']; $imagename = $picture['name']; $fileInfo = array( 'name' => $picture['name'], 'type' => $picture['type'], 'temp_name' => $picture['tmp_name'], 'error' => $picture['error'], 'size' => $picture['size'] ); $upload = $con->uploadImage($fileInfo); if ($upload == 1) { $con->command("UPDATE member SET pic = '".$imagename."', firstname = '".$fname."', lastname = '".$lname."', othernames = '".$othernames."', dob = '".$dob."', age = '".$age."', gender = '".$gender."', occupation = '".$occupation."', phonenumber = '".$pnum."', email = '".$email."', residence = '".$residence."', hometown = '".$hometown."', mstatus = '".$mstatus."', nod = '".$nod."', ministry = '".$ministry."', position = '".$position."', department = '".$department."', dojc = '".$dojc."', doma = '".$doma."', doc = '".$doc."', d_baptize = '".$d_baptize."', dofm = '".$dofm."', domr = '".$domr."', tithe_payer = '".$tithe_payer."', pre_church = '".$pre_church."' WHERE id = '".$id."' "); header("Location: ../viewallmem.php"); } } and public function uploadImage($f){ $target_dir = "../images/"; $target_file = $target_dir . basename($f['name']); $uploadOk = 1; $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); // Check if image file is a actual image or fake image $check = getimagesize($f['temp_name']); if($check !== false) { $uploadOk = 1; } else { $uploadOk = 0; } // Check if file already exists if (file_exists($target_file)) { $uploadOk = 0; } // Check file size if ($f['size'] > 50000000) { $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "PNG" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { // if everything is ok, try to upload file }else { move_uploaded_file($f['temp_name'], $target_file); } return $uploadOk; }
-4193721 0 If you want to implement server side sorting then it does not matter what technology you are using in the front end.
On a conceptual level you can do the following things:
Anyone who has programmed with actionscript 3.0 has most certainly noticed its lack of support for private constructors and abstract classes. There are ways to work around these flaws, like throwing errors from methods which should be abstract, but these work arounds are annoying and not very elegant. (Throwing an error from a method that should be abstract is a run-time check, not compile-time, which can lead to a lot of frustration).
I know actionscript 3.0 follows the current ECMAscript standard and this is the reason for its lack of private constructors, but what about abstract classes, are they not in the ECMAscript standard eather?
I guess the more specific question is why does ECMAscript standard not support private constructors? Is it something that can be look forward to in the future?
I have been wondering this for quit sometime, any insight will be much appreciated.
-33941965 0 Android How to package as APII am working on providing SDK support for another apps by opening my app UI elements into another app. Its like having Facebook SDK integrated with other apps where one when click on "Login with Facebook" facebook UI comes up. Other apps like Uber has its own SDK How can I achieve it? One option is to have .jar/.aar file packaged. Or Deep linking works well? Please also suggest some documentation which can help me. Thanks,
-19547000 0A little whitespace will go a long way...
The opposite of $0 ~ s is $0 !~ s, so
cvs -q status | awk ' c-- > 0 $0 !~ s { if (b) for (c=b+1; c>1; c--) print r[(NR-c+1)%b] print c=a } b {r[NR%b]=$0} ' b=1 a=9 s='Up-to-date'
-25581667 0 Match the top of the characters and the bottom baseline of the font Do you know of a reliable way to have borders matching the baseline of the font and the top of the characters?
I'm not sure it's very clear as I lack the words to explain this precisely, so here is an example: http://codepen.io/anon/pen/zwjLf. This is what I've been able to achieve messing with the line-height property until finding the best value:
line-height: 0.7em; But I guess it's not a very clean or reliable way to do it.
-11719652 0Glyph ID's do not always correspond to Unicode character values - especially with non latin scripts that use a lot of ligatures and variant glyph forms where there is not a one-to-one correspondance between glyphs and characters.
Only Tagged PDF files store the Unicode text - otherwise you may have to reconstruct the characters from the glyph names in the fonts. This is possible if the fonts used have glyphs named according to Adobe's Glyph Naming Convention or Adobe Glyph List Specification - but many fonts, including the standard Windows fonts, don't follow this naming convention.
-34987254 0 iOS how to cache data when kill application?I am developing a new feature for my app. I want cache all datas get from web service to read when offline.
Current, my app can cache data but when I killed my app It didn't work.
I saw an application https://itunes.apple.com/us/app/smartnews-trending-news-stories/id579581125?mt=8 can cache everything when killed application.
Do you have some suggest for me?
Thanks.
Some editions of find, mostly on linux systems, possibly on others aswell support -regex and -regextype options, which finds files with names matching the regex.
for example
find . -regextype posix-egrep -regex ".*\.(py|html)$" should do the trick in the above example. However this is not a standard POSIX find function and is implementation dependent.
-36754439 0Use background-size: cover; or background-size: contain; as per your necessity. That should fix it.
I have used this method on form2 to get values over to form3:
**form2.cs** Form3 frm3 = new Form3(cbDelivery.Text, cbOderNo.Text, cbCartonCode.Text, lblGRV.Text); frm3.Show(); this.Hide(); But now every time I want to use that I get "no overload for method 'form3' takes '0' arguments".
I do understand its looking for that same values but I don't need them. For example when I'm on form4 and want to go back to form3.
How do I bypass this?
Thanks in advance.
-29024997 0The PowerPivot tab is a COM Add-In. To view the progID of it and other COM Add-Ins use:
Sub ListCOMAddins() Dim lngRow As Long, objCOMAddin As COMAddIn lngRow = 1 With ActiveSheet For Each objCOMAddin In Application.COMAddIns .Cells(lngRow, "A").Value = objCOMAddin.Description .Cells(lngRow, "B").Value = objCOMAddin.Connect .Cells(lngRow, "C").Value = objCOMAddin.progID lngRow = lngRow + 1 Next objCOMAddin End With End Sub` In my case the progID of the PowerPivot tab is "Microsoft.AnalysisServices.Modeler.FieldList". So to close the tab use:
Private Sub Workbook_Open() Application.COMAddIns("Microsoft.AnalysisServices.Modeler.FieldList").Connect = False End Sub
-39790078 0 so try sticking applicationId to your modules gradle, at defaultConfig like
defaultConfig { applicationId "com.example.myapp" minSdkVersion 17 targetSdkVersion 24 versionCode 1 versionName "1.0" }
-33940429 0 In order to define an ArrayList with CheckBoxes please refer to following example:
List<JCheckBox> chkBoxes = new ArrayList<JCheckBox>(); Add your JCheckBox elements to the ArrayList using standard approach, for example:
JCheckBox chkBox1 = new JCheckBox(); chkBoxes.add(chkBox1); Interatve over the list and carry out check if selected using JCheckBox method #.isSelected() as follows:
for(JCheckBox chkBox : chkBoxes){ chkBox.isSelected(); // do something with this! }
-14017260 0 I'm going to be lazy here and take @H2CO3's answer to be working without trying it.
<script type="text/javascript"> function generate(var UNWANTED) { var r; do { r = Math.floor(Math.random() * 10); } while (r == UNWANTED); return r; } function GENERATE_RANDOM_FROM_0_TO_10_BUT_NOT_6_OR_SOMETHING_ELSE_(var NOT_GOOD){ return generate(NOT_GOOD) <== One line solution. } <script>
-34592745 0 How to customize angular-material grid system? It's possible customize the angular-material grid system like bootstrap, by setting columns, gutter-width, etc? http://getbootstrap.com/customize/
The angular-material.scss has some mixins like "flex-properties-for-name", but always will create 20 columns with increments of 5%.
I could override some mixins, but I was looking for other ways to do this.
Update:
My first solution was reuse some mixins from the angular-material.scss to create a custom grid. https://gist.github.com/dilvane/a5418f3f3c5d68cf1059
Does anyone have a different approach?
Update:
Issue reported: https://github.com/angular/material/issues/6537
-14057484 0You can use 2 comprehensions to naturally loop over the data structures.
dict((drug, [file for file in file_list if drug in file]) for drug in drug_list) Let's break this down. We'll need to create a dictionary, so let's use a list comprehension for that.
dict((a, str(a + " is the value")) for a in [1, 2, 3]) The outermost part is a list comprehension that creates a dict. By creating 2-tuples of the form (key, value) we can then simply call dict() on it to get a dictionary. In our answer, we set the drug as the key and we set the value to a list that is built from another list comprehension. So far we have:
{'17A': [SOMETHING], '56B': [SOMETHING], '96A': [SOMETHING]} Now we need to fill in the SOMETHINGs and this is what the inner comprehension does. It looks like your logic is to check if the drug text appears in the file. We already have the drug, so we can just say:
[file for file in file_list if drug in file] This runs through the file list and adds it if the drug appears therein.
In Python 2.7 and above, you can use a dictionary comprehension instead of using dict(). In that case it would look like:
{drug: [file for file in file_list if drug in file] for drug in drug_list} This is much clearer since all the boiler plate of making 2-tuples and converting can be done away with.
Comprehensions are an excellent way of writing code because the tend to be very clear descriptions of what you mean to do. It's worth noting that this is not the most efficient way of building the dictionary though, since it runs through every file for every drug. If the list of files is very long this could be very slow.
Edit: My first answer was nonsense. As penance, I have made this detailed one.
-8459164 0The bottom line is, from the client side, you will not be able to load the source of an external domain. You could do it through a server side httpclient call, but NOT from the client side.
-31194354 0 How does the roTextureManager image cache behave?Does the roTextureManager clear or replace bitmaps in its cache automatically when it sees that it is running out of memory? I cannot seem to find any good answer to this.
-8414219 0Q: How can I have DNS name resolving running while other protocols seem to be down?
A: Your local DNS resolver (bind is another possibility besides ncsd) might be caching the first response. dig will tell you where you are getting the response from:
[mpenning@Bucksnort ~]$ dig cisco.com ; <<>> DiG 9.6-ESV-R4 <<>> +all cisco.com ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 22106 ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 2, ADDITIONAL: 0 ;; QUESTION SECTION: ;cisco.com. IN A ;; ANSWER SECTION: cisco.com. 86367 IN A 198.133.219.25 ;; AUTHORITY SECTION: cisco.com. 86367 IN NS ns2.cisco.com. cisco.com. 86367 IN NS ns1.cisco.com. ;; Query time: 1 msec <----------------------- 1msec is usually cached ;; SERVER: 127.0.0.1#53(127.0.0.1) <--------------- Answered by localhost ;; WHEN: Wed Dec 7 04:41:21 2011 ;; MSG SIZE rcvd: 79 [mpenning@Bucksnort ~]$ If you are getting a very quick (low milliseconds) answer from 127.0.0.1, then it's very likely that you're getting a locally cached answer from a prior query of the same DNS name (and it's quite common for people to use caching DNS resolvers on a ppp connection to reduce connection time, as well as achieving a small load reduction on the ppp link).
If you suspect a cached answer, do a dig on some other DNS name to see whether it can resolve too.
ppp connection going down.If you find yourself in either of the last situations I described, you need to do some IP and ppp-level debugs before this can be isolated further. As someone mentioned, tcpdump is quite valuable at this point, but it sounds like you don't have it available.
I assume you are not making a TCP connection to the same IP address of your DNS server. There are many possibilities at this point... If you can still resolve random DNS names, but TCP connections are failing, it is possible that the problem you are seeing is on the other side of the ppp connection, that the kernel routing cache (which holds a little TCP state information like MSS) is getting messed up, you have too much packet loss for tcp, or any number of things.
Let's assume your topology is like this:
10.1.1.2/30 10.1.1.1/30 [ppp0] [pppX] uCLinux----------------------AccessServer---->[To the reset of the network] When you initiate your ppp connection, take note of your IP address and the address of your default gateway:
ip link show ppp0 # display the link status of your ppp0 intf (is it up?) ip addr show ppp0 # display the IP address of your ppp0 interface ip route show # display your routing table route -Cevn # display the kernel's routing cache Similar results can be found if you don't have the iproute2 package as part of your distro (iproute2 provides the ip utility):
ifconfig ppp0 # display link status and addresses on ppp0 netstat -rn # display routing table route -Cevn # display kernel routing table For those with the iproute2 utilities (which is almost everybody these days), ifconfig has been deprecated and replaced by the ip commands; however, if you have an older 2.2 or 2.4-based system you may still need to use ifconfig.
Troubleshooting steps:
When you start having the problem, first check whether you can ping the address of pppX on your access server.
pppX on the other side, then it is highly unlikely your DNS is getting resolved by anything other than a cached response on your uCLinux machine.pppX, then try to ping the ip address of your TCP peer and the IP address of the DNS (if it is not on localhost). Unless there is a firewall involved, you must be able to ping it successfully for any of this to work.If you can ping the ip address of pppX but you cannot ping your TCP peer's ip address, check your routing table to see whether your default route is still pointing out ppp0
If your default route points through ppp0, check whether you can still ping the ip address of the default route.
If you can ping your default route and you can ping the remote host that you're trying to connect to, check the kernel's routing cache for the IP address of the remote TCP host.... look for anything odd or suspicious
If you can ping the remote TCP host (and you need to do about 200 pings to be sure... tcp is sensitive to significant packet loss & GPRS is notoriously lossy), try making a successful telnet <remote_host> <remote_port>. If both are successful, then it's time to start looking inside your software for clues.
If you still can't untangle what is happening, please include the output of the aforementioned commands when you come back... as well as how you're starting the ppp connection.
I want to ad a title "Instant Independent" to the center "featured" section of my wordpress blog. Directly above where the "fee increase coming soon for lake mohave" story. http://www2.az-independent.com/
How do I do this?
-13492238 0You didn't mention what OS are you using... If it's linux you can do it in commandline like that:
find /the/path/to/your/project -name ".class" -exec rm {} \;
-7172537 0 If you accept to recycle the random numbers, why do you want to wait for the exhaustion of the combinations before recycling?
I would just generate random numbers, without caring if they've been used already.
If you really really want to keep it like you asked, here's how you could do it:
You could improve it by moving the used numbers from one table to another, and use the second table instead of the first one when the first table is empty.
You could also do that in memory, if you have enough of it.
-36401668 0 Webpacked Angular2 app TypeError: Cannot read property 'getOptional' of undefinedI've seen a lot of people having this issue, with a solution relating to angular2-polyfills.js. I'm already including this file in my webpack, however:
entry: { 'angular2': [ 'rxjs', 'zone.js', 'reflect-metadata', 'angular2/common', 'angular2/core', 'angular2/router', 'angular2/http', 'angular2/bundles/angular2-polyfills' ], 'app': [ './src/app/bootstrap' ] } Despite this, I get the following errors when trying to load my root component:
Cannot resolve all parameters for 'ResolvedMetadataCache'(?, ?). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'ResolvedMetadataCache' is decorated with Injectable. Uncaught TypeError: Cannot read property 'getOptional' of undefined Both from dom_element_schema_registry:43. What am I doing wrong?
Below is the component file in question.
import {Component} from 'angular2/core'; import {MapComponent} from './map/map.component'; declare var window: any; var $ = require('jquery'); window.$ = $; window.jQuery = $; @Component({ selector: 'app', template: require('./app.component.jade'), styles: [], directives: [MapComponent] }) export class AppComponent {} EDIT This may be to do with my use of jade-loader; when I switch to requiring a raw HTML file, I get a different error:
dom_element_schema_registry.ts:43 Uncaught EXCEPTION: Error during instantiation of Token Promise<ComponentRef>!. ORIGINAL EXCEPTION: RangeError: Maximum call stack size exceeded ORIGINAL STACKTRACE: RangeError: Maximum call stack size exceeded at ZoneDelegate.scheduleTask (http://localhost:3000/angular2.bundle.js:20262:28) at Zone.scheduleMicroTask (http://localhost:3000/angular2.bundle.js:20184:41) at scheduleResolveOrReject (http://localhost:3000/angular2.bundle.js:20480:16) at ZoneAwarePromise.then [as __zone_symbol__then] (http://localhost:3000/angular2.bundle.js:20555:19) at scheduleQueueDrain (http://localhost:3000/angular2.bundle.js:20361:63) at scheduleMicroTask (http://localhost:3000/angular2.bundle.js:20369:11) at ZoneDelegate.scheduleTask (http://localhost:3000/angular2.bundle.js:20253:23) at Zone.scheduleMicroTask (http://localhost:3000/angular2.bundle.js:20184:41) at scheduleResolveOrReject (http://localhost:3000/angular2.bundle.js:20480:16) at ZoneAwarePromise.then [as __zone_symbol__then] (http://localhost:3000/angular2.bundle.js:20555:19)
-39809756 0 Understanding R convolution code with sapply() I am trying to break apart the R code in this post:
x <- c(0.17,0.46,0.62,0.08,0.40,0.76,0.03,0.47,0.53,0.32,0.21,0.85,0.31,0.38,0.69) convolve.binomial <- function(p) { # p is a vector of probabilities of Bernoulli distributions. # The convolution of these distributions is returned as a vector # `z` where z[i] is the probability of i-1, i=1, 2, ..., length(p)+1. n <- length(p) + 1 z <- c(1, rep(0, n-1)) sapply(p, function(q) {z <<- (1 - q) * z + q * (c(0, z[-n])); q}) z } convolve.binomial(x) [1] 5.826141e-05 1.068804e-03 8.233357e-03 3.565983e-02 9.775029e-02 [6] 1.804516e-01 2.323855e-01 2.127628e-01 1.394564e-01 6.519699e-02 [11] 2.141555e-02 4.799630e-03 6.979119e-04 6.038947e-05 2.647052e-06 [16] 4.091095e-08 I tried debugging in RStudio, but it still opaque.
The issue is with the line: sapply(p, function(q) {z <<- (1 - q) * z + q * (c(0, z[-n])); q}).
I guess that within the context of the call convolve.binomial(x) p = q = x. At least I get identical results if I pull the lines outside the function and run sapply(x, function(x) {z <<- (1 - x) * z + x * (c(0, z[-n])); x}) :
x <- c(0.17,0.46,0.62,0.08,0.40,0.76,0.03,0.47,0.53,0.32,0.21,0.85,0.31,0.38,0.69) n <- length(x) + 1 z <- c(1, rep(0, n-1)) # [1] 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 sapply(x, function(x) {z <<- (1 - x) * z + x * (c(0, z[-n])); x}) z # Is extracted by calling it and contains the correct result My questions are:
;q} ending within sapply()?<<- symbol, meant to make z accessible outside of the "implicit" loop that is sapply()?Below you can see my problem "hacking" this line of code:
(x_complem = 1 - x) sapply(x, function(x) {z <<- x_complem * z + x * (c(0, z[-n])); x}) z # Returns 16 values and warnings z_offset = c(0, z[-n]) # [1] 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 sapply(x, function(x) {z <<- (1 - x) * z + x * z_offset; x}) z # Returns different values.
-26963227 0 Your recursive predicate isConnected/2 misses the base case:
isConnected(X,Y) :- graph1(X,Y). (assuming we are checking graph1, of course).
Anyway, you cannot use isConnected/2, since Prolog will loop on cyclic graphs.
-38302398 0I tested above scenario with Postman, and it works properly. Please find steps as follows;
Add proxy and remove message store. (Because adding null message to message store giving following error)
[2016-07-11 13:46:53,291] ERROR - NativeWorkerPool Uncaught exception java.lang.Error: Error: could not match input at org.apache.synapse.commons.staxon.core.json.stream.impl.JsonScanner.zzScanError(JsonScanner.java:530) at org.apache.synapse.commons.staxon.core.json.stream.impl.JsonScanner.yylex(JsonScanner.java:941) at org.apache.synapse.commons.staxon.core.json.stream.impl.JsonScanner.nextSymbol(JsonScanner.java:310) at org.apache.synapse.commons.staxon.core.json.stream.impl.JsonStreamSourceImpl.next(JsonStreamSourceImpl.java:149) at org.apache.synapse.commons.staxon.core.json.stream.impl.JsonStreamSourceImpl.peek(JsonStreamSourceImpl.java:272) at org.apache.synapse.commons.staxon.core.json.JsonXMLStreamReader.consume(JsonXMLStreamReader.java:129) at org.apache.synapse.commons.staxon.core.json.JsonXMLStreamReader.consume(JsonXMLStreamReader.java:132) at org.apache.synapse.commons.staxon.core.base.AbstractXMLStreamReader.hasNext(AbstractXMLStreamReader.java:446) at org.apache.synapse.commons.staxon.core.base.AbstractXMLStreamReader.next(AbstractXMLStreamReader.java:456) at javax.xml.stream.util.StreamReaderDelegate.next(StreamReaderDelegate.java:88) at org.apache.axiom.om.impl.builder.StAXOMBuilder.parserNext(StAXOMBuilder.java:681) at org.apache.axiom.om.impl.builder.StAXOMBuilder.next(StAXOMBuilder.java:214) at org.apache.axiom.om.impl.llom.OMElementImpl.getNextOMSibling(OMElementImpl.java:336) at org.apache.axiom.om.impl.OMNavigator._getFirstChild(OMNavigator.java:199) at org.apache.axiom.om.impl.OMNavigator.updateNextNode(OMNavigator.java:140) at org.apache.axiom.om.impl.OMNavigator.getNext(OMNavigator.java:112) at org.apache.axiom.om.impl.SwitchingWrapper.updateNextNode(SwitchingWrapper.java:1113) at org.apache.axiom.om.impl.SwitchingWrapper.(SwitchingWrapper.java:235) at org.apache.axiom.om.impl.OMStAXWrapper.(OMStAXWrapper.java:74) at org.apache.axiom.om.impl.llom.OMStAXWrapper.(OMStAXWrapper.java:52) at org.apache.axiom.om.impl.llom.OMContainerHelper.getXMLStreamReader(OMContainerHelper.java:51) at org.apache.axiom.om.impl.llom.OMElementImpl.getXMLStreamReader(OMElementImpl.java
Use Postman and invoke proxy service with "POST" command
Add json content in to body
the warnings are caused by the maven tar archiver. By default, it warns for tar entries with path length > 100 chars. Considering this is an ancient tar format limitation, I changed the default to "gnu" for tycho 0.17.0-SNAPSHOT so you should no longer get these warnings:
https://github.com/eclipse/tycho/commit/5db5cc2b76bdba8526cfc4acb66b3e4674f23f03
-23745501 0Java 7 supports the feature of having underscores in the numeric literals to improve the readability of the values being assigned.
but the underscore usage is restricted to be in between two numeric digits, i.e not at the beginning or ending of the numeric values but should be confined between two digits, should not be as a prefix to l,f used to represent long and float values and not in between radix prefixes also.
-39180627 0 Russian text displaying as ??? in my Angular appI have an app which is reading information from an SQL database and displaying in a table. The information in the SQL table is in Russian and has collation utf8_unicode_ci. I am using Angular.
Everything works fine - data is being displayed, however the text is displaying as ????? rather than the Russian text.
How do I fix this error? I have tried googling but cant find anything relevant.
Here is the head element of my index.html:
<html ng-app="crudApp"> <head> <title>Burger King Stock List</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Include Bootstrap CSS --> <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"> <!-- Include main CSS --> <link rel="stylesheet" type="text/css" href="css/style.css"> <!-- Include jQuery library --> <script src="js/jQuery/jquery.min.js"></script> <!-- Include AngularJS library --> <script src="lib/angular/angular.min.js"></script> <!-- Include Bootstrap Javascript --> <script src="js/bootstrap.min.js"></script> </head> I am thinking i needed to have another meta tag?
-32227126 0 CentOs Magento files created as directories?I noticed a few days ago that a few files that belong to a certain Magento extension were in fact created as directories and not in fact the .png .css and .js files that they were supposed to be. When updating the extension there are errors as the files are unable to overwrite the existing directories. I mainly noticed this due to the icons being missing from the Magento admin panel. Although baffling, no big deal, I deleted the directories (x4) and copied the correct files from the original distribution. Problem solved.
I used find . -type d "." and also the 'empty' option to identify directories which should be files. This fixes the symptom but not the cause. There were around 10 files, mostly images but some .js and .css affected.
I've just run an update of M2e via Magento connect, 'successfully', but having noticed some missing icons/graphics in admin I checked the code and have identified 17 empty directories that should have been image files (.png and .gif).
I guess my questions are how and why is this happening? How can I stop it happening again?
I have a dedicated CentOS server running Apache. Installs are done via Filezilla FTP upload or Magento Connect, it seems most likely that it's Connect causing the problem, both extensions have been updated by Connect at least once in their lifetime.
Hoping someone can enlighten me, though not a huge problem in itself, it is a concern that critical files (rather than images) may be prone to the same problems...Anyone seen this before??
Cheers RobH
-29155450 0You need to have a property to bind the selected items to. A multiple <Select> binds to, and post back an array of value types.
public class MyViewModel { public int[] SelectedContacts { get; set; } public List<Contact> AvailableContacts { get; set; } } View
@Html.ListBoxFor(m => m.SelectedContacts, new SelectList(Model.AvailableContacts, "ExternalUserID", "PublicName"), new { @class = "form-control", size = "15" })
-24453451 0 Autoencoders: Papers and Books regarding algorithms for Training Which are some of the famous research papers and/or books which concern Autoencoders and the various different training algorithms for Autoencoders? I'm talking about research papers and/or books which lay the foundation for the different training algorithms used to train autoencoders.
-6208732 0 LINQ to JSON in .net 4.0 Client ProfileHow would I go about about using LINQ to JSON in the .net 4 Client Profile in C#. I'd like to query certain json responses as shown in msdn blog post without having to write out a contract (datacontract, servicecontract, etc). I really only need to query(read) the response, I don't need to modify the json response. (Also would a datacontract be faster than LINQ to JSON?)
Alternatively I could use XML or the full .net 4 framework, but I'm hoping that this can be avoided. I can use external libraries if it's better than installing the whole framework.
-11991093 0glEnable(GL_TEXTURE_2D) (or the openTK equivalent) does not exist in OpenGLES 2.0. It only controls texturing for the fixed pipeline.
To use textures in OpenGLES 2.0, you just sample them in your shader, there's no need to enable anything.
-28068750 0 Unable Redirecting to a New PageI want to redirect to a new page on a button click. Suppose that I have a button in my Default.aspx as:
<asp:Button ID="signup_but" runat="server" Text="SignUp" onClick="Register"></asp:Button> and I want to redirect to a new page when I click this Button my Register Method is in Default.aspx.cs as:
protected void Register(object sender, EventArgs e) { Response.Redirect("~/Registration.aspx"); } The Problem is that when i click this button to redirect to a new page as Registration.aspx it does not redirect my to the page and shows the following URL:
http://localhost:18832/My%20First%20WebSite/Default.aspx?ReturnUrl=%2fMy+First+WebSite%2fRegistration.aspx
-16428811 0 Startup Script with Elastic Beanstalk I'm using Elastic Beanstalk (through Visual Studio) to deploy a .NET environment to EC2. Is there any way to have the equivalent of Azure's startup cmd scripts or powershell scripts? I know that you can pass scripts through User Data when creating EC2 instances, but is that possible in Elastic Beanstalk? If not, how can I create a script that executes one time on instance creation? The main purpose of the script is to download certain resources and to install dependencies before the application starts.
-17254452 0The size of a vector is split into two main parts, the size of the container implementation itself, and the size of all of the elements stored within it.
To get the size of the container implementation you can do what you currently are:
sizeof(std::vector<int>); To get the size of all the elements stored within it, you can do:
MyVector.size() * sizeof(int) Then just add them together to get the total size.
-37442883 0It looks like you set it up correctly. I would try invalidating the caches and restarting. I've had a similar problem to this before and that did it.
Go to "File" -> "Invalidate Caches/Restart" and choose "Invalidate and Restart".
A primary key in database design should be seen as a unique identifier of the info being represented. By removing an ID from a table you are essentially saying that this record shall be no more. If something was to take its place you are saying that the record was brought back to life. Now technically when you removed it in the first place you should have removed all foreign key references as well. One may be tempted at this point to say well since all traces are gone than there is no reason something shouldn't take it's place. Well, what about backups? Lets say you removed the record by accident, and it ended up replaced by something else, you would not be able to easily restore that record. This could also potentially cause problems with rollbacks. So not only is reusing ID's not necessary but fundamentally wrong in the theory of database design.
-13786647 0As @PinkElephantsOnParade writes, it makes no difference for the execution. Thus, it's solely a matter of personal aesthetical preference.
I myself set my editor to display trailing whitespace, since I think trailing whitespace is a bad idea. Thus, your line 10 would be highlighted and stare me in the face all the time. Nobody wants that, so I'd argue line 10 should not contain whitespace. (Which, coincidentally is how my editor, emacs, handles this automatically.)
-30244323 0 PHP - Cast type from variableI was asking myself if it's possible to cast a string to become another type defined before
e.g.
$type = "int"; $foo = "5"; $bar = ($type) $foo; and where $bar === 5
-319672 0 GetWindowLong vs GetWindowLongPtr in C#I was using GetWindowLong like this:
[DllImport("user32.dll")] private static extern IntPtr GetWindowLong(IntPtr hWnd, int nIndex); But according to the MSDN docs I am supposed to be using GetWindowLongPtr to be 64bit compatible. http://msdn.microsoft.com/en-us/library/ms633584(VS.85).aspx
The MSDN docs for GetWindowLongPtr say that I should define it like this (in C++):
LONG_PTR GetWindowLongPtr(HWND hWnd, int nIndex); I used to be using IntPtr as the return type, but what the heck would I use for an equivalent for LONG_PTR? I have also seen GetWindowLong defined as this in C#:
[DllImport("user32.dll")] private static extern long GetWindowLong(IntPtr hWnd, int nIndex); What is right, and how can I ensure proper 64bit compatibility?
-29012370 0The error is being returned because the conditions being evaluated are not short-circuiting - the condition PostalCode<7000 is being evaluated even where the postal code is non-numeric.
Instead, try:
SELECT * from Person.Address WHERE CASE WHEN PostalCode NOT LIKE '%[^0-9]%' THEN CAST(PostalCode AS NUMERIC) ELSE CAST(NULL AS NUMERIC) END <7000 (Updated following comments)
-28464752 0 not entering the condition if(intent.resolve(getPackageManager()){} neither else{}Hey I want my app to locate someone on a map so I made an intent but it's not working and I've no error so I'm a bit lost. I think I've no app that can perform a map location on my emulator but even then I should have that said in my logs. Here is the code:
private void openLocationInMap(){ Log.d("map","in fct"); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); final String BASE_URL ="geo:0,0?q="; Log.d("map","1"); String locationData = sharedPreferences.getString(getString(R.string.pref_location_key), getString(R.string.pref_location_default)); Log.d("map","2"); Uri uriGeolocalisation = Uri.parse(BASE_URL).buildUpon() .appendQueryParameter("q", locationData).build(); Log.d("map","3"); Intent intent = new Intent (Intent.ACTION_VIEW); intent.setData(uriGeolocalisation); Log.d("map","4"); if(intent.resolveActivity(getPackageManager()) != null) { Log.d("map", "in if"); startActivity(intent); }else{ Log.d("map", "couldn't open intent"); } Log.d("map","5"); } And in my log debug I get :
in fct, 1,2,3,4.
Edit: if that can help it works on my phone but still not working on the emulator. I'm guessing it's because I don't have google map on my emulator but still I should see something in the logs which I don't.
-41028172 0 A simple if statement seems to mess one functionI´m trying to hide and show some of the input fields in a form with jQuery. But it seems as the first if statement in the is messing things up. If I comment the if statement, everything works like a charm (except to check the default radio button if old input is missing).
The line {{ old('type_of_content') }} is from the Laravel Framework to retrieve old form input data if the validation fails.
$(document).ready(function(){ // Set the checked radiobutton var radio_checked = '{{ old('type_of_content') }}'; if (radio_checked) { // check if variable is empty or not $('input:radio[id='+radio_checked+']').attr('checked', true); }else{ $('input:radio[id=is_question]').attr('checked', true); } $.fn.showQuestion = function(){ $("#remove_questions_choices").show(); $("#remove_questions_box").show(); $("#data").show(); // Fråga $("#information_body").hide(); $("#is_information").attr("checked", false) $("#is_question").attr("checked", true) alert('Question is selected') } $.fn.showInformation = function(){ $("#remove_questions_choices").hide(); $("#remove_questions_box").hide(); $("#data").hide(); $("#information_body").show(); $("#is_question").attr("checked", false) $("#is_information").attr("checked", true) alert('Information is selected') } // If radio button is changed by user click $('input:radio[name=type_of_content]').change(function () { if ($("#is_question:checked").val()) { $.fn.showQuestion(); } if ($("#is_information:checked").val()) { $.fn.showInformation(); } }); // When a radio button is selected on page load (working) $('#is_question:checked').val(function(){ $.fn.showQuestion(); }); $('#is_information:checked').val(function(){ $.fn.showInformation(); }); }); The expected result should be to check if old input data exist, and check the corresponding radio button if so. Else, check the "default" radio button. No errors is reported in the chrome dev tools.
But what is happening is that i cannot "reselect" the #is_question, the showQuestion(). But showInformation() seems to be working.
Using jQuery 3.1.0
Made a fiddle: https://jsfiddle.net/zs85p7nx/
-26437889 0Ok, I downloaded your zip and ran the program. Your problem isn't in the matrix multiplication at all. The advice in the comments is still valid about reducing the number of threads, however as it stands the multiplication happens very quickly.
The actual problem is in your writeToAFile method - all the single-threaded CPU utilization you are seeing is actually happening in there, after the multiplication is already complete.
The way you're appending your strings:
fileOutputString = fileOutputString + resultMatrix[i][j] creates thousands of new String objects which then immediately become garbage; this is very inefficient. You should be using a StringBuilder instead, something like this:
StringBuilder sb=new StringBuilder(); for (int i = 0; i < resultMatrix.length; i++) { for (int j = 0; j < resultMatrix[i].length; j++) { sb.append(resultMatrix[i][j]); if (j != resultMatrix[i].length - 1) sb.append(","); } sb.append("\n"); } String fileOutputString=sb.toString(); That code executes in a fraction of a second.
-34308809 0It seems that the behavior of NSBundle preferredLocalizationsFromArray changed from iOS 8.4 to 9.0.
Example: I have selected "Austria" as region, and "German" as language.
For "de_AT", NSBundle pathForResource cannot find the "de" localization, and returns nil.
Fixed with this (ideally unnecessary) workaround:
NSArray* availableLocalizations = [[NSBundle mainBundle] localizations]; NSArray* userPreferred = [NSBundle preferredLocalizationsFromArray:availableLocalizations forPreferences:[NSLocale preferredLanguages]]; NSString *indexPath; for (NSString *locale in userPreferred) { indexPath = [[NSBundle mainBundle] pathForResource:@"hilfe" ofType:@"html" inDirectory:nil forLocalization:locale]; if (indexPath) break; }
-22847456 0 You can temporarily disable ScreenUpdating
Sub SilentRunning() Application.ScreenUpdating = False ' ' do your thing ' Application.ScreenUpdating = True End Sub
-4759726 0 .NET - Multiple libraries with the same namespace - referencing Today I am faced with a curious challenge...
This challenge involves two .NET libraries that I need to reference from my application. Both of which I have no control over and have the same namespace within them.
So...
I have foo.dll that contains a Widget class that is located on the Blue.Red.Orange namespace.
I have bar.dll that also contains a Widget class that is also located on the Blue.Red.Orange namespace.
Finally I have my application that needs to reference both foo.dll and bar.dll. This is needed as within my application I need to use the Widget class from foo and also the Widget class from bar
So, the question is how can I manage these references so that I can be certain I am using the correct Widget class?
As mentioned, I have no control over the foo or bar libraries, they are what they are and cannot be changed. I do however have full control over my application.
The simplest way in a nutshell:
https://jsfiddle.net/svArtist/2jd9uvx0/
hide lists inside other lists
upon hovering list elements, show the child lists
ul ul { display:none; display:absolute; bottom:-100%; } li{ position:relative; } li:hover>ul { display:table; } <ul> <li><a href="#">The Salon</a> <ul> <li><a href="#">Hair Cut</a> </li> </ul> </li> </ul> I have a problem with my attempt to show data in JSON UITableViewDataSource The data from JSON are:
[ "Jon", "Bill", "Kristan" ] JSON itself has gone through the validator. The error I have is TableViews [2050: f803] Illegal start of token [h]
Here is my code
NSString *myRawJson = [NSString stringWithFormat:@"http://site.com/json.php"]; if ([myRawJson length] == 0){ return; } NSError *error = nil; SBJsonParser *parser = [[SBJsonParser alloc] init]; tableData =[[parser objectWithString:myRawJson error:&error] copy]; NSLog(@"%@", [error localizedDescription]); list = [[NSArray alloc] initWithObjects:@"Johan", @"Polo", @"Randi", @"Tomy", nil]; [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib.
-12851914 0 No. Once a blob is created/uploaded you can't change the blob type. Unfortunately you would need to recreate/re-upload the blob. However I'm somewhat surprised. You mentioned that you copied the blob from one storage account to another. Copy Blob operation within Windows Azure (i.e. from one storage account to another) preserves the source blob type. It may seem a bug in CloudBerry explorer. I wrote a blog post some days ago about moving virtual machines from one subscription to another (http://gauravmantri.com/2012/07/04/how-to-move-windows-azure-virtual-machines-from-one-subscription-to-another/) and it has some sample code and other useful information for copying blobs across storage account. You may want to take a look at that. HTH.
-36068325 0You should use your frames converted to single channel, i.e. of type CV_8UC1:
disparity = stereo.compute(frame0_new, frame1_new)
-19261554 0 You need to move the delete query parameter up in your Url. I suspect that it is getting lost after the query parameter. Try the following:
http://localhost:8983/solr/update?commit=true&stream.body=<delete><query>id:APP 5.6.2*</query></delete>
-21123593 0 How to get the value of a static object from within that object? I’m trying to create a extern pointer to the value of a static object from within that static object. We’ll call this object Foo.
Thus far, the only way I’ve gotten this to work is to create a Supervisor class that Foo inherits from that contains two static type variables. One, called superObject is the actual initialized object. The other, called superPointer, is a double pointer of the same type. Inside of the Foo object I declare an extern pointer named TheSupervisor and assign it a nullptr. Then, from within the Supervisor base class, I use the double pointer superPointer to change the value of TheSupervisor extern pointer to the address of the superObject. Wallah.
The goal is here to create a globally accessible reference to this object. Trying my best to avoid singletons and keep things thread safe. I’m just wondering if there’s a better way?
I'd post code, but I'd really have to clean it and change it around. I think the description is sufficient. Maybe even simpler, actually.
EDIT: As it turns out, for static objects, I can't rely on when and in what order they are constructed. Using a one-phase process won't work for this. Instead, I have to keep relying on a two-phase process such as the one I outlined above. Marking Ilya Kobelevskiy's answer as correct as it demonstrates one way to do it, but again, it should come with a warning when used with static objects.
-22036801 0please refer this link i hope this is very help full for your requirements.click here
-20489905 0whenever you specify the namespace it means that the controller will search for the required resources in that particular namespace. So what i think is that you may not have some jsps that you are using in that particular "admin" namespace. So try moving all those resources into that folder. tell me if your code still not working
-29042866 0If you can use conio.h then you can do that by reading input in a character array with getch() function. Or if you are in visual studio you can use _getch() function for the same result.
conio.h defines function named getch() and getche() which reads a character then terminates without any enter key. Both these functions have specific meanings while they do the same task. I don't use those any more so I don't remember much. It's upto you if you wanna use them or not...
-10629435 0 Backbone.js rendering a reset collection with a single viewI'm trying to render a filtered collection from a single view using a select box using the reset property. First issue is that the select box and the rendered content must all appear in the same div in order to work. Is this normal? Second issue, is that instead showing the filtered results only, it appends the filtered collection to the end of the rendered content instead of replacing it.I know append in my ._each function won't work because it will only append the filtered items to the end of the entire collection. Here's my code sample below:
(function($) { var images = [ { tags: "Fun", date : "April 3, 2012", location : 'Home', caption : 'Having fun with my lady'}, { tags: "Chillin", date : "April 4, 2012", location : 'Home', caption : 'At the park with my lady'}, { tags: "Professional", date : "April 5, 2012", location : 'Home', caption : 'At the crib with my lady'}, { tags: "Education", date : "April 6, 2012", location : 'Home', caption : 'Having fun with my baby'}, { tags: "Home", date : "April 3, 2012", location : 'Home', caption : 'Having fun with my lady'}, { tags: "Professional", date : "April 4, 2012", location : 'Home', caption : 'At the park with my lady'}, { tags: "Fun", date : "April 5, 2012", location : 'Home', caption : 'At the crib with my lady'}, { tags: "Chillin", date : "April 6, 2012", location : 'Home', caption : 'Having fun with my baby'}, { tags: "Fun", date : "April 3, 2012", location : 'Home', caption : 'Having fun with my lady'}, { tags: "Education", date : "April 4, 2012", location : 'Home', caption : 'At the park with my lady'}, { tags: "Personal", date : "April 5, 2012", location : 'Home', caption : 'At the crib with my lady'}, { tags: "Personal", date : "April 6, 2012", location : 'Home', caption : 'Having a play date'} ]; var Item = Backbone.Model.extend({ defaults : { photo : 'http://placehold.it/200x250' } }); var Album = Backbone.Collection.extend({ model : Item }); var ItemView = Backbone.View.extend({ el : $('.content'), initialize : function() { this.collection = new Album(images); this.render(); $('#filter').append(this.createSelect()); this.on("change:filterType", this.filterByType); this.collection.on('reset', this.render, this); }, template : $('#img_container').text(), render : function() { var tmpl = _.template(this.template); _.each(this.collection.models, function (item) { this.$el.append(tmpl(item.toJSON())); },this); }, events: { "change #filter select" : "setFilter" }, getTypes: function () { return _.uniq(this.collection.pluck("tags"), false, function (tags) { return tags.toLowerCase(); }); }, createSelect: function () { var filter = this.$el.find("#filter"), select = $("<select/>", { html: "<option>All</option>" }); _.each(this.getTypes(), function (item) { var option = $("<option/>", { value: item.toLowerCase(), text: item.toLowerCase() }).appendTo(select); }); return select; }, setFilter: function (e) { this.filterType = e.currentTarget.value; this.trigger("change:filterType"); }, filterByType: function () { if (this.filterType === "all") { this.collection.reset(images); } else { this.collection.reset(images, { silent: true }); var filterType = this.filterType, filtered = _.filter(this.collection.models, function (item) { return item.get("tags").toLowerCase() === filterType; }); this.collection.reset(filtered); } } }); var i = new ItemView(); })(jQuery);
-19871021 0 What is event.preventDefault preventing despite the event? One goal of my main controller is to prevent users from going to urls of other users. That works perfectly fine with listening on $locationChangeStart and using its events preventDefault method. Unfortunately calling this method has the strange side effect of somehow "interrupting" the work of the function "handleNotification" which has the goal of notifying the user for 2 seconds that she or he has done something illegitimate. If I comment out event.preventDefault(), everything works as expected. So my question is: What is the 'scope' of the 'default' preventDefault prevents that I don't have on my mind and which keeps the handleNotification function from working properly?
$scope.$on('$locationChangeStart', function(event, newUrl, oldUrl) { ifUserIs('loggedIn', function() { if (newUrl.split('#/users/')[1] !== $scope.user.userId) { handleNotification('alert', 'You are not allowed to go here.'); event.preventDefault(); } }); }); function handleNotification (type, message) { $scope.notice = { content: message, type: type }; $timeout(function() { delete $scope.notice; return true; }, 2000); }
-18818456 0 center site content on all devices This is the site I am referring to: http://heattreatforum.flyten.net/
It was built as a child-site to the twenty-twelve theme.
I can't seem to get the content to center on every screen, and I am seeing a strange wide margin on the right that I just can't seem to locate in my css.
Any help would be much appreciated - thanks for looking!
-35335359 0Check the updated fiddle here: http://jsfiddle.net/yrzxj3x2/3/
You have to tell the x axis to be of type 'timeseries' and defining the format doesn't hurt. This is the bit that enabled timeseries on your chart:
axis: { x: { type: 'timeseries', tick: { format: '%Y-%m-%d' } } } See reference on here: http://c3js.org/samples/timeseries.html
-24732604 0 function addBox() { var rect = new fabric.Rect({ width: 1000, height: 600, top: 300, left: 500, fill: ' ', draggable: false }); rect.lockMovementX = true; rect.lockMovementY = true; rect.lockUniScaling = true; rect.lockRotation = true; canvas.add(rect); } make your fill null and if you want to have a border use strokeWidth: 3, stroke: "color"
-10216635 0 Assuming that identifyArrayCollection is an ArrayCollection containing some Objects and speedsArrayCollection is an ArrayCollection defined as variable of the Object type that are contained in the identifyArrayCollection
you should do:
for (var x:Number = 0; x < identifyArrayCollection.length; x++) { identifyArrayCollection.getItemAt(x).speedsArrayCollection.addItem(speedsObj); }
-40814370 0 You need to persisting the song data to the device.
The Android framework offers several options and strategies for persistence:
Use Cases
Each storage option has typically associated use cases as follows:
Read more: Persisting Data To Device.
You can use one of the options, but for your purpose, SQLite Database or ORM is the better options.
You can visit Local Databases with SQLiteOpenHelper for SQLite Database.
For ORM, you can try greenDAO.
-14773407 0 What does this piece of Perl code do in laymans terms?Found this inside a loop. I've read up about splice but it just confused me more. I'm not familiar with Perl, but am trying to translate an algorithm to another language.
my $sill = splice(@list,int(rand(@list)),1); last unless ($sill); To be more specific: What will be inside $sill if it doesn't exit the loop from the last?
Thanks for any help!
-8750828 0 drupal 6: using ahah for forms with markup typesfunction MyModule_menu() { $items['blah'] = array( 'title' = 'blah', 'page callback' => 'blah_page', 'type' => MENU_NORMAL_ITEM ); $items['clickPath'] = array( 'title' => 'A title', 'page callback' => 'clickPath_page', 'type' => MENU_CALLBACK, ); return $items; } function blah_page() { $output = drupal_get_form(MyModule_form); return $output; } function clickPath_page() { return ('you clicked me!'); } function MyModule_form($form,&$form_state) { $output = '<div id="clickDiv">Click me</div>'; $form['blah'] = array( '#type' => 'markup', '#value' => $output, '#ahah' => array( 'event' => 'click', 'path' => 'clickPath', 'wrapper' => 'clickDiv', ), ); return $form; } Why won't the above work? Is it not possible to use ahah and events on form types of 'markup'? Do I have to use my own custom javascript?
You can stop reading here! I would like to end my sentences and question here, but stackoverflow is forcing me to input a minimum amount of characters. Apologies in advance!!!!
-7704031 0 jquery sliding menu opening/closing animations issueI'm testing this on local : http://jsfiddle.net/fYkMk/1/ This is a booking form that opens up on mouse over (booking-mask) and closes when mouse leaves it. It has 4 fields :
the last three fields are sliding menus that open up with a click on the relative icon.
These sliding animations work until The user decide to "mouseover" then "mouseleave" and "mouseover" again over the booking-mask div before the oprning/closing animations are finished yet.
So it happens the lists are broken and I can only see a piece of them.[see image below]

Hope you can help me out with this. Thanks
Luca
-21505513 0Try this
class Item extends Eloquent { public function owner() { return $this->belongsTo('User','ownerID'); } }
-17278865 0 Connection to a web service in Android Virtual Device I have a web service with a WS-security. I can have access to this web service only with my machine IP address and only if I make the right WS configuration.
So when testing it in Soap-ui, I get responses! and when testing connection in browser of my emulator, I get the wsdl page!
But when implemented in my application, I can not call the web service! I'm making something really wrong and didn't get it!
Is the URL I'm using for calling my web service right? Have I to configure the DNS server in the emulator? What have I to do ?
Here is my SOAP request:
POST http://172.xxx.xxx.xxx:8080/wbb HTTP/1.1 Accept-Encoding: gzip,deflate Content-Type: text/xml;charset=UTF-8 SOAPAction: "" Content-Length: 1146 Host: 172.xxx.xxx.xxx:8080 Connection: Keep-Alive User-Agent: Apache-HttpClient/4.1.1 (java 1.5) <soapenv:Envelope xmlns:ser="http://www.''''.com/wbb/service" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> <soapenv:Header><wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"> <wsse:UsernameToken wsu:Id="UsernameToken-11"> <wsse:Username>whatever2</wsse:Username> <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">whatever3</wsse:Password> <wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">whatever4</wsse:Nonce> <wsu:Created>whatever5</wsu:Created> </wsse:UsernameToken></wsse:Security></soapenv:Header> <soapenv:Body> <ser:RechargeRequest> <ser:value1>?</ser:value1> <ser:value2>?</ser:value2> <!--Optional:--> <ser:value3>?</ser:value3> </ser:RechargeRequest>
and my android code:
protected String doInBackground(String... params) { private static final String SOAP_ACTION = ""; private static final String NAMESPACE"http://www.'''''.com/wbb/ws"; private static final String METHOD_NAME="Recharge"; private static final String URL = "http://172.xxx.xxx.xxx:8080/wbb/wbb.wsdl"; SoapPrimitive response = null; String xml=""; SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); PropertyInfo p1 =new PropertyInfo(); p1.name = "value1"; p1.setValue(params[0]); request.addProperty(p1); PropertyInfo p2 =new PropertyInfo(); p2.name = "value2"; p2.setValue(params[1]); request.addProperty(p2); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12); // create header Element[] header = new Element[1]; header[0] = new Element().createElement("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd","Security"); Element usernametoken = new Element().createElement("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "UsernameToken"); usernametoken.setAttribute(null, "Id", "UsernameToken-1"); header[0].addChild(Node.ELEMENT,usernametoken); Element username = new Element().createElement(null, "n0:Username"); username.addChild(Node.IGNORABLE_WHITESPACE,"whatever2"); usernametoken.addChild(Node.ELEMENT,username); Element pass = new Element().createElement(null,"n0:Password"); pass.setAttribute(null, "Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText"); pass.addChild(Node.TEXT, "whatever3"); usernametoken.addChild(Node.ELEMENT, pass); Element nonce = new Element().createElement(null, "n0:Nonce"); nonce.setAttribute(null, "EncodingType","http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary"); nonce.addChild(Node.TEXT, "whatever3"); usernametoken.addChild(Node.ELEMENT, nonce); Element created = new Element().createElement(null, "n0:Created"); created.addChild(Node.TEXT, "whatever4"); usernametoken.addChild(Node.ELEMENT, created); // add header to envelope envelope.headerOut = header; Log.i("header", "" + envelope.headerOut.toString()); envelope.dotNet = false; envelope.bodyOut = request; envelope.setOutputSoapObject(request); //HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); URL url = null; try { url = new URL(URL); } catch (MalformedURLException e1) { e1.printStackTrace(); } HttpTransportSE androidHttpTransport = null; String host = url.getHost(); int port = url.getPort(); String file = url.getPath(); Log.d("Exception d", "host -> " + host); Log.d("Exception d", "port -> " + port); Log.d("Exception d", "file -> " + file); androidHttpTransport = new KeepAliveHttpsTransportSE(host, port, file, 25000); Log.i("bodyout", "" + envelope.bodyOut.toString()); try { androidHttpTransport.debug = true; androidHttpTransport.call(SOAP_ACTION, envelope); xml = androidHttpTransport.responseDump; response = (SoapPrimitive)envelope.getResponse(); Log.i("myApp", response.toString()); } catch (SoapFault e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); Log.d("Exception Generated", ""+e.getMessage()); } return response; } Sorry for my bad english and for the mistakes!
-16911323 0Here I'm only matching the numbers and period character. This code should return the numbers you're looking for. It uses your data string from your example.
<? preg_match_all('!Gold\s+([0-9.]+)\s+([0-9.]+)!i',$data,$matches); //New York $ny_bid = $matches[1][0]; $ny_ask = $matches[2][0]; print("NY\nbid: $ny_bid\n"); print("ask: $ny_ask\n\n"); //Asia $asia_bid = $matches[1][1]; $asia_ask = $matches[2][1]; print("Asia\nbid: $asia_bid\n"); print("ask: $asia_ask\n"); ?> Output
NY bid: 1411.20 ask: 1412.20 Asia bid: 1406.80 ask: 1407.80
-29308309 0 There must be a nicer solution, but this is the one that quickly popped into mind:
set source = range(Rows(1).address & "," & Rows(emptyrow).address).SpecialCells(xlCellTypeVisible) Disgusting, but works (if I understood what you needed correctly).
Edit: found another solution:
set source = Application.Union(rows(1),rows(emptyrow)).SpecialCells(xlCellTypeVisible)
-37710071 0 Could someone tell me why this code isn't working? So I have been stuck with this for a long time now, unable to figure why it isn't working. This is a registration page which, after submitting information, should upload the information (the one I choose, not all the registration options enter the database) into a table (called tbl) inside the database (known as Database2.mdf). This is through Visual Studio 2010. There is also a java phase that checks the information but I don't think that is what is causing the problem so I'll just post the SQL code and the HTML code, along with the names of the table lines.
The SQL bit:
<%@ Page Language="C#" %> <%@ Import Namespace="System.Data.SqlClient" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> protected void Page_Load(object sender, EventArgs e) { if (Request.Form["sub"] != null) { string fName = Request.Form["FName"]; string lName = Request.Form["LName"]; string uName = Request.Form["UName"]; string Street = Request.Form["Street"]; string City = Request.Form["City"]; string Pass = Request.Form["Password"]; string PassCon = Request.Form["PasswordConf"]; string Email = Request.Form["Email"]; string Comments = Request.Form["Comment"]; int ID = int.Parse(Request.Form["ID"]); string conStr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database2.mdf;Integrated Security=True;User Instance=True"; string cmdStr = string.Format("INSERT INTO tbl (FirstName, LastName, UserName, Street, City, Password, PasswordConfirm, Email, Comments, IdentificationNumber) VALUES (N'{0}', N'{1}', N'{2}', N'{3}', N'{4}', N'{5}', N'{6}', N'{7}', N'{8}', {9})", fName, lName, uName, Street, City, Pass, PassCon, Email, Comments, ID); SqlConnection conObj = new SqlConnection(conStr); SqlCommand cmdObj = new SqlCommand(cmdStr, conObj); conObj.Open(); cmdObj.ExecuteNonQuery(); conObj.Close(); } } </script> The HTML bit: (CheckForm is the name of the Javassript action that checks if the form matches the requirements, also Registration.aspx is the registration page obviously, and it is not linked to a master page)
<form action="Registration.aspx" method="post" name="ContactForm" onsubmit="return CheckForm()"> First Name: <input type="text" size="65" name="FName" /> <br /> Last Name: <input type="text" size="65" name="LName" /> <br /> Username: <input type="text" size="65" name="UName" /> <br /> Street: <input type="text" size="65" name="Street" /> <br /> City: <input type="text" size="65" name="City" /> <br /> Password: <input type="password" size="65" name="Password" /> <br /> Password Confimration: <input type="password" size="65" name="PasswordConf" /> <br /> E-mail Address: <input type="text" size="65" name="Email" /> <br /> Comments: <input type="text" size="100" name="Comment" /> <br /> Identification Number: <input type="password" size="65" name="ID" /> <br /> Mobile : <input type="text" id="mobile" name="mobile" style="width: 40px;" maxlength="3" /> - <input type="text" name="mobile1" maxlength="7" /> <br /> Gender: Male<input type="radio" name="gender" id="gender_Male" value="Male" checked /> Female<input type="radio" name="gender" id="gender_Female" value="Female" /> <br /> Which countries would you like to recieve political news for?: <br /> <input type='checkbox' name='files[]' id='1' value='1' /> Israel <input type='checkbox' name='files[]' id='2' value='2' /> Russia <input type='checkbox' name='files[]' id='3' value='3' /> Canada <br /> How often do you read the newspaper? <br /> <select id="cardtype" name="sel"> <option value=""></option> <option value="1">Never</option> <option value="2">Everyday</option> <option value="3">Once a week</option> <option value="4">Once a year</option> </select> <br /> What can we help you with? <select type="text" value="" name="Subject"> <option></option> <option>Customer Service</option> <option>Question</option> <option>Comment</option> <option>Consultation</option> <option>Other</option> </select> <br /> <input type="submit" value="Send" name="submit" /> <input type="reset" value="Reset" name="reset" /> </form> The table lines are as follows:
I know this is A LOT to sift through but I have been stuck with it for so long and I must get it fixed very quickly, I would VERY much appreciate any help provided! Thanks in advance!
-11476031 0There must be a problem with your version/install.
Graphviz 2.28 on a windows system produces this output (11605x635px !):

Try dot -version to see version number and information about installed plugins & config file.
I'm doing a lucene search using PARENT. But returns me 0 results, and it's not ok. My query is like this:
TYPE:"{mymodel}exp" AND PARENT:"workspace://SpacesStore/30da316f-9d2a-4e37-a28b-89d86bff6582" AND =@myexp\:num_exp:"Exp 433" The problem is that the node I'm searching isn't direct children of parent node.
PARENT don't search recursively? Are there another way to search on children and subchildren? I can't use PATH, because I need a quick response and I read that PATH isn't optimal.
-24779469 0 Implement rollback in Nested stored procedureI am using TRY CATCH block to capture error and do rollback
ALTER PROCEDURE sp_first /* parameters */ BEGIN TRY BEGIN TRANSACTION /* statements */ COMMIT END TRY BEGIN CATCH IF(@@TRANCOUNT>0) ROLLBACK END CATCH Will the above approach work if there is another stored procedure sp_inner being called inside sp_first which also performs DML statements INSERT , DELETE , UPDATE etc.
ALTER PROCEDURE sp_first /* parameters */ BEGIN TRY BEGIN TRANSACTION /* statements of sp_first */ -- stored procedure sp_inner also requires rollback if error occurs. EXEC sp_inner @paramaterList COMMIT END TRY BEGIN CATCH IF(@@TRANCOUNT>0) ROLLBACK END CATCH How to implement roll back if nested stored procedure is used?
-35751448 0 Disabling"Synchronous XMLHttpRequest on the main thread is deprecated"I'm using Chrome to debug a web page, and while debugging I get frequent warnings and stops with the message "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/."
I understand what is causing these, but they are in code over which I have no control. But their existence is making it hard to debug my code, as I have to click past twenty or so of these warnings to reach my code, and sometimes others are thrown during the execution of my code.
My question is: How do I prevent the Chrome debugger from stopping on these warnings?
-1530872 0 Jquery UI DatepickerI'd like to change the Default altFormat, but I can't seem to get it to work.
$("#myFav").datepicker({ dateFormat: 'yy-mm-dd' }); $("#myFav").datepicker('option', 'dateFormat', 'yy-mm-dd'); I thought altFormat would work just the same?
-12870896 0 Google Analytics Traffic Sources issue with mobile traffic redirected to m. siteA big chunk of my traffic is mobile. My server identifies this traffic by regex on the user agent and redirects (301) from www.mydomain.com to m.mydomain.com
My site has different sources I want to get insights on (ads, Facebook, referrer sites etc)
In the traffic sources report in Google Analytics I see a big chunk of visits originate from mydomain.com. That chunk size is similar to my mobile traffic, though a little lower.
Does it make sense that the traffic source issue is related to mobile?
If so:
One option I saw was faking a Google campaign by having the server add fake parameters to the query. This way I can use Google Analytics advertising-related reports to track origin.
I'm looking for something more straightforward if possible.
Will HTTP 302 work better?
The issue was in the dependencies of the gradle.build file.
Changed the following lines in gradle.build from:
dependencies { groovy 'org.codehaus.groovy:groovy:2.2.2' ... to:
dependencies { groovy 'org.codehaus.groovy:groovy-all:2.2.2' ... This resolved the issue.
-29615692 0 How to know what routes go on between two points?Ok guys, i'm dealing with this situation in my Android App. I have:
So.. my question is: how can I know what of these routes is the most nearest route from my location (origin) that can take me to another location (destination)?
I neeed to use Google Maps API? What part of the API?
Can you help me?
-40689117 0Seems you set inappropriate maximum nested level in style checks which provided by compiler switch "-gnatyL" and then set up the compiler to treat all warnings and style checks as errors by "-gnatwe" switch.
-21548428 0 Getting Server Error while calling Servlet from Java ApplicationHere is my Java Class by which I am calling simple servlet and passing the data, I am
using URL and HttpURlConnection class.What should be path of url for the servlet
public class TestJava { public static void main(String[] args) { try { URL url=new URL("http://localhost:9865/TestingServlet/PushServlet"); HttpURLConnection http_url =(HttpURLConnection) url.openConnection(); http_url.setRequestMethod("POST"); http_url.setDoOutput(true); http_url.setDoInput(true); InputStream response = http_url.getInputStream(); System.out.println(" " +response); ObjectOutputStream objOut = new ObjectOutputStream(http_url.getOutputStream()); objOut.writeObject("hello"); objOut.flush(); objOut.close(); } catch (IOException e) { e.printStackTrace(); } } } Here is the servlet code, I am receiving the object from the java code and displaying
it on the console.
public class PushServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { System.out.println("HELLO This is servlet"); ObjectInputStream objIn = new ObjectInputStream(request.getInputStream()); TestJava p = null; p = (TestJava) objIn.readObject(); System.out.println("Servlet received p: "+p); } catch (Throwable e) { e.printStackTrace(System.out); } } My web.xml is like this
<welcome-file-list> <welcome-file> Customer_Servlet </welcome-file> </welcome-file-list> <servlet> <servlet-name>PushServlet</servlet-name> <servlet-class>com.servlet.PushServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>PushServlet</servlet-name> <url-pattern>/PushServlet</url-pattern> </servlet-mapping> <session-config> <session-timeout>50</session-timeout> </session-config> </web-app> When i m trying to run the java code on server i.e Apache server, I'm getting
error HTTP Status 404 i am not able to find why i am getting this server error My code is all about invoking the servlet from java application
please help me guys .
-15495487 0 Just looking at it, I'm pretty sure your code works. Well I know this does.
<img id="pic" src="https://www.google.com.au/images/srpr/logo4w.png"/> <input type="button" value ="Yahoo" onclick="change('http://l.yimg.com/ao/i/mp/properties/frontpage/eclipse/img/y7-logo_default.v1.png')" /> <input type="button" value ="Google" onclick="change('https://www.google.com.au/images/srpr/logo4w.png')" /> <script> function change(src){ document.getElementById('pic').src = src; } </script>
-22302785 0 use this code:
public class KeyboardInput extends Thread{ Scanner sc= new Scanner(System.in); @Override public void run() { while(true) { sc.hasNext(); } } } Then just call this when you want to start the input:
Thread t1= new Thread(new KeyboardInput); t1.start(); Now you have a thread that reads inputs while the main thread is free to print to screen
EDIT: be sure to only call the thread once!
-30330509 0 Change color of links in NUnit Test Runner in ResharperI prefer to use the dark theme in Visual Studio, but one source of annoyance is the links in Resharper's nUnit Test Runner. I've looked everywhere, but I can't seem to find the option to change to get them to display properly.
Specifically, this the Unit Test Session window, the Output tab, when you have a stack trace and it has a link on it, it currently appears in the default dark blue, which is fine on a white/grey background...however on the black background, it looks horrible and is near impossible to read.
Does anyone know the option to change the color of that link?
-11564053 0 C++ Referencing an Object from a global static functionI have a globally declared static function that needs to reference an object, but when I do so, I get an "undeclared identifier" error.
Here is a sample of my code
#pragma once #include "stdafx.h" #include <vector> #include "Trigger.h" using namespace std; namespace Gamma_Globals { static vector<void*> gvTriggers; } static LPARAM CALLBACK ProgramWndProc(HWND, UINT, WPARAM, LPARAM); static LPARAM CALLBACK ProgramWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_KEYUP: { for (int i = 0; i < Gamma_Globals::gvTriggers.size(); i++) { Trigger t = Gamma_Globals::gvTriggers[i]; } } default: return DefWindowProc(hWnd, uMsg, wParam, lParam); break; } return 0; } The issue comes in the WM_KEYUP case, when I tried to set "Trigger t", I get the error "'Trigger' : undeclared identifier." What can I do to reference the Trigger object from ProgramWndProc?
Thanks!
As requested, here is a copy of Trigger.h
#pragma once #include "Noun.h" #include "TermFactory.h" #include "Globals.h" using namespace std; class Trigger { public: enum TRIGGER_TYPE {NONE, ONKEYPRESS, ONMOUSEPRESS}; Trigger(void*); Trigger(LPTSTR trigger, LPTSTR action, Gamma_Globals::TRIGGER_TIME); ~Trigger(void); VOID Perform(); TRIGGER_TYPE GetType(); private: LPTSTR lpCondition; LPTSTR lpAction; Gamma_Globals::TRIGGER_TIME triggerTime; vector<Noun*> vNouns; TRIGGER_TYPE triggerType; VOID LoadAction(LPTSTR Action); HRESULT LoadCondition(LPTSTR Condition); };
-8824737 0 Check this question, especially the answer with the OverrideCursor class.
I have a uitextview with more text that can fit in the view. I enabled "scrolling enabled" on the textview, however the scrollview does not scroll.
Here is how I populate the textview in viewDidLoad:
PFQuery *query = [MyObject query]; [query whereKey:@"cycleNumber" equalTo:_cycleNumber]; [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { if([objects count] > 0){ NSString *description = objects[0]; _lessonDescriptionTextView.text = description; } }]; How can I make the textview scroll to show all content?
-1069662 0I figured out a workaround... Since I am not making any changes to the DocumentLibrary list schema, i can just reference that list and only need a ListInstance element that references the DocumentLibrary feature and list TemplateType. So my Elements will now look like this:
<ListInstance FeatureId="00BFEA71-E717-4E80-AA17-D0C71B360101" TemplateType="101" Id="Pages" Title="Content Pages" Description="Web Site Content Pages" Url="Pages" OnQuickLaunch="True" />
-40046142 0 You can create your own CSS file. Then your have imported the CSS file on client side.
You need to write following CSS in that file.
.wrapper { position: initial; //You can use !important in case it doesn't overwrite the CSS. } -10358488 0Note: Pleae make sure your file load after the admin lte css files.
Template value must be compile-time constant, that is literal, constexpr or static const variable.
I recently moved my website from a ASP/IIS server to a LINUX/APACHE:
Most of my new URL's looks the same, but without .aspx extension.
OLD: http://example.com/yankees-news.aspx
NEW: http://example.com/yankees-news
I want search engine users clicking on old URL's/Links to Redirect to new URLs.
-7237488 0Value property of NumericUpDown is Decimal - that is perhaps why you are having issues. In your if block, I would consider casting the Value Property of NumericUpDown object into an integer in the true part and use integer value 3 in its else part. There after, I would avoid parsing again and give it to Substring as is.
-8230438 0 download file from absolute uri to stream to SaveFileDialogI've gotten as far as putting a file into a stream from a url. However puttin savefiledialog inside the event OpenReadCompleted gives an exception because the savefiledialog needs to be fired from an user iniated event. Putting the savefiledialog NOT inside OpenReadCompleted gives an error because the bytes array is empty, not yet processed. Is there another way to save a file to stream from a uri without using an event?
public void SaveAs() { WebClient webClient = new WebClient(); //Provides common methods for sending data to and receiving data from a resource identified by a URI. webClient.OpenReadCompleted += (s, e) => { Stream stream = e.Result; //put the data in a stream MemoryStream ms = new MemoryStream(); stream.CopyTo(ms); bytes = ms.ToArray(); }; //Occurs when an asynchronous resource-read operation is completed. webClient.OpenReadAsync(new Uri("http://testurl/test.docx"), UriKind.Absolute); //Returns the data from a resource asynchronously, without blocking the calling thread. try { SaveFileDialog dialog = new SaveFileDialog(); dialog.Filter = "All Files|*.*"; //Show the dialog bool? dialogResult = dialog.ShowDialog(); if (dialogResult != true) return; //Get the file stream using (Stream fs = (Stream)dialog.OpenFile()) { fs.Write(bytes, 0, bytes.Length); fs.Close(); //File successfully saved } } catch (Exception ex) { //inspect ex.Message MessageBox.Show(ex.ToString()); } }
-34501567 0 Proxy a websocket to hide the IP I have a sub domain routed through cloudflare. They don't cover websockets unless it enterprise or maybe business depending on traffic.
So now when users visit the external site, it connects to my sub domain via a websocket with the url of my site being passed in their url.
e.g thridpartysite.com?ws=my.subdomain.com But my IP is revealed and I am worried about DDoS.
I am using nginx and ubuntu 14.04. Is there anything I can do to mask the IP?
Here is my current nginx config
# Config server { listen 80; listen [::]:80; server_name my.subdomain.com www.my.subdomain.com; location / { proxy_pass http://MySubdomainIP:443; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } } So it takes the app on 443 and proxies to 80 so I can route that through cloudflare but no websocket support means I need to reveal my IP which leaves me open to DDoS attacks.
Is there anything I can do at this point?
-21554839 0 The menu is not displayed in mac os 10.9.1In my application used "Application is agent(UIElement)" = YES.
I use it to hide the second process. But first process need show.
For show process I used code:
// display dock icon TransformProcessType(&psn, kProcessTransformToForegroundApplication); // enable menu bar SetSystemUIMode(kUIModeNormal, 0); // switch to Dock.app [[NSWorkspace sharedWorkspace] launchAppWithBundleIdentifier:@"com.apple.dock" options:NSWorkspaceLaunchDefault additionalEventParamDescriptor:nil launchIdentifier:nil]; // switch back [[NSApplication sharedApplication] activateIgnoringOtherApps:TRUE]; The problem is that the menu is not displayed. But if you switch to some other program and back, the menu appears.
-19671043 0I've got exactly the same question. The problem as I see it is that the view login_form is designed to cater for everything (forgotten passwords, captchas, etc) in one. What I'm trying to create is a system where there is the quick login, and then if needed, another view to deal with registration, forgotten passwords, etc. I'm struggling to separate out the two objectives from this one login_form form.
The auth controller login function has all that logic, and then simply $this->load->view('auth/login_form', $data);
-6942445 0I have had mixed results using TemplateBinding on custom dependency properties. Because of this, I have used RelativeSource TemplatedParent which seems to work in every situation.
<EasingColorKeyFrame KeyTime="0:0:.5" Value="{Binding HeaderColor, RelativeSource={RelativeSource TemplatedParent}}" />
-16720560 0 If you want to check if a variable (say v) has been defined and is not null:
if (typeof v !== 'undefined' && v !== null) { // Do some operation } If you want to check for all falsy values such as: undefined, null, '', 0, false:
if (v) { // Do some operation }
-32920954 0 The simplest solution is to use
new Loadable(); if the class is know at compile time and you expect it to be available at runtime. Note: this will throw a NoClassDefError at runtime if it is not available.
If you are not sure it will be available a runtime, you might use
Class.forName("classload.Loadable").newInstance(); as it is clearer as to which exceptions will be thrown.
The problem with
classload.Loadable.class.newInstance() is that it's not particularly useful in either context.
Note: Class.newInstance() has a known issue were it will throw checked exceptions which you don't know about. i.e. if the Constructor throws a checked exception it won't be wrapped and the compiler can't tell what will be thrown.
With CSS3 you could also use a[rel="#"] {display:none}
I'm writing a program that reads integer values from an input file, divides the numbers, then writes percentages to an output file. Some of the values that my program may be zero, and bring up a 0/0 or 4/0 occasion.
From here, I get a Zerodivisionerror, is there a way to ignore this error so that it simply prints 0%??
Thanks.
-35058702 0try this way it will help
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:id="@+id/container_toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <include android:id="@+id/toolbar" layout="@layout/toolbar" /> </LinearLayout> <FrameLayout android:id="@+id/container_body" android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="1" /> </LinearLayout> <fragment android:id="@+id/fragment_navigation_drawer" android:name="info.androidhive.materialdesign.activity.FragmentDrawer" android:layout_width="@dimen/nav_drawer_width" android:layout_height="match_parent" android:layout_gravity="start" app:layout="@layout/fragment_navigation_drawer" tools:layout="@layout/fragment_navigation_drawer" /> </android.support.v4.widget.DrawerLayout>
-7829312 0 Why can't post scores via Scores API in Javascript? I'm writing a javascript game library that I want to integrate with Facebook Scores. Games made with my library typically run on static file servers (i.e. just ordinary HTML+JS, no server side scripts).
I've been looking at the scores documentation and have come across this problem: you can only submit a score with an app access token.
Why?
Correct me if I'm wrong, but it seems I can't get an app access token unless I have the app secret, and it seems obvious I should not put the app secret in javascript. For most of these games, server side scripting is out of the question. So I have no way to get an app access token, so none of these games can submit scores.
What seems especially dumb is if the user grants the app the "publish_stream" permission, you can automatically make a wall post along the lines of "I just scored 77777 in MySuperGame!". You can do that with just pure HTML+JS. But you can't post a score.
Am I missing something or is the API just a bit dumb about this?
-26108113 0Personally I found Stephen Toub's article to be the best source regarding constrained execution regions: Using the Reliability Features of the .NET Framework. And in the end CER are the bread and butter of any fault tolerant code so this article contains pretty much everything you need to know, explained in a clear and concise way.
That being said you could rather choose to favor a more radical design where you immediately resort to the destruction of the application domain (or depend on this pattern when the CLR is hosted). You could look at the bulkhead pattern for example (and maybe the reactive manifesto if you're interested on this pattern and facing complex data flows).
That being said, the "let it fail" approach can backfire if you cannot completely recover after that, as demonstrated by Ariane V.
-35812557 0var i = 0; var myImg = document.getElementById("img"); function zoomin(){ i++; myImg.style.transform = "scale(1."+ i +")"; } declare i=0; outside function will solve you probleem
-38305696 0I suspect that with mention of nodejs, there are a bunch of npm packages being downloaded as part of the build. On your local machine, these are already present but Kudu is restoring them in a clean folder every time.
Secondly, about 5 mins of your build time is spent on building (and probably running) test projects. Unless intentional and required in deployment workflow, I would recommend turning if off via a flag.
-15631496 0 Issue using bootstrap responsive for tablet and phonesI am designing a page using bootstrap responsive for the following image and I'm beginner for using bootstrap responsive..
And the html is as follows.
<!DOCTYPE HTML> <html> <head> <meta http-equiv="content-type" content="text/html" /> <meta name="author" content="" /> <meta charset="utf-8"> <title>Bootstrap Responsive</title> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <meta content="" name="description"> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/bootstrap-responsive.min.css"> <style> .container { margin-top: 80px; } #main-form { margin: auto; width: 500px; } .profile-photo { vertical-align: middle; } .form { text-align: center; } .profile-image { width: 100%; height: 100%; } </style> <body> <div class="container"> <div class="row text-center"> <img src="img/slider/1.jpg" width="250px" height="250px" /> </div> <div class="row text-center"> <h2>Create your account</h2> </div> <div class="row"> <div id="main-form"> <div class="span2"> <div class="profile-photo"> <img class="profile-image" src="img/slider/1.jpg" /> </div> </div> <div class="span3 form"> <div class="widget-container widget-box4"> <div class="control-group"> <div class="controls"> <input type="text" id="inputEmail" placeholder="Username"> </div> </div> <div class="control-group"> <div class="controls"> <input type="text" id="inputEmail" placeholder="Email"> </div> </div> <div class="control-group"> <div class="controls"> <input type="password" id="inputPassword" placeholder="Password"> </div> </div> <div class="control-group"> <div class="controls"> <input type="password" id="inputPassword" placeholder="Confirm Password"> </div> </div> <div class="control-group"> <div class="controls"> <input type="checkbox"> Remember me </div> </div> <div class="control-group"> <div class="controls"> <button type="submit" class="btn">Sign in</button> </div> </div> </div> </div> </div> </div> </div> <script src="js/jquery-1.9.1.min.js"></script> <script src="js/bootstrap.min.js"> <script type="text/javascript"> $('.carousel').carousel(); </script> </body> I wanted it in the middle of the page and I'm getting correctly in Desktop.
But problem is the form and profile image are not coming in center.
Please help me how to do that?.
The work is more appreciated.
-17871476 01)Use KeyBindings KeyListener has 2 big issues,first you listen to all keys and second you have to have focus and be focusable. Instead KeyBinding you bind for a key and you don't have to be in focus.
Simple Example:
AbstractAction escapeAction = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { //code here example ((JComponent)e.getSource()).setVisible(Boolean.FALSE); }}; String key = "ESCAPE"; KeyStroke keyStroke = KeyStroke.getKeyStroke(key); component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, key); component.getActionMap().put(key, escapeAction); You can use these JComponent constants
WHEN_ANCESTOR_OF_FOCUSED_COMPONENT WHEN_FOCUSED WHEN_IN_FOCUSED_WINDOW 2) Don't use concrete inheritance if it isn't necessary at all.
3) Don't implement ActionListener in top classes, see Single Responsability Principle Example Change this:
public class Board extends JPanel implements ActionListener{ to:
public class Board{ private JPanel panel; private class MyActionListener implements ActionListener{ //code here } } 4) Don't use inheritance if it's just the same for example in your KeyAdapter , you don't add nothing to it, just use KeyAdapter (Now you are gonna to use keybinding so this is useless but to know :) ).
5) Add @Override annotation when you do overriding , also you should override paintComponent(..) instead of paint(..) in swing.
I have filed an issue against Python. The text of this issue is reproduced below:
PEP 8 recommends absolute imports over relative imports, and section 5.4.2 of the import documentation says that an import will cause a binding to be placed in the imported module's parent's namespace.
However, since (with all current Python versions) this binding is not made until after the module body has been executed, there are cases where relative imports will work fine but absolute imports will fail. Consider the simple case of these five files:
xyz.py: import x x/__init__.py: import x.y x/y/__init__.py: import x.y.a x/y/a/__init__.py: import x.y.b; foo = x.y.b.foo x/y/b/__init__.py: foo = 1 This will fail in a fashion that may be very surprising to the uninitiated. It will not fail on any of the import statements; rather it will fail with an AttributeError on the assignment statement in x.y.a, because the import of y has not yet finished, so y has not yet been bound into x.
This could conceivably be fixed in the import machinery by performing the binding before performing the exec. Whether it can be done cleanly, so as not to cause compatibility issues with existing loaders, is a question for core maintainers.
But if it is decided that the current behavior is acceptable, then at a minimum both the PEP 8 and the import documentation should have an explanation of this corner case and how it can be solved with relative imports.
-15779474 0 selenium run only few methodsI know by creating test suite I can run all my class files, using code like
suite.addTestSuite( TestCase3.class); suite.addTestSuite( TestCase2.class); suite.addTestSuite( TestCase1.class); But what if I dont want to run all the methods in a class file? I want to run only specific test methods inside a test class, how to do that?
-24436121 0None of the proposed solutions work to show the original column names, so I'm not sure why people are voting them up... I do have a "hack" that works for the original request, but I really don't like it... That is you actually append or prefix a string onto the query for each column so they are always long enough for the column heading. If you are in an HTML mode, as the poster is, there is little harm by a bit of extra white spacing... It will of course slow down your query abit...
e.g.
SET ECHO OFF SET PAGESIZE 32766 SET LINESIZE 32766 SET NUMW 20 SET VERIFY OFF SET TERM OFF SET UNDERLINE OFF SET MARKUP HTML ON SET PREFORMAT ON SET WORD_WRAP ON SET WRAP ON SET ENTMAP ON spool '/tmp/Example.html' select (s.ID||' ') AS ID, (s.ORDER_ID||' ') AS ORDER_ID, (s.ORDER_NUMBER||' ') AS ORDER_NUMBER, (s.CONTRACT_ID||' ') AS CONTRACT_ID, (s.CONTRACT_NUMBER||' ') AS CONTRACT_NUMBER, (s.CONTRACT_START_DATE||' ') AS CONTRACT_START_DATE, (s.CONTRACT_END_DATE||' ') AS CONTRACT_END_DATE, (s.CURRENCY_ISO_CODE||' ') AS CURRENCY_ISO_CODE, from Example s order by s.order_number, s.contract_number; spool off; Of course you could write a stored procedure to do something better, but really it seems like overkill for this simple scenario.
This still does not meet the original posters request either. In that it requires manually listing on the columns and not using select *. But at least it is solution that works when you are willing to detail out the fields.
However, since there really is no problem having too long of fields in HTML, there is an rather simple way to fix Chris's solution to work it this example. That is just pick a use the maximum value oracle will allow. Sadly this still won't really work for EVERY field of every table, unless you explicitly add formatting for every data type. This solution also won't work for joins, since different tables can use the same column name but a different datatype.
SET ECHO OFF SET TERMOUT OFF SET FEEDBACK OFF SET PAGESIZE 32766 SET LINESIZE 32766 SET MARKUP HTML OFF SET HEADING OFF spool /tmp/columns_EXAMPLE.sql select 'column ' || column_name || ' format A32766' from all_tab_cols where data_type = 'VARCHAR2' and table_name = 'EXAMPLE' / spool off SET HEADING ON SET NUMW 40 SET VERIFY OFF SET TERM OFF SET UNDERLINE OFF SET MARKUP HTML ON SET PREFORMAT ON SET WORD_WRAP ON SET WRAP ON SET ENTMAP ON @/tmp/columns_EXAMPLE.sql spool '/tmp/Example.html' select * from Example s order by s.order_number, s.contract_number; spool off;
-36225137 0 sensu-client is failing during start My sensu-client is failing during start (fresh install) and /var/log/sensu/sensu-client.log doesn't show much despite me adding LOG_LEVEL=debug into /etc/default/sensu . I used similar client.json and rabbitmq.json config files (inside /etc/sensu/conf.d) on my other sensu-clients (copied ssl certificates).
$ sudo service sensu-client start [FAILED] sensu-client[ OK ] Below is sensu-client log
$ tail -f /var/log/sensu/sensu-client.log from /opt/sensu/embedded/lib/ruby/gems/2.0.0/gems/sensu-0.20.3/lib/sensu/daemon.rb:187:in `setup_transport' from /opt/sensu/embedded/lib/ruby/gems/2.0.0/gems/sensu-0.20.3/lib/sensu/client/process.rb:412:in `start' from /opt/sensu/embedded/lib/ruby/gems/2.0.0/gems/sensu-0.20.3/lib/sensu/client/process.rb:19:in `block in run' from /opt/sensu/embedded/lib/ruby/gems/2.0.0/gems/eventmachine-1.0.3/lib/eventmachine.rb:187:in `call' from /opt/sensu/embedded/lib/ruby/gems/2.0.0/gems/eventmachine-1.0.3/lib/eventmachine.rb:187:in `run_machine' from /opt/sensu/embedded/lib/ruby/gems/2.0.0/gems/eventmachine-1.0.3/lib/eventmachine.rb:187:in `run' from /opt/sensu/embedded/lib/ruby/gems/2.0.0/gems/sensu-0.20.3/lib/sensu/client/process.rb:18:in `run' from /opt/sensu/embedded/lib/ruby/gems/2.0.0/gems/sensu-0.20.3/bin/sensu-client:10:in `<top (required)>' from /opt/sensu/bin/sensu-client:23:in `load' from /opt/sensu/bin/sensu-client:23:in `<main>' ^C Here is default config
$ cat /etc/default/sensu EMBEDDED_RUBY=false LOG_LEVEL=debug Even reboot of my RHEL7 doesnt help, see log below
Mar 25 13:09:24 nms02w sensu-client: Starting sensu-client[ OK ]#015[FAILED] Mar 25 13:09:24 nms02w systemd: sensu-client.service: control process exited, code=exited status=1 Mar 25 13:09:24 nms02w systemd: Unit sensu-client.service entered failed state. Mar 25 13:09:24 nms02w systemd: sensu-client.service failed. Adding more log:
systemctl status sensu-client.service ● sensu-client.service - LSB: Sensu monitoring framework client Loaded: loaded (/etc/rc.d/init.d/sensu-client) Active: failed (Result: exit-code) since Fri 2016-03-25 13:09:24 EDT; 1h 47min ago Docs: man:systemd-sysv-generator(8) Process: 948 ExecStart=/etc/rc.d/init.d/sensu-client start (code=exited, status=1/FAILURE) Mar 25 13:09:21 nms02w systemd[1]: Starting LSB: Sensu monitoring framework client... Mar 25 13:09:21 nms02w runuser[983]: pam_unix(runuser:session): session opened for user sensu by (uid=0) Mar 25 13:09:24 nms02w sensu-client[948]: [38B blob data] Mar 25 13:09:24 nms02w systemd[1]: sensu-client.service: control process exited, code=exited status=1 Mar 25 13:09:24 nms02w systemd[1]: Failed to start LSB: Sensu monitoring framework client. Mar 25 13:09:24 nms02w systemd[1]: Unit sensu-client.service entered failed state. Mar 25 13:09:24 nms02w systemd[1]: sensu-client.service failed.
-19751863 0 If you are on windows use MinGW or like most have suggested ggo with GCC on Linux
Though ofcourse since it's commandline so you might find Dev-C++ and/or Code::Blocks, Eclipse CDT etc which are IDEs useful for you to make your job simpler.
There is no standard and each compiler and it's libraries differ from one another.
-27730637 0 add Account(settings) method doesn't start ActivityI want to create custom app account in settings.
settings > Add account but no nameAuthenticatorActivity doesn't start. I debug Authenticator class, addAccount method is called but no activity popped.I did the following steps:
public class AccountAuthenticator extends AbstractAccountAuthenticator{ @Override public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException { final Intent intent = new Intent(mContext, AuthenticatorActivity.class); intent.putExtra(AuthenticatorActivity.ARG_ACCOUNT_TYPE, accountType); intent.putExtra(AuthenticatorActivity.ARG_AUTH_TYPE, authTokenType); intent.putExtra(AuthenticatorActivity.ARG_IS_ADDING_NEW_ACCOUNT, true); intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response); final Bundle bundle = new Bundle(); bundle.putParcelable(AccountAuthenticator.KEY_INTENT, intent); return bundle; } } public class AuthenticatorService extends Service{ @Override public IBinder onBind(Intent intent) { authenticator = new AccountAuthenticator(this); return authenticator.getIBinder(); } } <service android:name="com.voillo.utils.AuthenticatorService" android:exported="false" android:label="@string/app_name"> <intent-filter> <action android:name="android.accounts.AccountAuthenticator" /> </intent-filter> <meta-data android:name="android.accounts.AccountAuthenticator" android:resource="@xml/authenticator" /> </service> <account-authenticator xmlns:android="http://schemas.android.com/apk/res/android" android:accountType="com.example.myapp" android:icon="@drawable/myapp_icon" android:smallIcon="@drawable/myapp_icon_small" android:label="myapp" />
-16072877 0 I am not claiming this is how to do it, but it seems to work, and would appreciate any opinions. Thanks
DELIMITER $$ CREATE PROCEDURE `createRecord` () BEGIN IF NEW.created_by_user IS NULL OR NEW.created_by_user = '' THEN SET NEW.created_by_user = @users_id; END IF; IF NEW.modified_by_user IS NULL OR NEW.modified_by_user = '' THEN SET NEW.modified_by_user = @users_id; END IF; END$$ CREATE PROCEDURE `modifyRecord` () BEGIN IF NEW.modified_by_user = OLD.modified_by_user THEN SET NEW.modified_by_user = @users_id; END IF; END$$ CREATE TRIGGER tg_notes_upd BEFORE UPDATE ON notes FOR EACH ROW BEGIN CALL createRecord(); END$$ CREATE TRIGGER tg_notes_ins BEFORE INSERT ON notes FOR EACH ROW BEGIN CALL modifyRecord(); END$$ DELIMITER ;
-29189599 0 It's not clear what you mean by "issues distinguishing between AM and PM". Is it that you enter a time in the afternoon, e.g. 12pm, then add minutes and it becomes am? That's because minutesAdded() is using the number of minutes to determine whether it's the morning or evening. You would be better off calculating the time -- meaning the whole time, hours and minutes, not just minutes -- before printing out the time. You have made a start with
nTime = minutes + addedMinutes; but don't stop there. As long as the accumulated minutes value is >= 60, you have to take off 60 minutes and bump the hours up by one. Not just once. If you add 122 minutes, you have to take TWO lots of 60 minutes off. Does that sound like a while loop? No, not unless you want the teacher to laugh at your code! Look up the operators for division and remainder. You're trying to do the calculation and the output in one step. That's difficult. Work out the value first, then print it afterwards.
Oh, and by the way, don't forget about what happens if you add 200 minutes to 23:00...
When you are working out the time after adding the minutes, why do you not use the hours and minutes variables? If you add some minutes to your time, the time should be changed, meaning the minutes and/or hours members should be updated.
You should have a method to add the minutes -- not to read the amount to be added, and then print out the time with the minutes added, just a method to add the minutes.
void Time::incrementMinutes(int nMinutes) { ...the code to update hours and minutes variables correctly is left as an exercise... } Then after you have got addedMinutes from cin, call
incrementMinutes(addedMinutes); Then you could make a method to print the time, printTime() which sends the time to cout. That would then be used by minutesAdded() and by militaryClock(), so you don't have to worry in BOTH places about all the conditions for whether it's AM or PM. You only have to get that right in printTime().
Now, about the structure of your program.
First, the constructor should construct the object, set everything in it. It gets called automatically when an instance is constructed, to set up the whole instance. It's not the way to just set one field. Please write a different method to set the minutes to 0 if you are not constructing a Time object.
Maybe setMinutes was to have been that method. But setMinutes() is
void Time::setMinutes() { this -> minutes = minutes; } That doesn't do anything. Within the method of an object, the member name refers to the member of the object (unless overridden by the same name in a closer scope). So within this function, 'minutes' means the same as 'this->minutes'.
Maybe you intended something like this instead?
void Time::setMinutes(int newMinutes) { minutes = newMinutes; } That would at least set this->minutes to a certain value. Then, to set minutes to 0, you don't call Time(), you call setMinutes(0).
Finally, you can tell cout to use 2 characters for minutes, by piping setw(2) before the number; you can tell it to use the value '0' for the extra character by piping in setfill('0'). You have to #include to get this stuff. So
#include <iostream> #include <iomanip> using namespace std; int main() { cout << setfill('0') << setw(2) << 1 << ":" << setw(2) << 2 << endl; } will output 01:02 The setfill('0') means any padding will be done with '0'; the setw(2) means the single next thing output will be padded to 2 chars.
Hope that helps... without doing your homework for you...
-21948559 0You are inserting a String as parameter to the setOpacity method, which only takes doubles.
-20721988 0 background is gone whenI want my application will be more smoothly and I read that hardware_acceleraton could be a solution.
So I turn on hardware_acceleraton = true and my background image just gone and only appearing black background.
Do I have to do another thing or what is wrong here?
-12054987 0 Devise/OmniAuth - LinkedIn: Email is blank in callbackI'm using Devise 2.1.2 with multiple OmniAuth providers. My devise.rb file contains this line:
config.omniauth :linkedin, API_KEY, SECRET_KEY, :scope => 'r_emailaddress', :fields => ["email-address"] It is currently stripped down to just email-address since that is the only thing acting strange. Taking a look inside request.env['omniauth.auth'].info, the email key is blank.
How come? I don't want to bypass validation, I wan't to use the email address from the users LinkedIn account.
-18616083 0 Why does my MVC 4 Project Partially Run on Production IIS 7 ServerWe have a ASP.NET MVC 4 project containing a number of controllers, models and views.
On our development server a Windows Standard 2008 (x64) the project is deployed/published and it runs fine.
However, when we try to publish the project to our live production server running a Windows Web 2008 x64 the MVC pages appear to partially load, but when we try to make calls to the controller it appears that it is failing.
It is very difficult for me to give more information, since I don't know where to trap the error or how to diagnose the problem.
Any help would be greatly received.
-12457346 0You will not be able to retrieve a plain text password from wordpress.
Wordpress use a 1 way encryption to store the passwords using a variation of md5. There is no way to reverse this.
See this article for more info http://wordpress.org/support/topic/how-is-the-user-password-encrypted-wp_hash_password
-31957052 0put this theme in your manifest file in application Tag
android:theme="@android:style/Theme.Black.NoTitleBar"
-30817100 0All the problems boil down to the fact that the following declaration
slist<int> L; throwed the error that
slist was not declared in this scope
You need to make sure slist is declared in your scope. include the necessary headers.
That's because when the JTextField is shown, the mouseExited() method is immediately called. Then of course the JLabel is shown again and this loops while you keep moving the mouse.
The following works:
jl.addMouseListener(new MouseAdapter() { public void mouseEntered(MouseEvent evt) { cl.show(jp, "2"); } }); jtf.addMouseListener(new MouseAdapter() { public void mouseExited(MouseEvent evt) { cl.show(jp, "1"); } });
-25763592 0 Symmetric Encryption isn't working I am trying to generate cipher text and decrypted data. I already have assigned my incrypted value and key. But when I run the program in netbeans it shows error in the execution area, but no cipher text and decrypted data is produced.
Encryption.java:
package encryption; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class Encryption { private static byte[] message; public static void main(String[] args) throws Exception { byte[] message = {0, 0, 1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 2, 3, 8, 9}; byte[] key = {1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4}; byte[] ciphertext; byte[] decrypted; Sender s = new Sender(); s.send(message); Receiver r = new Receiver(); r.receive(message); // TODO code application logic here } } Sender.java:
package encryption; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class Sender { private Cipher encoder; private SecretKeySpec myKey; public Sender() throws Exception { encoder = Cipher.getInstance("AES"); } public void setKey(byte[] key) throws Exception { myKey = new SecretKeySpec(key, "AES"); encoder.init(Cipher.ENCRYPT_MODE, myKey); } public byte[] send(byte[] message) throws Exception { return encoder.doFinal(message); } } Receiver.java:
package encryption; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class Receiver { private Cipher decoder; private SecretKeySpec myKey; public Receiver()throws Exception{ decoder=Cipher.getInstance("AES"); } public void setKey(byte[] key) throws Exception{ myKey= new SecretKeySpec(key ,"AES"); decoder.init(Cipher.DECRYPT_MODE, myKey); } public byte[] receive(byte[] message) throws Exception{ return decoder.doFinal(message); } }
-37655373 0 You can use Array#sort with Math.abs().
arr.sort((a, b) => Math.abs(a - num) - Math.abs(b - num)); Using ES5 Syntax for older browsers
arr.sort(function(a, b) { return Math.abs(a - num) - Math.abs(b - num); }); To consider negative numbers too, don't use Math.abs().
var arr = [10, 45, 69, 72, 80]; var num = 73; var result = arr.sort((a, b) => Math.abs(a - num) - Math.abs(b - num));; console.log(result); These subprograms (functions and procedures) are probably not what you want them to be: they are declared within the Polynomials package, but do not reference the type Polynomial at all.
Apart from that, your question is easily answered: POLYNOMIO is not a tagged type, so object.function notation does not work. You should call type.function instead, i.e. Polynomials.times (q).
I would guess that you are using experience (or some pre-written code) from a language like C++ or Java. There, the functions (methods) belong to the class/type and take an implicit parameter to an instance of that class. This is not the case in Ada: the functions belong to the package, and you have to add a parameter yourself, e.g.
function times (p: Polynomial; b: Integer) return Integer; (Shouldn't it return a Polynomial?)
A question: why do you declare two similar types, Polynomials.Polynomial and Polynomials_Test.POLYNOMIO?
Try <script src="/resources/js/controller.js"></script>
You can take the iterator from the List of OrdemItem here:
private List<OrderItem> items = new ArrayList<OrderItem>(); and do:
public Iterator<OrderItem> iterator() { return items.iterator(); } instead of doing
public Iterator<OrderItem> iterator() { return this.iterator(); //How to do this part?? }
-40956784 0 I would use:
if [ $YARN -eq 1 ]; then npm install -g yarn && echo "yarn installed" fi My bash reports 1 if program is not installed and i am not sure if value 1 will pass the -z test
-38063055 0 fibers install not possible on ubuntu 14.04When I try to install fibers, I get this errormessage.
I have Node version 0.10.45 for the use Meteor 1.3.2 on Ubuntu 14.04 64 Bits on a Strato VPS.
When I do a meteor build I need to run npm install fibers inside of programs/server of the build output. But I have no chance installing fibers as I get this output. I have not found anything yet about that problem on the web.
sudo npm install -g fibers > fibers@1.0.13 install /usr/local/lib/node_modules/fibers > node build.js || nodejs build.js (...) make: Entering directory `/usr/local/lib/node_modules/fibers/build' CXX(target) Release/obj.target/fibers/src/fibers.o g++: internal compiler error: Bus error (program as) (...) make: *** [Release/obj.target/fibers/src/fibers.o] Error 4 make: Leaving directory `/usr/local/lib/node_modules/fibers/build' (...) gyp ERR! stack Error: `make` failed with exit code: 2 gyp ERR! stack at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:276:23) gyp ERR! stack at ChildProcess.emit (events.js:98:17) gyp ERR! stack at Process.ChildProcess._handle.onexit (child_process.js:820:12) gyp ERR! System Linux 3.13.0-042stab111.12 gyp ERR! command "node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--release" gyp ERR! cwd /usr/local/lib/node_modules/fibers (...) Ubuntu users please run: `sudo apt-get install g++` Alpine users please run: `sudo apk add python make g++` npm ERR! Linux 3.13.0-042stab111.12 npm ERR! argv "node" "/usr/local/bin/npm" "install" "-g" "fibers" npm ERR! node v0.10.45 npm ERR! npm v3.10.2 npm ERR! file sh npm ERR! code ELIFECYCLE npm ERR! errno ENOENT npm ERR! syscall spawn npm ERR! fibers@1.0.13 install: `node build.js || nodejs build.js` npm ERR! spawn ENOENT npm ERR! npm ERR! Failed at the fibers@1.0.13 install script 'node build.js || nodejs build.js'. npm ERR! Make sure you have the latest version of node.js and npm installed. npm ERR! If you do, this is most likely a problem with the fibers package, npm ERR! not with npm itself. npm ERR! Tell the author that this fails on your system: npm ERR! node build.js || nodejs build.js npm ERR! You can get information on how to open an issue for this project with: npm ERR! npm bugs fibers npm ERR! Or if that isn't available, you can get their info via: npm ERR! npm owner ls fibers npm ERR! There is likely additional logging output above. npm ERR! Please include the following file with any support request: npm ERR! /home/keller/repos/rmt-app/npm-debug.log
-30422729 0 Performance difference between member function and global function in release version I have implemented two functions to perform the cross product of two Vectors (not std::vector), one is a member function and another is a global one, here is the key codes(additional parts are ommitted)
//for member function template <typename Scalar> SquareMatrix<Scalar,3> Vector<Scalar,3>::outerProduct(const Vector<Scalar,3> &vec3) const { SquareMatrix<Scalar,3> result; for(unsigned int i = 0; i < 3; ++i) for(unsigned int j = 0; j < 3; ++j) result(i,j) = (*this)[i]*vec3[j]; return result; } //for global function: Dim = 3 template<typename Scalar, int Dim> void outerProduct(const Vector<Scalar, Dim> & v1 , const Vector<Scalar, Dim> & v2, SquareMatrix<Scalar, Dim> & m) { for (unsigned int i=0; i<Dim; i++) for (unsigned int j=0; j<Dim; j++) { m(i,j) = v1[i]*v2[j]; } } They are almost the same except that one is a member function having a return value and another is a global function where the values calculated are straightforwardly assigned to a square matrix, thus requiring no return value.
Actually, I was meant to replace the member one by the global one to improve the performance, since the first one involes copy operations. The strange thing, however, is that the time cost by the global function is almost two times longer than the member one. Furthermore, I find that the execution of
m(i,j) = v1[i]*v2[j]; // in global function requires much more time than that of
result(i,j) = (*this)[i]*vec3[j]; // in member function So the question is, how does this performance difference between member and global function arise?
Anyone can tell the reasons?
Hope I have presented my question clearly, and sorry to my poor english!
//----------------------------------------------------------------------------------------
More information added:
The following is the codes I use to test the performance:
//the codes below is in a loop Vector<double, 3> vec1; Vector<double, 3> vec2; Timer timer; timer.startTimer(); for (unsigned int i=0; i<100000; i++) { SquareMatrix<double,3> m = vec1.outerProduct(vec2); } timer.stopTimer(); std::cout<<"time cost for member function: "<< timer.getElapsedTime()<<std::endl; timer.startTimer(); SquareMatrix<double,3> m; for (unsigned int i=0; i<100000; i++) { outerProduct(vec1, vec2, m); } timer.stopTimer(); std::cout<<"time cost for global function: "<< timer.getElapsedTime()<<std::endl; std::system("pause"); and the result captured:

You can see that the member funtion is almost twice faster than the global one.
Additionally, my project is built upon a 64bit windows system, and the codes are in fact used to generate the static lib files based on the Scons construction tools, along with vs2010 project files produced.
I have to remind that the strange performance difference only occurs in a release version, while in a debug build type, the global function is almost five times faster than the member one.(about 0.10s vs 0.02s)
-33624861 0Try this one, it should do exactly what you want:
let date = NSDate() let dateFormetter = NSDateFormatter() dateFormetter.dateFormat = "h:mm a" dateFormetter.timeZone = NSTimeZone(name: "UTC") dateFormetter.locale = NSLocale(localeIdentifier: "en_GB") let timeString = dateFormetter.stringFromDate(date) // 7:34 a.m.
-38504311 0 You can simple parse that date as shown below.
package com.test; import java.text.ParseException; import java.text.SimpleDateFormat; public class Sample { public static void main(String[] args) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); System.out.println(sdf.parse("2016-07-21T11:25:00.000+01:00")); } }
-19316023 0 Short Answer : No
Workaround : Use Javascript or jQuery using .toggle()
If you want to stick with CSS, you can do something like
div[style*="block"] + div { display: none; } The above selector will see whether div having an attribute of style contains a value called block if yes, than hide the adjacent div element using +
As explained in this answer, you need to add a TargetFrameworkVersion by manually editing the .vcxproj file.
I have VS2008 installed on that machine but I think I also selected to include the VC90 compilers when I installed 2010.
However, it appears it is not supported by design, according to this Microsoft response: targeting the 3.5 framework with the Visual C++ 2010 compiler is not supported. The Visual C++ 2010 compiler only supports targeting the 4.0 framework.
-39987143 0Final Update: I was able to fix this by using psqlodbc_09_03_0400. For whatever reason, other versions kept throwing error.
-8651613 0Use .Distinct(). Since you can't use the default comparer, you can implement one like this
class MyEqualityComparer : IEqualityComparer<Comment> { public bool Equals(Comment x, Comment y) { return x.Sender.Equals(y.Sender); } public int GetHashCode(Comment obj) { return obj.Sender.GetHashCode(); } } And then just filter them like this. You don't need the if statement.
List<Comment> StreamItemComments = objStreamItem.GetComments() .Distinct(new MyEqualityComparer()) .Where(x => x.Sender != ClientUser.UserName) .ToList();
-10441434 0 You haven't exactly defined how you want to use diagonal lines so you will have to write the final function as you need it, i suppose taking the path with shortest length of those that use diagonals, noting that path from a>c is shorter than path a>b>c for a,b,c in path
grid = [[False]*16 for i in range(16)] #mark grid of walls def rect(p1,p2): x1, y1 = p1 x2, y2 = p2 for x in range(x1, x2+1): for y in range(y1, y2+1): yield (x, y) rects = [((1,2),(5,5)), ((5,5),(14,15)), ((11,5),(11,11)), ((5,11),(11,11)), ((4,7),(5,13)), ((5,13),(13,13))] for p1,p2 in rects: for point in rect(p1,p2): x,y = point grid[x][y] = True start = (1,2) end = (12,13) assert(grid[start[0]][start[1]]) assert(grid[end[0]][end[1]]) def children(parent): x,y = parent surrounding_points = ((x1,y1) for x1 in range(x-1,x+2) for y1 in range(y-1,y+2) if x1>0 and y<15) for x,y in surrounding_points: if grid[x][y]: #not a wall grid[x][y] = False #set as wall since we have been there already yield x,y path = {} def bfs(fringe): if end in fringe: return new_fringe = [] for parent in fringe: for child in children(parent): path[child] = parent new_fringe.append(child) del fringe if new_fringe: bfs(new_fringe) bfs([start]) def unroll_path(node): if node != start: return unroll_path(path[node]) + [node] else: return [start] path = unroll_path(end) def get_final_path_length(path): #return length of path if using straight lines for i in range(len(path)): for j in range(i+1,len(path)): #if straight line between pathi and pathj return get_final_path(path[j+1:]) + distance_between_i_and_j
-22300705 0 You can edit output name from netbeans project
-22636707 0
- Right click on Library in netbeans
- Open Properties
- Build->Archiver->Output. At the end you will see name of lib (SomeName.a)
- Change it to suiltable name you need.
- Rebuild Project. You are good to go...
No, it's not possible. But you can add your feature request on JetBrains tracker: http://youtrack.jetbrains.com/issues/WI#newissue=yes
-14912924 0 identify a solid pattern to abstract a network layer to allow testabilityI've read various questions here on the argument like
How do you unit-test a TCP Server? Is it even worth it?
and others more specific questions as
Has anyone successfully mocked the Socket class in .NET?
rhino mocks: how to build a fake socket?
but I anyway feel to post the question.
I need to design an abstract network layer. It should be abstract to decouple consumer code from depending upon a specific implementation and, last but not least, be completely testable with fakes.
I'm ended up that I don't need to mock a Socket class, but rather define am higher level abstraction and mock it.
interface INetworkLayer { void OnConnect(Stream netwokStream); void OnException(Exception e); // doubts on this } Has anyone done something close to this that can provide observations, comments or explain how may look the right direction?
-25522969 0null and [] are both false, a shorter and cleaner way
ng-show="myData.Address"
-36840150 0 Hide the button that appears inside the chart
chart: { resetZoomButton: { theme: { display: 'none' } } } then use your own button:
$('#button2').click(function(){ chart.xAxis[0].setExtremes(Date.UTC(1970, 5, 9), Date.UTC(1971, 10, 9)); });
-11965812 0 You don't need to split anything, simply loop:
$.getJSON('data/data.json', function (ids) { for (var i = 0; i < ids.length; i++) { var id = ids[i]; console.log(id); } }); jQuery will automatically parse the string returned from the server as a javascript array so that you could directly access its elements.
You could split each element by the space if you want to retrieve the 2 tokens.
-5308595 0 SQL query (can include pl/sql bits) based on conditional countPremise: We've got a table with 5 fields. 2 fields are always unique.
What would be a good way to fulfill this:
if (count_of_result == 3) { add up the 3 rows from the same table. unique values get added up & the non-unique values are assumed to be same for all the 3 rows. the query result should show 1 row, with the values added up. } else {
display all the results of the query as usual.
}
Thank you.
-28931183 0Further messing around yielded the answer: xargs instead of a subshell:
echo \'foo bar\' \'baz quux\' | xargs /usr/bin/defaults write com.apple.systemuiserver menuExtras -array
-27302366 0 What you are looking for is UINavigationControllerDelegate.
I believe the method that gives you the message you need is
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated; And
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated; In your CustomViewController, you are going to want to conform to the UINavigationControllerDelegate protocol like this:
@interface CustomViewController : UIViewController <UINavigationControllerDelegate> And then override the delegate methods above to get the messages you are looking for.
Here is an complete implementation in Swift:
import UIKit class ViewController: UIViewController, UINavigationControllerDelegate { override func viewDidLoad() { super.viewDidLoad() navigationController?.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) { println(viewController) } } class FirstViewController: ViewController { } class SecondViewController: ViewController { }
-4827507 0 Did you change the SDK location? That may cause this issue.
If possible please post exact error message.
I developed an application. It loads sql database on my pc with this connection string:
Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Database\Books.mdf;Integrated Security=True;User Instance=True private void Window_Loaded(object sender, RoutedEventArgs e) { DataSet ds = new DataSet(); SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Database\Books.mdf;Integrated Security=True;User Instance=True"); SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = new SqlCommand("SELECT * FROM Lessons", con); da.Fill(ds); grdPersonnel1.DataContext = ds.Tables[0]; con.Open(); } but, my Database data doesn't load in another pc!
-37159943 0 How to perform heroku-like deployment on shared hosting?For our production server we use shared hosting. Until now, we were using FTP system to manually upload changes.
I am looking for a technique that lets me use git to push only changes from development to production server.
For my private projects I was using GitHub as development remote and Heroku as production remote. I am looking for something that can do similar thing without using Heroku itself. (note that we use shared hosting). I want to have two remotes, development (to development server) and production remote (from development server to production server). Idea is to push from development server to production server using git.
Projects are mostly written in PHP.
-5442611 0Try to read this articles:
Use RTTI for Dynamic Type Identification
-2844661 0Checkout the newest revision of the restored backup into a working copy. do an svn export of and old working copy and simply copy all files/folders onto the previously checkout working copy. Than do an svn add if needed and commit. This should summ all changes.
-32308650 0Likely, with iOS8, the path that you have saved won't be valid across launches.
The solution is to save the filename and not the complete path, and to recreate the URL or complete path, by getting the path to the Documents (or tmp) folder and appending the filename to it.
-21100155 0You need to make this operation optional if value is empty:
if value: data.append((next(value), value)) This change works for me:
if value: try: data.append(next(value), value) except StopIteration: pass
-40641967 0 Parallax Background in div of Content Is it possible to create a parallax background inside a div that has a certain width? Every tutorial I've seen has parallax backgrounds on full screen websites. My site is not full screen width, but I would still like to use the parallax effect within the content of my site. Obviously if I use the background-attachment: fixed; css property, the background becomes fixed to the body tag and not of the actual div.
To understand what I'm trying to do, you can look at this simple jsfiddle: http://jsfiddle.net/yh02y6dy/
//Parallax function simpleParallax() { //This variable is storing the distance scrolled var scrolled = $(window).scrollTop() + 1; //Every element with the class "scroll" will have parallax background //Change the "0.3" for adjusting scroll speed. $('.scroll').css('background-position', '0' + -(scrolled * 0.05) + 'px'); } //Everytime we scroll, it will fire the function $(window).scroll(function (e) { simpleParallax(); }); .scroll { /*Set a css background */ background:url(http://cdn.wallpapersafari.com/63/15/o20clA.jpg) fixed; width:600px; height:250px; line-height:300px; margin:0 auto; margin-top:150px; text-align:center; color:#fff; } body { min-height:3000px; } <div class="scroll"> <h1>Text on parralax background</h1> </div> You can see that the background image is fixed to the top left corner of the screen and not to the div. I want the background image to start where the div is starting.
I'm not opposed to using jquery if that is what's needed to make this work.
Thanks!
-21588596 0Try this:
tt <- c(0, 1, 2, 3, 4, 5, 1, 2, 3, 4, 1, 2, 3, 4, 5) grp <- cumsum(c(FALSE, diff(tt) < 0)) which gives:
> grp [1] 0 0 0 0 0 0 1 1 1 1 2 2 2 2 2
-33305397 0 Assuming you want to copy the values of the previous block when add button is clicked, you can do this:
$scope.cloneItem = function() { var food = $scope.foods[$scope.foods.length - 1]; var itemToClone = { "selectproduct": food.selectproduct, "Quantity1": food.Quantity1, "Quantity2": food.Quantity2 }; $scope.foods.push(itemToClone); }
-2739196 0 Login fails after upgrade to ASP.net 4.0 from 3.5 I cannot log in using any of the membership accounts using .net 4.0 version of the app. It fails like it's the wrong password, and FailedPasswordAttemptCount is incremented in my_aspnet_membership table. (I am using membership with mysql membership provider.)
I can create new users. They appear in the database. But I cannot log in using the new user credentials (yes, IsApproved is 1).
One clue is that the hashed passwords in the database is longer for the users created using the asp.net 4.0 version, e.g 3lwRden4e4Cm+cWVY/spa8oC3XGiKyQ2UWs5fxQ5l7g=, and the old .net 3.5 ones are all like +JQf1EcttK+3fZiFpbBANKVa92c=.
I can still log in when connecting to the same db with the .net 3.5 version, but only to the old accounts, not the new ones created with the .net 4.0 version. The 4.0 version cannot log in to any accounts.
I tried dropping the whole database on my test system, the membership tables are then auto created on first run, but it's still the same, can create users, but can't log in.
-25979700 0PayPal is actually better than most in terms of enabling you to do testing. There's a complete testing sandbox solution (support document), and when adding/editing your REST API application, you can click the "Edit" link next to "App Redirect URLs" and specify both a testing URL and live URL for production. That should give you everything you need to test locally without exposing your site to the outside world.
If it does end up giving you fits over using localhost, there's always services like localtest.me, that can let you get around it.
-39233034 0Well, I dont have a direct approach. But this hack should help you get what you want..
// Start the Browser As Process to start in Private mode Process browserProcess = new Process(); browserProcess.StartInfo.FileName = "iexplore.exe"; browserProcess.StartInfo.Arguments = "-private"; browserProcess.StartInfo.WindowStyle = ProcessWindowStyle.Maximized; // Start browser browserProcess.Start(); // Get Process (Browser) Handle Int64 browserHandle = browserProcess.Handle.ToInt64(); // Create a new Browser Instance & Assign the browser created as process using the window Handle BrowserWindow browserFormHandle = new BrowserWindow(); browserFormHandle.SearchProperties.Add(BrowserWindow.PropertyNames.WindowHandle, browserFormHandle.ToString()); browserFormHandle.NavigateToUrl(new Uri("http://www.google.com"));
-29356529 0 If you don't need it to undock and float then you can use a HeaderedContentControl.
When you want to add the close button you can template the header presenter to include a button.
-32738943 0 VB6 read barcode while program is running in backgroundi have a problem to make a program that can read Barcode. What i want to do is a program (maybe a service? i don't know) that can capture barcode from a barcode scanner while is running in background.
I have found that i can check if is plugged in a specific barcode scanner with his VID/PID, here some code:
Set wmi = GetObject("winmgmts://./root/cimv2") Dim VID As String Dim PID As String 'Barcode scanner VID = "VID_040B" PID = "PID_6510" 'REV = "REV_0120" For Each d In wmi.ExecQuery("SELECT * FROM Win32_USBControllerDevice") If InStr(d.Dependent, VID & "&" & PID) > 0 Then Debug.Print ("Barcode Scanner found it!") Debug.Print wmi.Get(d.Dependent).Description End If Next How can I do that is read by my program only the input of my barcode scanner?
Thank you in advance.
-5817142 0Exactly, UML class diagrams are just a notation that you could (and should) differently depending on the sofware development phase you are in. You can start with only classes, attributes and associations, then refine the diagram to add types information for the attributes, then navigation, class methods, qualifiers for associations ... until you get a complete class diagram ready for the implementation phase
Note that you could even iterate to the point in which you remove associations and replace them by attributes of complex types to have a class diagram even more similar to the final implementation. It's up to you how to use class diagrams in each phase.
-40989587 0If you use a val, you're not allowed to assign it a new value, so in your code example above, if you switch the third line with
val fa2 = fa.:+(ra) then fa can be a val.
-40810615 0ok, I got it working consistently between the two accounts and the key was to set the UseMachineKeyStore flag.
private static RSACryptoServiceProvider CreateRsaCypher(string containerName = DefaultContainerName) { // Create the CspParameters object and set the key container // name used to store the RSA key pair. CspParameters cp = new CspParameters(); cp.KeyContainerName = containerName; cp.Flags = CspProviderFlags.UseExistingKey | CspProviderFlags.UseMachineKeyStore; // Create a new instance of RSACryptoServiceProvider that accesses // the key container MyKeyContainerName. return new RSACryptoServiceProvider(cp); }
-6444612 0 width, height = im.size
According to the documentation.
-32933716 0NPE is because of the below reason
try { desktop.browse(uri); } catch(IOException ioe) { System.out.println("The system cannot find the " + uri + " file specified"); //ioe.printStackTrace(); } you are initializing desktop in DesktopDemo constructor but onLaunchBrowser() is a static method so desktop object is not instantiated!
-2996780 0The response from the SOAP interface is already parsed. The englighten() method returns an XML string. When you call it with SOAP, this response is wrapped within even more XML. The SOAP library already parses the outer SOAP XML and returns the result of the enlighten() method, which is also XML.
-26020180 0OK, I'm not going to try a fix your code. I'm just going to create constraints that I would use to achieve your layout. I'll put the thought process in comments.
First get a nice vertical layout going...
// I'm just using standard padding to make it easier to read. // Also, I'd avoid the variable padding stuff. Just set it to a fixed value. // i.e. ==padding not (>=0, <=padding). That's confusing to read and ambiguous. @"V:|-[titleLabel]-[ratingBubbleView]-[descriptionLabel]-|" Then go through layer by layer adding horizontal constraints...
// constraint the trailing edge too. You never know if you'll get a stupidly // long title. You want to stop it colliding with the end of the screen. // use >= here. The label will try to take it's intrinsic content size // i.e. the smallest size to fit the text. Until it can't and then it will // break it's content size to keep your >= constraint. @"|-[titleLabel]->=20-|" // when adding this you need the option "NSLayoutFormatAlignAllBottom". @"|-[ratingBubbleView]-[dateLabel]->=20-|" @"|-[descriptionLabel]-|" Try not to "over constrain" your view. In your code you are constraining the same views with multiple constraints (like descriptionLabel to the bottom of the superview).
Once they're defined they don't need to be defined again.
Again, with the padding. Just use padding rather than >=padding. Does >=20 mean 20, 21.5, or 320? The inequality is ambiguous when laying out.
Also, In my constraints I have used the layout option to constrain the vertical axis of the date label to the rating view. i.e. "Stay in line vertically with the rating view". Instead of constraining against the title label and stuff... This means I only need to define the position of that line of UI once.
-16122623 0If you want to run asynchronous process programmatically go for it. That is, use the lower level functions.
(set-process-sentinel (start-process "pdflatex" "*async pdflatex*" "pdflatex" filename) (lambda (process event) (cond ((string-match-p "finished" event) (kill-buffer "*async pdflatex*")) ((string-match-p "\\(exited\\|dumped\\)" event) (message "Something wrong happened while running pdflatex") (when (yes-or-no-p "Something wrong happened while running pdflatex, see the errors?") (switch-to-buffer "*async pdflatex*")))))) start-process starts a process asynchronously and set-process-sentinel defines the function triggered when the process status changes.
Well, for starters you'd have to avoid the client's navigation cache (often a back/forward doesn't actually pull the page back down).
After that hurdle you can look at (ironically) using a session variable to store if it's been viewed [output] and only dump it to the page once.
if that seems to much, you could just add a cookie check in the function so when it's run (and re-run) it checks for a cookie and, when absent, makes an alert and sets a cookie. Pseudocode:
function showAlert(msg){ if (cookie[msg] == null){ // a cookie doesn't exist for this msg alert(msg); // alert the msg cookie[msg] = true; // set the cookie so the next pass is ignored } }
-30012708 0 for data transfer you can use the library Emmet
https://github.com/florent37/emmet
We can imagine a protocol like this
public interface SmartphoneProtocole{ void getStringPreference(String key); void getBooleanPreference(String key); } public interface WearProtocole{ void onStringPreference(String key, String value); void onBooleanPreference(String key, boolean value); } wear/WearActivity.java
//access "MY_STRING" sharedpreference SmartphoneProtocole smartphoneProtocol = emmet.createSender(SmartphoneProtocole.class); emmet.createReceiver(WearProtocole.class, new WearProtocole(){ @Override void onStringPreference(String key, String value){ //use your received preference value } @Override void onBooleanPreference(String key, boolean value){ } }); smartphoneProtocol.getStringPreference("MY_STRING"); //request the "MY_STRING" sharedpreference mobile/WearService.java
final WearProtocole wearProtocol = emmet.createSender(WearProtocole.class); emmet.createReceiver(SmartphoneProtocol.class, new SmartphoneProtocol(){ //on received from wear @Override void getStringPreference(String key){ String value = //read the value from sharedpreferences wearProtocol.onStringPreference(key,value); //send to wear } @Override void getBooleanPreference(String key){ } });
-5415236 0 You can delete the files and/or directories prior to publishing like so:
<RemoveDir Directories="$(MyDirectory)" Condition="Exists('$(TempDirectory)')" /> <Delete Files="$(MyFiles)" Condition="Exists('$(MyFiles)')" />
-23446627 0 I did it. Thanks for your help
declare @name varchar(100) set @name='Sharma,Ravi,K' select CASE WHEN CHARINDEX(' ',REPLACE(@name,',',' '), CHARINDEX(' ',REPLACE(@name,',',' ')) + 1) >0 THEN SUBSTRING(REPLACE(@name,',',' '), CHARINDEX(' ',REPLACE(@name,',',' ')) + 1,(LEN(@name)-CHARINDEX(' ',REVERSE(REPLACE(@name,',',' '))))-CHARINDEX(' ',REPLACE(@name,',',' '))) else SUBSTRING(REPLACE(@name,',',' '), CHARINDEX(' ',REPLACE(@name,',',' ')) + 1,LEN(@name)) END AS 'FIRST NAME' ,CASE WHEN CHARINDEX(' ',REPLACE(@name,',',' '), CHARINDEX(' ',REPLACE(@name,',',' ')) + 1) >0 THEN SUBSTRING(REPLACE(@name,',',' '),LEN(@name)-CHARINDEX(' ',REVERSE(REPLACE(@name,',',' ')))+2,LEN(@name)) ELSE ' ' END AS 'MIDDLE NAME' , SUBSTRING(REPLACE(@name,',',' '), 1,CHARINDEX(' ',REPLACE(@name,',',' ')))
-18205592 0 When you do writeObject, the objevt you write needs to be Serializable. Try to change the signature of your copy-method to
public static Object copy(Serializable oldObj) The error message will be clearer.
-4170290 0 jQuery Templates and Razor?Can someone shed some light on how these compare/complement each other in the context of an ASP.NET MVC application?
-2894704 0The DataContext on your usercontrol isn't set. Specify a Name for it (I usually call mine "ThisControl") and modify the TextBox's binding to Text="{Binding ElementName=ThisControl, Path=TitleValue, Mode=TwoWay}". You can also set the DataContext explicitly, but I believe this is the preferred way.
It seems like the default DataContext should be "this", but by default, it's nothing.
[edit] You may also want to add , UpdateSourceTrigger=PropertyChanged to your binding, as by default TextBoxes' Text binding only updates when focus is lost.
i have following code
List<TimeZoneInfo> timeZoneList = new List<TimeZoneInfo>(TimeZoneInfo.GetSystemTimeZones()); timeZoneList.Sort((item1, item2) => { return string.Compare(item2.Id, item1.Id); }); but it does not sort the list correctly. (using linq.OrderBy() yields same result).
but the following code sorts correctly.
List<string> timeZoneList1 = new List<string>(); foreach (TimeZoneInfo timeZoneInfo in TimeZoneInfo.GetSystemTimeZones()) timeZoneList1.Add(timeZoneInfo.Id); timeZoneList1.Sort((item1, item2) => { return string.Compare(item1, item2); }); what is the problem? what do i missing?
really?
no one knows the answer?
--------------------------- EDIT ------------------------------------
where as i assign the list to a Combobox, it will appears in the wrong order but it will be fixed when i set the DisplayMember of the Combobox. can any one explain this behavior?
They are buffered, but I don't know on what level or what the limit is.
http://tangentsoft.net/wskfaq/ is a great resource you might find useful for any winsock related issue.
-2038527 0int* memory = NULL; memory = malloc(sizeof(int)); if (memory != NULL) { memory=10; free(memory); } This will crash. You're setting the pointer to memory location 10 and then asking the system to release the memory. It's extremely unlikely that you previously allocated some memory that happeneds to start at 0x10, even in the crazy world of virutal address spaces. Furthermore, IF malloc failed, no memory has been allocated, so you do not need to free it.
int* memory = NULL; memory = malloc(sizeof(int)); if (memory != NULL) { memory=10; } free(memory); This is also a bug. If malloc fails, then you are setting the pointer to 10 and freeing that memory. (as before.) If malloc succeeds, then you're immediately freeing the memory, which means it was pointless to allocate it! Now, I imagine this is just example code simplified to get the point across, and that this isn't present in your real program? :)
-15863381 0 django formset - not able to update entriesI want to update a formset that can have different entries. I will able to present the formset pre populated with the correct data, however I'm doing something wrong since it does not update but creates a new instance..
I'm seen inlineformset_factory however since I'm passing more than one value to the formset I was not able to work with it..
If anyone has any pointer I will truly appreciate it!
views.py
epis = Contact.objects.filter(episode=int(value)) ContactSet = formset_factory(Contact1Form, extra=len(epis), max_num=len(epis)) if request.method =='POST': formset = ContactSet(request.POST) if formset.is_valid(): for form in formset.forms: age = form.cleaned_data['age'] bcg = form.cleaned_data['bcg_scar'] radio = form.cleaned_data['radiology'] profile = form.save(commit=False) for i in epis: profile.contact = i fields = {'age': age, 'bcg_scar': bcg, 'radiology': radio} for key, value in fields.items(): if value == u'': setattr(profile, key, None) else: setattr(profile, key, value) profile.save() return render_to_response('success.html', {'location': location}) else: dic = [] for c in epis: aux = {} for f in c._meta.fields: if f.name not in ['contact_id', 'episode']: aux[f.name] = getattr(c, f.name) dic.append(aux) formset = ContactSet(initial=dic) return render_to_response('form.html', { 'msg': msg, 'location': location, 'formset': formset, 'word': word }) forms.py
class ContactForm(forms.ModelForm): affinity = forms.ModelChoiceField(queryset=Affinity.objects.all(), label=ugettext("Affinity")) age = forms.IntegerField(label=ugettext("Age when diagnosed"), required=False) MAYBECHOICES = ( ('', '---------'), (ugettext('Yes'), ugettext('Yes')), (ugettext('No'), ugettext('No'))) bcg_scar = forms.ChoiceField(choices=MAYBECHOICES, label=ugettext( "BCG scar"), required=False) radiology = forms.ModelChoiceField(queryset=Radiology.objects.all(), label=ugettext("Radiology"),required=False) class Meta: model = Contact Any pointers would be of great help!
EDIT
After some suggestions from Catherine
formset = ContactSet(request.POST, queryset=epis) which gave me this error:
__init__() got an unexpected keyword argument 'queryset' I try changing
from django.forms.models import modelformset_factory ContactSet = modelformset_factory(Contact1Form, extra=len(epis), max_num=len(epis)) and this error appeared:
'ModelFormOptions' object has no attribute 'many_to_many' and then saw that to solve this error I will need to use the name of the model instead.
ContactSet = modelformset_factory(Contact, extra=len(epis), max_num=len(epis)) and I get a MultiValueDictKeyError
-40025364 0 Cannot perform LINQ complex object search in Entity FrameworkI have entities in the DB which each contain a list of key value pairs as metadata. I want to return a list of object by matching on specified items in the metadata.
Ie if objects can have metadata of KeyOne, KeyTwo and KeyThree, I want to be able to say "Bring me back all objects where KeyOne contains "abc" and KeyThree contains "de"
This is my C# query
var objects = repository.GetObjects().Where(t => request.SearchFilters.All(f => t.ObjectChild.Any(tt => tt.MetaDataPairs.Any(md => md.Key.ToLower() == f.Key.ToLower() && md.Value.ToLower().Contains(f.Value.ToLower()) ) ) ) ).ToList(); and this is my request class
[DataContract] public class FindObjectRequest { [DataMember] public IDictionary<string, string> SearchFilters { get; set; } } And lastly my Metadata POCO
[Table("MetaDataPair")] public class DbMetaDataPair : IEntityComparable<DbMetaDataPair> { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public long Id { get; set; } [Required] public string Key { get; set; } public string Value { get; set; } } The error I get is
-16783675 0 Running Continumm StandaloneError was Unable to create a constant value of type 'System.Collections.Generic.KeyValuePair`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'. Only primitive types or enumeration types are supported in this context.
I have downloaded apache continuum.
After that i unpacked and i typed continuun console.
It´s started fine... but when i put localhost:8080/continuum in the browser the console show this error: What´s happend?
jvm 1 | org.apache.jasper.JasperException: PWC6345: There is an error in invo king javac. A full JDK (not just JRE) is required jvm 1 | at org.apache.jasper.compiler.DefaultErrorHandler.jspError(Defau ltErrorHandler.java:92) jvm 1 | at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDisp atcher.java:378) jvm 1 | at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDisp atcher.java:119) jvm 1 | at org.apache.jasper.compiler.Jsr199JavaCompiler.compile(Jsr199J avaCompiler.java:208) jvm 1 | at org.apache.jasper.compiler.Compiler.generateClass(Compiler.ja va:384) jvm 1 | at org.apache.jasper.compiler.Compiler.compile(Compiler.java:453 ) jvm 1 | at org.apache.jasper.JspCompilationContext.compile(JspCompilatio nContext.java:625) jvm 1 | at org.apache.jasper.servlet.JspServletWrapper.service(JspServle tWrapper.java:374) jvm 1 | at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServle t.java:492) jvm 1 | at org.apache.jasper.servlet.JspServlet.service(JspServlet.java: 378) jvm 1 | at javax.servlet.http.HttpServlet.service(HttpServlet.java:848) jvm 1 | at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder. java:648) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHand ler.java:455) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:137) jvm 1 | at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHan dler.java:577) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doHandle(Sess ionHandler.java:231) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doHandle(Cont extHandler.java:1072) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandl er.java:382) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doScope(Sessi onHandler.java:193) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doScope(Conte xtHandler.java:1006) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:135) jvm 1 | at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:2 76) jvm 1 | at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:1 03) jvm 1 | at org.eclipse.jetty.servlet.DefaultServlet.doGet(DefaultServlet .java:566) jvm 1 | at javax.servlet.http.HttpServlet.service(HttpServlet.java:735) jvm 1 | at javax.servlet.http.HttpServlet.service(HttpServlet.java:848) jvm 1 | at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder. java:648) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter (ServletHandler.java:1336) jvm 1 | at org.apache.struts2.dispatcher.ng.filter.StrutsExecuteFilter.d oFilter(StrutsExecuteFilter.java:85) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter (ServletHandler.java:1307) jvm 1 | at com.opensymphony.sitemesh.webapp.SiteMeshFilter.obtainContent (SiteMeshFilter.java:129) jvm 1 | at com.opensymphony.sitemesh.webapp.SiteMeshFilter.doFilter(Site MeshFilter.java:77) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter (ServletHandler.java:1307) jvm 1 | at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareFilter.d oFilter(StrutsPrepareFilter.java:82) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter (ServletHandler.java:1307) jvm 1 | at org.springframework.web.filter.CharacterEncodingFilter.doFilt erInternal(CharacterEncodingFilter.java:96) jvm 1 | at org.springframework.web.filter.OncePerRequestFilter.doFilter( OncePerRequestFilter.java:76) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter (ServletHandler.java:1307) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHand ler.java:453) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:137) jvm 1 | at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHan dler.java:559) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doHandle(Sess ionHandler.java:231) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doHandle(Cont extHandler.java:1072) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandl er.java:382) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doScope(Sessi onHandler.java:193) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doScope(Conte xtHandler.java:1006) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:135) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandlerCollection.han dle(ContextHandlerCollection.java:255) jvm 1 | at org.eclipse.jetty.server.handler.HandlerCollection.handle(Han dlerCollection.java:154) jvm 1 | at org.eclipse.jetty.server.handler.HandlerWrapper.handle(Handle rWrapper.java:116) jvm 1 | at org.eclipse.jetty.server.Server.handle(Server.java:365) jvm 1 | at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest (AbstractHttpConnection.java:485) jvm 1 | at org.eclipse.jetty.server.AbstractHttpConnection.headerComplet e(AbstractHttpConnection.java:926) jvm 1 | at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandle r.headerComplete(AbstractHttpConnection.java:988) jvm 1 | at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:6 35) jvm 1 | at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.j ava:235) jvm 1 | at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttp Connection.java:82) jvm 1 | at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectC hannelEndPoint.java:627) jvm 1 | at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectCh annelEndPoint.java:51) jvm 1 | at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedT hreadPool.java:608) jvm 1 | at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedTh readPool.java:543) jvm 1 | at java.lang.Thread.run(Unknown Source) jvm 1 | 2013-05-27 23:52:11.265:WARN:oejs.ErrorPageErrorHandler:EXCEPTION jvm 1 | org.apache.jasper.JasperException: PWC6345: There is an error in invo king javac. A full JDK (not just JRE) is required jvm 1 | at org.apache.jasper.compiler.DefaultErrorHandler.jspError(Defau ltErrorHandler.java:92) jvm 1 | at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDisp atcher.java:378) jvm 1 | at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDisp atcher.java:119) jvm 1 | at org.apache.jasper.compiler.Jsr199JavaCompiler.compile(Jsr199J avaCompiler.java:208) jvm 1 | at org.apache.jasper.compiler.Compiler.generateClass(Compiler.ja va:384) jvm 1 | at org.apache.jasper.compiler.Compiler.compile(Compiler.java:453 ) jvm 1 | at org.apache.jasper.JspCompilationContext.compile(JspCompilatio nContext.java:625) jvm 1 | at org.apache.jasper.servlet.JspServletWrapper.service(JspServle tWrapper.java:374) jvm 1 | at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServle t.java:492) jvm 1 | at org.apache.jasper.servlet.JspServlet.service(JspServlet.java: 378) jvm 1 | at javax.servlet.http.HttpServlet.service(HttpServlet.java:848) jvm 1 | at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder. java:648) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHand ler.java:455) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:137) jvm 1 | at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHan dler.java:577) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doHandle(Sess ionHandler.java:231) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doHandle(Cont extHandler.java:1072) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandl er.java:382) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doScope(Sessi onHandler.java:193) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doScope(Conte xtHandler.java:1006) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:135) jvm 1 | at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:2 76) jvm 1 | at org.eclipse.jetty.server.Dispatcher.error(Dispatcher.java:112 ) jvm 1 | at org.eclipse.jetty.servlet.ErrorPageErrorHandler.handle(ErrorP ageErrorHandler.java:136) jvm 1 | at org.eclipse.jetty.server.Response.sendError(Response.java:348 ) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHand ler.java:538) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:137) jvm 1 | at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHan dler.java:559) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doHandle(Sess ionHandler.java:231) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doHandle(Cont extHandler.java:1072) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandl er.java:382) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doScope(Sessi onHandler.java:193) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doScope(Conte xtHandler.java:1006) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:135) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandlerCollection.han dle(ContextHandlerCollection.java:255) jvm 1 | at org.eclipse.jetty.server.handler.HandlerCollection.handle(Han dlerCollection.java:154) jvm 1 | at org.eclipse.jetty.server.handler.HandlerWrapper.handle(Handle rWrapper.java:116) jvm 1 | at org.eclipse.jetty.server.Server.handle(Server.java:365) jvm 1 | at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest (AbstractHttpConnection.java:485) jvm 1 | at org.eclipse.jetty.server.AbstractHttpConnection.headerComplet e(AbstractHttpConnection.java:926) jvm 1 | at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandle r.headerComplete(AbstractHttpConnection.java:988) jvm 1 | at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:6 35) jvm 1 | at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.j ava:235) jvm 1 | at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttp Connection.java:82) jvm 1 | at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectC hannelEndPoint.java:627) jvm 1 | at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectCh annelEndPoint.java:51) jvm 1 | at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedT hreadPool.java:608) jvm 1 | at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedTh readPool.java:543) jvm 1 | at java.lang.Thread.run(Unknown Source)
-9043173 0 MIniMagick::Image.write() saves files with varying permissions I am writing a little photo gallery with Rails 3.0.11 and MiniMagick.
def JadeImage.rescale path,new_path,max_height=150 image = MiniMagick::Image.open(path) image.adaptive_resize(self.resize(image[:height],max_height))if image[:height] > max_height image.write(new_path) end I am using this to save two resized images from the same photo. One of the files gets saved with 644 permissions and all is right in the world. The other always get saved as 600 and as such can't be displayed in the webpage.
For now, after saving them, I run a little utility to set everything in that directory as 644 so it works now.
Is there any reason why this would occur?
-8494204 0what about checking the referral ? are you using php ?, if yes the you can try using refferal instead, like
if($_SERVER[’HTTP_REFERER’]!=''){ echo "<script> $(function(){ $.ajax({ type: 'POST', url: this.href, success: updatePortslide, dataType: 'json', data: 'js=2' }); return false; }); </script>"; }
-9569438 0 This is an example of code that works for me. It performs these operations:
If the current element is a number, then this element and the next element (the city) is stored on an ArrayList.
import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.*; public class split{ private List<String> newline = new ArrayList<String>(); public split(){ String myString = "Graaf Karel De Goedelaan 1 8500 Kortrijk"; String array[] = myString.split("\\s+"); for(int z = 0;z<arr.length;z++){ int sizestr = array[z].length(); if(sizestr==4){/* if the generic string has 4 characters */ String expression = "[0-9]*"; CharSequence inputStr = array[z]; Pattern pattern = Pattern.compile(expression); Matcher matcher = pattern.matcher(inputStr); if(matcher.matches()){/* then if the string has 4 numbers, we have the postal code" */ newline.add(array[z]); /* now we add the postal code and the next element to an array list" */ newline.add(array[z+1]); } } } Iterator<String> itr = newline.iterator(); while (itr.hasNext()) { String element = itr.next(); System.out.println(element); /* prints "8500" and "Kortrijk" */ } } public static void main(String args[]){ split s = new split(); } } For further info about the check of the string, take a look to this page, and, for the ArrayList Iterator, see this.
I hope this can help to solve your problem.
-19628498 0If its Real device we can not See Data folder inside data
but if its Emulator
Go to
data>data> Search for your package name>database>yourdatabse.db

enter image description here
Search your package name. Then inside database folder yourdatabse.db will be created.
-26038374 0You can make change in below css
.content { margin-top:50px;//added position:absolute;//changed clear: both; width:100px; height:50px; background:#D52100; } .click_menu{ width:100px; height:50px; float:left; color:#191919; text-align:center; position: absolute;// added z-index: 100;//added }
-7388567 0 Some responders have suggested storing the data in ViewState. While this is custom in ASP.NET you need to make sure that you absolutely understand the implications if you want to go down that route, as it can really hurt performance. To this end I would recommend reading TRULY understanding ViewState.
Usually, storing datasets retrieved from the database in ViewState really hurts performance. Without knowing the details of your situation I would hazard a guess that you are better off just loading the data from the database on every request. Essentially, you have the option of a) serializing the data and sending the data to the client (who could be on a slow connection) or b) retrieving the data from the database, which is optimized for data retrieval and clever caching.
-34241578 0Same problem here
$ mysqldump -h localhost --lock-all-tables --set-gtid-purged=OFF -u root -p --socket=/var/run/mysqld/mysqld.sock --all-databases > dump.sql mysqldump: Couldn't execute 'SHOW VARIABLES LIKE 'ndbinfo\_version'': Native table 'performance_schema'.'session_variables' has the wrong structure (1682) Have you test a
$ mysql_upgrade -u root -p or
$ mysql_upgrade --force -u root -p
-24246562 0 How to migrate S3 bucket to another account I need to move data from an S3 bucket to another bucket, on a different account. I was able to sync buckets by running:
aws s3 sync s3://my_old_bucket s3://my_new_bucket --profile myprofile myprofile contents:
[profile myprofile] aws_access_key_id = old_account_key_id aws_secret_access_key = old_account_secret_access_key I have also set policies both on origin and destination. Origins allows listing and getting, and destination allows posting.
The commands works perfectly and I can log in to the other account and see the files. But I can't take ownership or make the new bucket public. I need to be able to make changes as I was able to in the old account. New account is totally unrelated to new account. It looks like files are retaining permissions and they are still owned by the old account.
How can I set permissions in order to gain full access to files with the new account?
-38934847 0The line of code num1, num2 = num2, (num1 + num2) is assigning two variables at once. num1 gets the old value of num2, while num2 gets the new value (num1 + num2).
Having multiple assignments on a single line of code allows you to do both operations without needing to use a temporary variable. For example, this won't work:
num1 = num2 num2 = (num1 + num2) because num1 has been overwritten with a new value before the addition step, so num2 will be assigned the wrong value. The one-line version is equivalent to:
temp = (num1 + num2) num1 = num2 num2 = temp For reference, this is called parallel assignment or sometimes multiple assignment.
-23991717 0 Horizontal lines in errorbars disappearingI'm having some troubles with errorbars in ggplot (R) similar to this problem in Python. My horizontal errobars are disappearing when using the scale_y function. Can you help me find a solution? The data is here.
My code is:
data_sac_ggplot <- ggplot(yeast_sac, aes(x=factor(day), y=mean_count, colour=yeastsample, group=c("low","high"))) + scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x), labels = trans_format("log10", math_format(10^.x))) + geom_line(size=0.8) + geom_point(size=2, shape=21, fill="white") + theme_bw() data_sac_ggplot + geom_errorbar(aes(ymin=mean_count-low, ymax=mean_count+high), width=0.1, position=pd) data_sac_ggplot + scale_y_log10(breaks=c(1000,10000,100000,1000000,10000000,100000000,1000000000)) Thanks!
-23051546 0 Chromecast Chrome API - senderIdThe receiver adds a senderId to each message it receives. Is the sender aware of that id? Where can it be found? That would help greatly during development.
-17099774 0Try this:
String strEvents = new JSONArray(apiResponse).getJSONObject(0).toString(); String strVenues= new JSONArray(apiResponse).getJSONObject(1).toString(); jsonArray = new JSONObject(strEvents).getJSONArray("fql_result_set"); jsonVenues = new JSONObject(strVenues).getJSONArray("fql_result_set");
-4159189 0 Rails Bundler on windows refuses to install hpricot (even on manual gem install get Error: no such file to load -- hpricot) Upgraded to rails 3, and using Bundler for gems, in a mixed platform development group. I am on Windows. When I run Bundle Install it completes succesfully but will not install hpricot. The hpricot line is:
gem "hpricot", "0.8.3", :platform => :mswin also tried
gem "hpricot", :platform => :mswin Both complete fine but when I try to do a "bundle show hpricot" I get:
Could not find gem 'hpricot' in the current bundle. If I do a run a rails console and try "require 'hpricot'" I get:
LoadError: no such file to load -- hpricot I have manually installed hpricot as well, and still get the above error. This worked fine before moving to rails 3.
-28117005 0 How can I tail -f but only in whole lines?I have a constantly updating huge log file (MainLog).
I want to create another file which is only the last n lines of the log file BUT also updating.
If I use:
tail -f MainLog > RecentLog
I get ALMOST what I want except RecentLog is written as MainLog is available and might at any point only have part of the last MainLog line.
How can I specify to tail that I only want it to write when a WHOLE line is available?
-3477306 0you left out a for(;true;) loop
-37612974 0I've spent two days fighting with it. Adding "*" namespace to xPath solved the issue for me (my input file did not have any).
return <label>{fn:doc(fn:concat($collection, '/', $child))//*:testResult/text()}</label>
-5958423 0 I had the same problem and resolved it by updating to the latest jQuery (1.6) and jQuery.validate (1.8) libraries. The easiest way to get these is searching NuGet for jQuery.
-826228 0Use JConsole-- you likely already have it: http://java.sun.com/j2se/1.5.0/docs/guide/management/jconsole.html http://openjdk.java.net/tools/svc/jconsole/
-39643679 0var orders = JSON.parse($('#orderData')); console.log(orders[0].value);
-19823386 0 Cant push to stack, mips I am just trying to print this 'a' to screen, but by first pushing to stack so that I can check whether I did accomplish on pushing to stack or not, seems that I couldn't because it prints a weird character everytime. What's wrong?
.data char: .word 'a' .text .globl main main: la $t0, char sub $sp, $sp, 4 #allocate byte for stack sb $t0, 0($sp) #push to stack la $t1, 0($sp) #I wasnt able to print the top of the stack directly so I tried this li $v0, 11 la $a0, 0($t1) #It isnt working anyway.. Prints É syscall add $sp, $sp, 4 jr $ra
-3092562 0 A couple of ways:
In your web.config on the customErrors mode set the redirectMode to ResponseRewrite - this removes the 302 redirect from the server to the error page - this also has the happy coincidence that uses can easily see what the original page they requested was, and can retry with an F5 if that's likely to resolve the issue.
If you are hooking into the ApplicationError event, make sure that rather than redirecting to your error pages you use Server.Transfer instead.
I have the following in one of my web.configs:
<customErrors mode="On" defaultRedirect="ErrorHandler.aspx" redirectMode="ResponseRewrite"> Then in my ErrorHandler page I check for the last error from the server, and configure those:
var serverError = Server.GetLastError(); var error = serverError as HttpException; int errorCode; string errorMessage; if (null != error) { errorCode = error.GetHttpCode(); errorMessage = error.GetHtmlErrorMessage(); } else { errorCode = 404; errorMessage = "Page not found"; } Response.StatusCode = errorCode; Response.StatusDescription = errorMessage; Obviously you may want to do additional processing - for example before I do all this I'm comparing the original request with my Redirects database to check for moved content/vanity urls, and only falling back to this if I couldn't find a suitable redirect.
-41068081 0UserDefaults is just a bunch of pairs of keys and values. So, you could assign a boolean value ("hidden") for each product:
// get the current product - this depends on how your table is set up let product = products[indexPath.row] // set the boolean to true for this product UserDefaults.set(true, forKey: product) Then, wherever you're initializing your products, add:
// only include elements that should not be hidden products = products.filter({ UserDefaults.boolForKey($0) == false }) You could also store all of the
-32426365 0Your first script seems to work just fine with the latest Unicode version of AutoHotkey. Get latest version @ ahkscript.org
Added a check for "ы" in the code below:
~LWin Up:: Input, key, L1 if (key = "n" or key = "ы") { Run, Notepad.exe } else if (key = "s") { Run, cmd.exe } return Make sure to Encode your with script UTF-8 (not UTF-8 without BOM)
Edit:
Okay I think I found an Answer that doesn't require you to Add "ы" but instead relies on SC codes produced by the Keyboard, meaning it's Layout independent.
Relevant info from Input command from the Docs:
E [v1.1.20+]: Handle single-character end keys by character code instead of by keycode. This provides more consistent results if the active window's keyboard layout is different to the script's keyboard layout. It also prevents key combinations which don't actually produce the given end characters from ending input; for example, if @ is an end key, on the US layout Shift+2 will trigger it but Ctrl+Shift+2 will not (if the E option is used). If the C option is also used, the end character is case-sensitive.
EndKeys A list of zero or more keys, any one of which terminates the Input when pressed (the EndKey itself is not written to OutputVar). When an Input is terminated this way, ErrorLevel is set to the word EndKey followed by a colon and the name of the EndKey. Examples: EndKey:., EndKey:Escape.
The EndKey list uses a format similar to the Send command. For example, specifying {Enter}.{Esc} would cause either ENTER, period (.), or ESCAPE to terminate the Input. To use the braces themselves as end keys, specify {{} and/or {}}.
To use Control, Alt, or Shift as end-keys, specify the left and/or right version of the key, not the neutral version. For example, specify {LControl}{RControl} rather than {Control}.
Although modified keys such as Control-C (^c) are not supported, certain characters that require the shift key to be held down -- namely punctuation marks such as ?!:@&{} -- are supported in v1.0.14+. Other characters are supported with the E option described above, in v1.1.20+.
An explicit virtual key code such as {vkFF} may also be specified. This is useful in the rare case where a key has no name and produces no visible character when pressed. Its virtual key code can be determined by following the steps at the bottom fo the key list page.
~LWin Up:: Input, key, L1 E, {SC031}.{SC01F} ; {n}.{s} if (Errorlevel = "EndKey:SC031") { Run, Notepad.exe } If (Errorlevel = "EndKey:SC01f") { Run, cmd.exe } return Also, I wasn't able to reproduce an issue where Windows key was held down?
-3195918 0You can't prevent the user from switching back because you've spawned a separate process. As far as the operating system is concerned it's as if you'd started the second one via it's desktop icon (for example).
I think the best you can hope for is to disable the relevant menus/options when the second process is active. You'll need to keep polling to see if it's still alive, otherwise your main application will become unusable.
Another approach might be to minimize the main application which will keep it out of the way.
-7061264 0 Access a flash object from jQueryI am using swfobject 2 to dynamically embed my flash... let's call my object "swfContent"
I have tried to use $('swfContent') and $("#swfContent") to access my swf object, but no luck.
Thanks!
-25130414 0 not being able to set the n° of specified threads desiredI have this very simple openmp program that is not creating the four desired threads, #include #include
main () { omp_set_num_threads(4); #pragma omp paralel { int id = omp_get_thread_num(); int nt = omp_get_num_threads(); printf ("I am thread %d of %d threads\n",id,nt); } When I run it the command line says the total it is 1. What am I forgetting?
-3761428 0Since you're asking for the best way, and if Log4J is not a strong requirement, my suggestion would be to use Logback and its DbAppender. That's the best way :)
Last time I checked, the JDBCAppender from Log4J was still not satisfying and if you can't use logback, you might prefer some third party implementation. See the links below for details:
for (CNContact *contact in contacts) { if (!contacts) { contacts = [[NSMutableArray alloc] init]; if ( contact.imageData != nil ) { // iOS >= 4.1 UIImage *CIMage = [UIImage imageWithData:(NSData *)contact.imageData]; } } NSString *string = [formatter stringFromContact:contact]; NSLog(@"contact = %@", string); [contacts addObject:string]; } // Please this code is run in my app please try it.
-15831268 0 There is a "cacheDirectory" in your "data/package_name" directory.
If you want to store something in that cache memory,
File cacheDir = new File(this.getCacheDir(), "temp"); if (!cacheDir.exists()) cacheDir.mkdir(); where this is context.
-20014292 0 Chain an additional order on a Rails activerecord query?Activerecord seems to ignore my second order in a chained AR query.
What I'm trying to do is retrieve the top 5 most-read articles within the top 25 highest-scored (eg. rated by users) articles.
Article has both read_count (integer) and score (float) columns that I order by.
My (naive?) attempt was this query:
Article.order("score DESC").limit(25).order("read_count DESC").limit(5) What this returns is simply the first 5 highest-scored articles, rather than the 5 most-read articles within the first 25 highest-scored.
Can I do this in a single query? Thanks for any help!
(I'm on Rails 3.2 and Postgres 9.2)
Addendum
Thank you to brad and Philip Hallstrom for two solutions to this. Either would have been acceptable, although I went with brad's database-only solution as explained in my comment on his answer.
Profiling each query on my local development machine (MBA) showed the subquery solution to be 33% faster than the Ruby-loop solution. Profiling the queries on my production machine (Heroku + Crane production database) showed the subquery solution to be 95% faster! (this is across a database of 40,000 articles).
While the actual time taken is pretty insignificant, 95% faster and 50% fewer lines of code is a pretty good decider.
Ruby-loop solution: (Philip) dev: 24 msec prod: 16 msec Sub-query solution: (brad) dev: 22 msec prod: 0.9 msec Thanks to both Philip and brad for their answers!
-25821688 0 Swift generic Function (n choose k)I'm trying to make this JavaScript code in Swift: k_combinations
And so far i have this in Swift:
import Foundation import Cocoa extension Array { func slice(args: Int...) -> Array { var s = args[0] var e = self.count - 1 if args.count > 1 { e = args[1] } if e < 0 { e += self.count } if s < 0 { s += self.count } let count = (s < e ? e-s : s-e)+1 let inc = s < e ? 1 : -1 var ret = Array() var idx = s for var i=0;i<count;i++ { ret.append(self[idx]) idx += inc } return ret } } func kombinaatiot<T>(setti: Array<T>, k: Int) -> Array<Array<T>> { var i: Int, j: Int if (k > setti.count || k <= 0) { return [] } if (k == setti.count) { return [setti] } if (k == 1) { var combs: Array<T> = [] for var i = 0; i < setti.count; i++ { combs += [setti[i]] } return [combs] } var combs: Array<Array<T>> = [[]] for var i = 0; i < setti.count - k + 1; i++ { var head = setti.slice(i,i + 1) var tailcombs = kombinaatiot(setti.slice(i + 1), k - 1) for var j = 0; j < tailcombs.count; j++ { combs += ([head + tailcombs[j]]) } } println(combs) return combs } But problem is that my function prints
[[], [1, 2, 2, 3, 4], [2, 3, 3, 4], [3, 4, 4]] when it should print
[[1,2], [1,3], [2, 3] What i'm doing wrong here? Im noobie at coding, and my javascript skills aren't very well, but that javascript worked for me, but in swift i can't make that work.
-38889709 0 Redirect to another route when `mapHooks` failsI have defined following mapHooks:
const mapHooks = { fetch: ({ dispatch, params }) => dispatch(fetchPost(params.postId)).catch(() => { console.log('catch'); }), }; Sometimes, post cannot be found and I'd like to redirect user to the another page. When I catch the error I tried to call push('/foo') to redirect to /foo page, but it does nothing (push comes from react-router-redux.
How can I redirect user properly ?
-30184152 0You can achieve this by specifying things you want to show on card in cardConfig
cardConfig: { fields: [ 'Name', 'TestCases', 'c_StoryType', 'Children', 'c_TargetRelease', 'PlanEstimate' { name: 'Children', renderer: this._renderChildStories }, ], } and then define _renderChildStories function, I thing value will be a collection of child stories, so you can loop that depending upon the val value
_renderChildStories: function(val) { var store = Ext.create('Rally.data.custom.Store',{ data: [ { 'FormattedID': val.get('FormattedID'), 'Name': val.get('Name') } ] }); return store }
-8334422 0 I would personally use an interface as suggested, but in case you didn't have access to who is calling you (such as third party .dll) then you can accept an argument of type object:
/// <summary> /// Draw any type of object if the objec type is supported. /// Circles, Squares, etc. /// </summary> /// <param name="objectToDraw"></param> public void Draw(object objectToDraw) { // get the type of object string type = objectToDraw.GetType().ToString(); switch(type) { case "Circle": // cast the objectToDraw as a Circle Circle circle = objectToDraw as Circle; // if the cast was successful if (circle != null) { // draw the circle circle.Draw(); } // required break; case "Square": // cast the object as a square Square square = objectToDraw as Square; // if the square exists if (square != null) { // draw the square square.Draw(); } // required break; default: // raise an error throw new Exception("Object Type Not Supported in Draw method"); } }
-22092822 0 There is no official release of OpenCV for system without OS. OpenCV library is available for Windows, linux, mac, Android and Ios operating system.
Here you can find a link which explain the challenges of having OpenCV running on microcontrollers
-26008034 0 How to customise the php script so that the feedback is exactly the same as the user have typed out in a form?Does anyone have any idea how to customize the php page so that the user can see a feedback of what he has already filled in? I noticed many php scripts have a 'thank you' feedback but I want more than that. The codes for the php as shown below :
<?php if(isset($_POST['email'])) { // EDIT THE 2 LINES BELOW AS REQUIRED $email_to = "james@ace.com.sg"; $email_subject = "Photography Courses that I want to sign up"; function died($error) { // your error code can go here echo "We are very sorry, but there were error(s) found with the form you submitted. "; echo "These errors appear below.<br /><br />"; echo $error."<br /><br />"; echo "Please go back and fix these errors.<br /><br />"; die(); } // validation expected data exists if(!isset($_POST['name']) || !isset($_POST['email']) || !isset($_POST['tel']) || /*!isset($_POST['basic']) || !isset($_POST['advanced']) || !isset($_POST['raw']) || !isset($_POST['lightroom']) ||*/ !isset($_POST['comments'])) { died('We are sorry, but there appears to be a problem with the form you submitted.'); } $name = $_POST['name']; // required $email_from = $_POST['email']; // required $telephone = $_POST['tel']; // required $basic = $_POST['basic']; // not required $advanced = $_POST['advanced']; // not required $raw = $_POST['raw']; // not required $lightroom = $_POST['lightroom']; // not required $comments = $_POST['comments']; // not required $error_message = ""; $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/'; $string_exp = "/^[A-Za-z .'-]+$/"; if(!preg_match($string_exp,$name)) { $error_message .= 'The Name you entered does not appear to be valid.<br />'; } if(!preg_match($email_exp,$email_from)) { $error_message .= 'The Email Address you entered does not appear to be valid.<br />'; } /*if(!preg_match($string_exp,$telephone)) { $error_message .= 'You need to insert the telephone number.<br />'; }*/ /* if(strlen($comments) < 2) { $error_message .= 'Insufficient Words for comments! <br />'; }*/ if(strlen($error_message) > 0) { died($error_message); } $email_message = "Form details below.\n\n"; function clean_string($string) { $bad = array("content-type","bcc:","to:","cc:","href"); return str_replace($bad,"",$string); } $email_message .= "\n Name: ".clean_string($name)."\n\n"; $email_message .= "Email: ".clean_string($email_from)."\n\n"; $email_message .= "Telephone: ".clean_string($telephone)."\n\n"; $email_message .= "Courses Taking: \n\n".clean_string($basic)."\n\n" .clean_string($advanced)."\n\n" .clean_string($raw)."\n\n" .clean_string($lightroom)."\n\n"; $email_message .= "Comments: ".clean_string($comments)."\n\n"; // create email headers $headers = 'From: '.$email_from."\r\n". 'Reply-To: '.$email_from."\r\n" . 'X-Mailer: PHP/' . phpversion(); @mail($email_to, $email_subject, $email_message, $headers); ?> <!-- include your own success html here --> <?php echo '<h2>Thanks for filling up this form, We will get back to you by next Monday (29 Sep). Have a terrific weekend!</h2>'; echo '<p>**How do I feedback of what the user has already filled in the form here?** </p>'; ?> <?php $redirect = 'http://www.acetraining.com.sg'; ?> <?php } ?> <SCRIPT LANGUAGE="JavaScript"> redirTime = "4000"; redirURL = "<?php echo $redirect ?>"; function redirTimer() { self.setTimeout("self.location.href=redirURL;",redirTime);} </script> <BODY onLoad="redirTimer()"> Thanks!
-33968920 0 postgres database : Insufficient privilege, permission denied for relation tableI have been using the postgres database on heroku for a while. and suddenly I had some problems on saving to database I got this error all the time
Insufficient privilege, permission denied for relation table its a problem of user permission , but I'm confused why it happened , because it was working correctly before
-1469564 0The character array contains executable code and the cast is a function cast.
(*(void(*) ()) means "cast to a function pointer that produces void, i.e. nothing. The () after the name is the function call operator.
I am trying to get a regular expression pattern to implement a shortcode feature in Joomla CMS, using plugins, similar to WordPress.
The shortcode may be a self closing one like {myshortcode shortcode="codeone"} at some occassions and may be an enclosed ones like:
{myshortcode shortcode="anothercode"|param="test"} {column}column 1{/column} {/myshortcode} I managed to figure out the regular expression used in WordPress:
{(}?)(myshortcode)(?![\w-])([^}\/]*(?:\/(?!})[^}\/]*)*?)(?:(\/)}|}(?:([^{]*+(?:{(?!\/\2})[^{]*+)*+){\/\2})?)(}?) This is working fine if the content contains one or more self closing shortcodes, or one or more of the enclosed shortcodes. But if the content contains a mixture of both, it won't work.
Instead of using the square brackets [], I am using the curly braces {}, as this is how content plugins are used in Joomla.
Now please check the below HTML snippet:
<div id="lipsum"> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin pellentesque lectus tellus, ut tincidunt orci posuere non. Aliquam erat volutpat. Phasellus in lobortis dolor, porta varius nunc. Ut et felis rutrum, pharetra mi a, ullamcorper purus. In vitae fringilla velit. In nec scelerisque mauris, sed eleifend urna. Duis feugiat risus et arcu eleifend venenatis. </p> <h3>Shortcode 1</h3> <p>{myshortcode shortcode="codeone"}</p> <h3>Shortcode 2 - </h3> <p>{myshortcode shortcode="anotherone"|param="test"} {column}column 1{/column} {/myshortcode} </p> <p> Duis quis nisl fringilla, porttitor tellus a, congue mauris. Sed posuere erat vel metus egestas, eget lobortis dolor pretium. Proin iaculis pharetra consectetur. Sed in enim ultricies, sagittis nisl vitae, porttitor libero. Praesent ut erat nisi. Maecenas luctus magna lacus. Mauris ullamcorper maximus arcu et tincidunt. Aenean cursus enim blandit, scelerisque ex sed, vestibulum felis. In magna massa, sagittis in eleifend vel, tristique vitae nisi. </p> </div> Here the HTML contains both self enclosing and enclosing shortcodes. In this case the above regular expression pattern is not working, as it matches the two shortcodes as one, starting from {myshortcode shortcode="codeone"} to {/myshortcode} as a single shortcode.
So my question is is there a pattern I can use to match both the shortcodes?
Please check the current state of it here http://regex101.com/r/tF0mA9/1. Here I am expecting two matches.
Thank you for your help.
-27802997 0#graph_bg{ position:relative; width:350px; height:300px; background-color:yellow; overflow:hidden; } #graph_bar{ position: absolute; top: 350px; left: 50px; height:300px; width:50px; background-color:blue; } #pop{ position: absolute; top:50px; left: 50px; width:50px; height:50px; background-color:red; display: none; } <div id="graph_bg"> <div id="graph_bar"></div> <div id="pop"></div> </div> $("#graph_bar").animate({"top":"50px"} ,2000 ,function(){ $("#pop").show(); } ); http://jsfiddle.net/zacwolf/cgsdcwp3/1/
Since I didn't have your images I used background-colors instead, but you could just change those to background-image to use your images. The thing you were missing is that the background container needs to be the parent to the other two elements, then you can use "overflow-hidden" in the background container, and set the initial absolute position of the bar so that it is outside the visible limits of the background container. Then you just animate it to the "top" position where you want it to be. Also, you forget the # in your show()
-20354188 0f1 = 1 ; N = 1024 ; fs = 200 ; ts = 1/fs ; t = -(N/(2*fs)):ts:(N/(2*fs) ; y = sin(2*pi*f1*t) ; plot(t,y) You do not need to use i for getting 1024 samples out. this can be done by choosing correct start and stop values for t.
-25349880 0 GetJsonObject from a for looped JsonArray show syntax error JsonObject jObj = JsonObject.Parse(json); JsonArray jArr = jObj.GetNamedArray("records"); for (int i = 0; i < jArr.Count; i++) { JsonObject innerObj = jArr.GetObjectAt(i); mData[i] = new Data(innerObj .GetNamedString("countryName"), innerObj .GetNamedString("countryId"), innerObj.GetNamedString("callPrefix"), innerObj .GetNamedString("isoCode")); } Visual studio show syntax error: the best overloaded method for jArr.GetObjectAt(uint) has an invalid argument
-1443584 0 Is there any Document Management Component (Commercial or Open Source) for .NET?We are building a .NET web application (case management) and one of the requirement it needs to have a Document Management System to store and manage the document and at the same time it can be used out side this application such as intranet. Rather than inventing the wheel to do this, is there any Document Management System component that can be integrated with .NET? I preferred the commercial one but if there is open source I am more than happy.
Thank you
-10692864 0 Load UIImage from file using grand central dispatchI'm trying to load images in the background using gcd. My first attempt didn't work:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW,0), ^{ dispatch_async(dispatch_get_main_queue(), ^{ // create UI Image, add to subview }); }); commenting out the background queue code and leaving just the main queue dispatch block didn't work:
dispatch_async(dispatch_get_main_queue(), ^{ // create UI Image, add to subview }); Is there some trick to doing ui stuff inside a gcd block?
In response to mattjgalloway's comment, I'm simply trying to load a big image in a background thread. Here's the full code that I tried originally:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW,0), ^{ UIImage* img = [[UIImage alloc] initWithContentsOfFile: path]; dispatch_async(dispatch_get_main_queue(), ^{ imageView = [[[UIImageView alloc] initWithImage: img] autorelease]; imageView.contentMode = UIViewContentModeScaleAspectFill; CGRect photoFrame = self.frame; imageView.frame = photoFrame; [self addSubview:imageView]; }); }); I simplified it so that I was running everything inside the main queue, but even then it didn't work. I figure if I can't get the whole thing to work in the main queue, no way the background queue stuff will work.
================ UPDATE ==============
I tried the above technique (gcd and all) in a brand new project and it does indeed work as expected. Just not in my current project. So I'll have to do some slow, painful process of elimination work to figure out what's going wrong. I'm using this background loading to display images in a uiscrollview. Turns out bits of the images do sometimes show up, but not always. I'll get to the bottom of this....
================ UPDATE ==============
Looks like the issue is related to the UIScrollView all of this is inside. I think stuff isn't getting drawn/refreshed when it should
-26181981 0 DIDO is a MATLAB optimal control tool for solving general-purpose hybrid optimal control problems. -39630787 0If you script has repeated instructions shorten the script down and use the "play loop" and increase "max" setting how many times you want the script to repeat, i find anything over 10,000 lines begans to stall the script to start longer the script the longer it takes to load into memory
-35662195 0My suggestion is:
get_foo = re.compile(r'([^\)]*\)?)').findall foo = get_foo(s1) # And so on
-38896485 0 I guess the problem is that CD V:\ is not enough. If you are on C:\ CD V:\ won't move the scope to V:. To achieve this you have to add the /d switch to the CD command:
... cd /d V:\ ...
-3596523 0 Is it possible to read an LLVM bitcode file into an llvm::Module? I'm writing a compiler with LLVM. Each source file is compiled into an LLVM bitcode file. Eventually the linker links and optimizes all the bitcode files into one final binary.
I need a way to read the bitcode files in the compiler in order to access the type information. The LLVM documentation shows a class called BitcodeReader, but that appears to be internal to LLVM.
Is there any publicly accessible way to read a bitcode file into an llvm::Module?
Values of background-size property should be like Xpx Ypx. Try change Your last line to this:
t.getBody().style.backgroundSize = newWidth+"px "+newHeight+"px";
-34647436 0 .*(=|<|>|!=)\s*(-?\d+|'[^']+')
-29186154 0 Chrome - clicking mailto: links closes websocket connection I'm using the latest stable Chrome, version 41 . I have an open websocket connection on the page and a link to an email address (mailto:***). When the user clicks on the email address the websocket connection is closed. Firefox doesn't have this issue. Do you know how to fix this?
Thank you
-33085823 0All the snippets of code access data that has been deleted, which has no defined behavior. Therefore, any further assumption is meaningless and left to the single case. Whether you're accessing a vector, char*, string there's no difference: it's always the same violation.
From the documentation for dispatchKeyEvent:
Return
trueif the KeyboardFocusManager should take no further action with regard to the KeyEvent;falseotherwise
Also you can directly consume the event in your dispatchKeyEvent implementation when no further processing of the event is required.
e.consume(); Suggestion of @MadProgrammer is also important. Using of global event processing possibilities is the last choice.
-9936386 0 How to draw into PDF on iOS?I am trying to find a way to allow the user to annotate (i.e. free form drawing) an existing PDF file in iOS, but the only approach that I have found seems extraordinarily cumbersome.
The solution is in Monotouch, but I can translate from Objective-C if needed. This will also mean that many of the method and property names may not be completely familiar to non-Monotouch developers, but I am just looking for an approach.
I currently have code that allows users to annotate images (jpg, png) using the TouchesMoved and TouchesBegan events on a UIView. This works well and accomplishes what I need.
However, when working with an existing PDF file, it seems that the majority of the CGPDF functionality is centered around creating new files rather than editing existing ones.
The only approach that I have been able to come up with is the following:
When the UIView is opened, create a temporary file and set the PDF context to that file (UIGraphics.BeginPDFContext(filename)).
Create a new CGPDFDocument from the original file and then draw each page from the original PDF into the current context, which will be the new temporary file.
Destroy the original PDF document created in step 2.
Show the user the first page and then let them draw on it, with the drawing commands being sent to the new file's context. There will also be methods to allow the user to change pages.
When the user is done, close the PDF context, which will save all of the annotations to the new PDF file.
This seems like it has the potential to be an enormous memory and performance hog, so I am wondering if there is any other way to approach this?
-26542261 0 Contact form design issue in CSSI'm trying to code the below contact form in HTML&CSS.. The issue is how to make the inputs, textarea and the post button in one container and at by taking in consideration that there is a label for each one (out of the container).

For the name, the label is on the right. And it's on the left for the email. Then, the textarea label is stick to the top (I tried using bottom:100px with position:relative and it works) but I'm looking for more ideal solution.
Please find the code in this fiddle: (see full screen for better view)
Input group CSS:
.post .contact form .input-group { display: inline-block; margin-left: 10px; margin-bottom: 15px; position: relative; } PS: The layout should be responsive and work on all screens.
Thanks,
-12528564 0 friend function returning reference to private data memberI have two questions about the following code.
class cls{ int vi; public: cls(int v=37) { vi=v; } friend int& f(cls); }; int& f(cls c) { return c.vi; } int main(){ const cls d(15); f(d)=8; cout<<f(d); return 0; } As a1ex07 says in a comment, your code looks more like what you would put in operator= than in a copy constructor.
First of all, a copy constructor is initializing a brand new object. A check like if (this != &p) doesn't make much sense in a copy constructor; the point you are passing to the copy constructor is never going to be the object that you are initializing at that point (since it's a brand new object), so the check is always going to be true.
Also, doing things like if (label != NULL) is not going to work, because label is not yet initialized. This check might return true or false in random ways (depending if the uninitialized label is NULL by chance).
I would write it like this:
GPSPoint(const GPSPoint& p) : lat(p.lat), lon(p.lon), h(p.h) { if (p.label != NULL) { label = new char[strlen(p.label) + 1]; strcpy(label, p.label); } else { label = NULL; } } Maybe making label a std::string instead of a C-style char* would be a better idea, then you could write your copy constructor purely using an initializer list:
class GPSPoint { private: double lat, lon, h; std::string label; public: // Copy constructor GPSPoint(const GPSPoint& p) : lat(p.lat), lon(p.lon), h(p.h), label(p.label) { } }
-30701258 0 The createPolygon function needs to return the resulting polygon to GeoXml3 so it can manage it.
function addMyPolygon(placemark) { var polygon = geoXml.createPolygon(placemark); google.maps.event.addListener(polygon, 'click', function(event) { var myLatlng = event.latLng; infowindow.setContent("<b>"+placemark.name+"</b><br>"+placemark.description+"<br>"+event.latLng.toUrlValue(6)); infowindow.setPosition(myLatlng); infowindow.open(map); }); return polygon; }; Also, if you are going to use event inside the polygon 'click' listener it needs to be defined.
I'm not expecting upvotes... but I wanted to share this: Multithreaded Algorithms Chapter of the Cormen book.
-30604353 0Sometimes this problem happens when you don´t make any calls to some of Pygames event queue functions in each frame of your game, as the Documentation states.
If you are not using any other event functions in your main game, you should call pygame.event.pump() to allow Pygame to handle internal actions, such as joystick information.
Try the following updated code:
while True: pygame.event.pump() #allow Pygame to handle internal actions joystick_count = pygame.joystick.get_count() for i in range(joystick_count): joystick = pygame.joystick.Joystick(i) joystick.init() name = joystick.get_name() axes = joystick.get_numaxes() hats = joystick.get_numhats() button = joystick.get_numbuttons() joy = joystick.get_axis(0) print(name, joy) An alternative would be to wait for events generated by your joystick (such as JOYAXISMOTION) by using the pygame.event.get() function for instance:
while True: #get events from the queue for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() if event.type == pygame.JOYAXISMOTION and event.axis == 0: print(event.value) joystick_count = pygame.joystick.get_count() for i in range(joystick_count): joystick = pygame.joystick.Joystick(i) joystick.init() #event queue will receive events from your Joystick Hope this helps a little bit :)
-2150387 0Probably both elements are linked by a ID..
-36631453 0 Eclipse Mars - one specific file will not open in compare editor?All of the sudden last week, a single javascript file will no longer open in the compare editor.
It is only this ONE file ... and it is a main file of a node.js project. It used to diff just fine, and all of the sudden last week this one file will no longer diff and throws this exception.
When I look in the log, I see the following exception:
-35066552 0!ENTRY org.eclipse.ui 4 0 2016-04-14 12:38:08.535 !MESSAGE Unhandled event loop exception !STACK 0 org.eclipse.swt.SWTException: Failed to execute runnable (java.lang.IllegalArgumentException) at org.eclipse.swt.SWT.error(SWT.java:4491) at org.eclipse.swt.SWT.error(SWT.java:4406) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:138) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4155) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3772) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1127) at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1018) at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:156) at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:694) at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:606) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:150) at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:139) at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:380) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:235) 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 org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:669) at org.eclipse.equinox.launcher.Main.basicRun(Main.java:608) at org.eclipse.equinox.launcher.Main.run(Main.java:1515)
Caused by: java.lang.IllegalArgumentException at org.eclipse.wst.jsdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2490) at org.eclipse.wst.jsdt.core.dom.ASTConverter.convertToVariableDeclarationStatement(ASTConverter.java:2696) at org.eclipse.wst.jsdt.core.dom.ASTConverter.checkAndAddMultipleLocalDeclaration(ASTConverter.java:319) at org.eclipse.wst.jsdt.core.dom.ASTConverter.convert(ASTConverter.java:436) at org.eclipse.wst.jsdt.core.dom.ASTConverter.convert(ASTConverter.java:1175) at org.eclipse.wst.jsdt.core.dom.JavaScriptUnitResolver.convert(JavaScriptUnitResolver.java:262) at org.eclipse.wst.jsdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:887) at org.eclipse.wst.jsdt.core.dom.ASTParser.createAST(ASTParser.java:647) at org.eclipse.wst.jsdt.internal.ui.compare.JavaStructureCreator.createStructureComparator(JavaStructureCreator.java:284) at org.eclipse.wst.jsdt.internal.ui.compare.JavaStructureCreator.createStructureComparator(JavaStructureCreator.java:243) at org.eclipse.compare.structuremergeviewer.StructureCreator.internalCreateStructure(StructureCreator.java:121) at org.eclipse.compare.structuremergeviewer.StructureCreator.access$0(StructureCreator.java:109) at org.eclipse.compare.structuremergeviewer.StructureCreator$1.run(StructureCreator.java:96) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) at org.eclipse.compare.internal.Utilities.runInUIThread(Utilities.java:859) at org.eclipse.compare.structuremergeviewer.StructureCreator.createStructure(StructureCreator.java:102) at org.eclipse.compare.structuremergeviewer.StructureDiffViewer$StructureInfo.createStructure(StructureDiffViewer.java:155) at org.eclipse.compare.structuremergeviewer.StructureDiffViewer$StructureInfo.refresh(StructureDiffViewer.java:133) at org.eclipse.compare.structuremergeviewer.StructureDiffViewer$StructureInfo.setInput(StructureDiffViewer.java:104) at org.eclipse.compare.structuremergeviewer.StructureDiffViewer.compareInputChanged(StructureDiffViewer.java:342) at org.eclipse.compare.structuremergeviewer.StructureDiffViewer$2.run(StructureDiffViewer.java:74) at org.eclipse.compare.structuremergeviewer.StructureDiffViewer$6.run(StructureDiffViewer.java:322) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) at org.eclipse.compare.structuremergeviewer.StructureDiffViewer.compareInputChanged(StructureDiffViewer.java:319) at org.eclipse.compare.structuremergeviewer.StructureDiffViewer.compareInputChanged(StructureDiffViewer.java:307) at org.eclipse.wst.jsdt.internal.ui.compare.JavaStructureDiffViewer.compareInputChanged(JavaStructureDiffViewer.java:143) at org.eclipse.compare.structuremergeviewer.StructureDiffViewer.inputChanged(StructureDiffViewer.java:278) at org.eclipse.jface.viewers.ContentViewer.setInput(ContentViewer.java:292) at org.eclipse.jface.viewers.StructuredViewer.setInput(StructuredViewer.java:1701) at org.eclipse.compare.CompareViewerSwitchingPane.setInput(CompareViewerSwitchingPane.java:277) at org.eclipse.compare.internal.CompareStructureViewerSwitchingPane.setInput(CompareStructureViewerSwitchingPane.java:132) at org.eclipse.compare.CompareEditorInput.feedInput(CompareEditorInput.java:747) at org.eclipse.compare.CompareEditorInput.createContents(CompareEditorInput.java:555) at org.eclipse.compare.internal.CompareEditor.createCompareControl(CompareEditor.java:462) at org.eclipse.compare.internal.CompareEditor.access$6(CompareEditor.java:422) at org.eclipse.compare.internal.CompareEditor$3.run(CompareEditor.java:378) at org.eclipse.ui.internal.UILockListener.doPendingWork(UILockListener.java:162) at org.eclipse.ui.internal.UISynchronizer$3.run(UISynchronizer.java:154) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:135) ... 23 more
You don't really need the absolute url. Correct relative url is fine.
You should use the Url.Action helper method to generate the correct relative path to your action method. This will generated the proper path irrespective of your current page/view.
url: "@Url.Action("ActionMethodName","YourControllerName")" Url.Action helper method will work if your javascript code is inside a razor view. But if your code is inside an external js file, you should build the relative url to your app root using Url.Content("~") helper method and pass that to your js code via a variable as explained in this post . Try to use javascript namespacing when doing so to prevent possible conflict/overwriting from other global variables with same name.
EDIT : Including Marko's comment as an alternate solution. Thank you :)
If it is an anchor tag, you can simply use the href attribute value of the clicked link.
<a href="@Url.Action("Delete","Product")" class="ajaxLink">Delete</a> and in your js code
$("a.ajaxLink").click(function(e){ e.preventDefault(); var url = $(this).attr("href"); //use url variable value for the ajax call now. }); If it is any other type of html element, you can use html5 data attribute to keep the target url and use the jQuery data method to retrieve it in your js code.
<div data-url="@Url.Action("Delete","Product")" class="ajaxLink">Delete</div> and in your js code
$(".ajaxLink").click(function(e){ e.preventDefault(); // to be safe var url = $(this).data("url"); //use url variable value for the ajax call now. });
-28800060 0 if i got you right...
JQuery:
$(document).ready(function(){ var ParentWidth = $('.parent').width(); if (ParentWidth > 400) { $('.parent').addClass('newstyle'); } }); CSS:
.newstyle { background: red; /*** add more css ***/ } i Recommends you to use class because you can add more css to the class later.
-33896449 0Governance is a way to limit script execution to avoid the overcomsuption of resources server side, as metioned in the documentation:
Perhaps the behavior your are experiencing is not the intended. But actually it is not a feature that is considered for the web browser.
-39388179 0Google allow you to create a custom GVRView which doesn't have the (i) icon - but it involves creating your own OpenGL code for viewing the video.
A hack working on v0.9.0 is to find an instance of QTMButton:
let videoView = GVRVideoView(frame: self.view.bounds) for subview in self.videoView.subviews { let className = String(subview.dynamicType) if className == "QTMButton" { subview.hidden = true } } It is a hack though so it might have unintended consequences and might not work in past or future versions.
-4440306 0First try updating your statistics.
Then, look into your indexing, and make sure you have only what you need. Additional indexes can most definitely slow down inserts.
Then, try rebuilding the indexes.
Without knowing the schema, query, or amount of data, it is hard to say more than that.
-6119230 0 You need 10,000 digits of e on a windows boxLet's say you have a bare-bones Windows XP machine, nothing added. This means no compilers, no MS Office, etc. Oh, and no network connection.
You want 10,000 digits of e (e is the base of the natural logarithm). You have one hour. How could you do it?
Disclaimer: There are probably multiple "good" answers, but I have one particular idea in mind.
-25907377 0 error in spring-security.xml for constructor arg errori m using spring security for my login page.in this in the database user password is stored using sha-password encoder.now i want to use the same in my spring-security.xml.i tried this
<beans:bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder"> <constructor-arg value="256"/> </beans:bean> <authentication-manager> <authentication-provider> <password-encoder ref="passwordEncoder"/> <jdbc-user-service data-source-ref="dataSource" users-by-username-query= "select email,password, 'true' as enabled from user_login where email=? limit 1" authorities-by-username-query= "select email, role from user_roles where email =? " /> </authentication-provider> </authentication-manager> </beans:beans> i m getting error at
cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'constructor-arg'. - Security namespace does not support decoration of element [constructor-arg] - Configuration problem: Security namespace does not support decoration of element. anyone help me for this,please.
-4701510 0 android: listActivity under TabSorry if this is a repeat, none of the solutions I found online worked for me.
I have 2 tabs, and I'm trying to add a list unto one of the tabs. Here's the code:
public class Library extends ListActivity { ParsingDBHelper mDbHelper; ListView lv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle extra = getIntent().getExtras(); String temp = extra.getString(Httpdwld.RESULT); mDbHelper = new ParsingDBHelper(this); mDbHelper.open(); parsing(); fillData(); } private void parsing() { // IMPLEMENT } private void fillData() { Cursor c = mDbHelper.fetchAllSearch(); String[] FROM = new String[] {ParsingDBHelper.KEY_TITLE, ParsingDBHelper.KEY_AUTHOR, ParsingDBHelper.KEY_YEAR, ParsingDBHelper.KEY_LOCATION, ParsingDBHelper.KEY_CALL_ISBN, ParsingDBHelper.KEY_AVAILABILITY}; int[] TO = new int[] {R.id.row_title, R.id.row_author, R.id.row_year, R.id.row_location, R.id.row_id, R.id.row_avail}; SimpleCursorAdapter notes = new SimpleCursorAdapter(this, R.layout.row_layout, c, FROM, TO); lv.setAdapter(notes); } } mDbHelper is simply a a helper for using SQLiteDatabase.
Here's my XML code for the Tabs
<?xml version="1.0" encoding="utf-8"?> <TabHost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/tabhost" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="5dp"> <TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="5dp" > </FrameLayout> <ListView android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout>> </TabHost> But I keep getting "Cannot start Activity: Library" error. Here's where I call Library
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.search_result); TabHost tabHost = getTabHost(); TabHost.TabSpec spec; Intent intent; intent = new Intent(this, Library.class); // Initialize a TabSpec for each tab and add it to the TabHost spec = tabHost.newTabSpec("Library").setIndicator("Library") .setContent(intent); tabHost.addTab(spec); }
Any suggestions?
-19253826 0I found the solution. If load following HTML in UIWebView in iOS 7 (not Safari), the onblur event doesn't work:
<html> <head> <meta name='viewport' content='initial-scale=1.0,maximum-scale=10.0'/> </head> <body> <table style='height:80%'><tr><td> <select onblur="alert('blur')" > <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> </td></tr></table> </body> </html> The important components: viewport, table with some height defined, select inside this table. If remove table OR remove height style OR remove viewport, then onblur works.
I can't explain this effect, but I just remove table height style and it works. Maybe it helps somebody.
-16496963 0HKL9 (string) is greater than HKL15, beacause they are compared as strings. One way to deal with your problem is to define a column function that returns only the numeric part of the invoice number.
If all your invoice numbers start with HKL, then you can use:
SELECT MAX(CAST(SUBSTRING(invoice_number, 4, length(invoice_number)-3) AS UNSIGNED)) FROM table It takes the invoice_number excluding the 3 first characters, converts to int, and selects max from it.
-24092656 0You can either use, but $('title') will fail in IE8
document.title="new title"; or
$('title').html('new title'); or
$(document).attr('title','new title');
-1279656 0 Cocoa/Objective-C: how much optimization should I do myself? I recently found myself writing a piece of code that executed a Core Data fetch, then allocated two mutable arrays with the initial capacity being equal to the number of results returned from the fetch:
// Have some existing context, request, and error objects NSArray *results = [context executeFetchRequest:request error:&error]; NSMutableArray *firstArray = [[[NSMutableArray alloc] initWithCapacity:[results count]] autorelease]; NSMutableArray *secondArray = [[[NSMutableArray alloc] initWithCapacity:[results count]] autorelease]; I looked this over again once I'd written it, and something struck me as odd: I was calling [results count] twice. The resultset is potentially pretty large (hundreds, maybe a thousand, objects).
My first instict was to break out [results count] into a separate NSUInteger, then use that integer for the capacity of each of the arrays. My question: is this kind of by-hand optimization necessary? Will the compiler recognize it's running [results count] twice and just hold the value without me having to explicitly specify that behavior? Or will it run the method twice - a potentially costly operation?
In a similar vein, what other optimizations should programmers (especially iPhone programmers, where there's a limited amount of memory/processing power available) do by hand, as opposed to trusting the compiler?
-35760975 0The best way to coordinate multiple asynchronous operation is to use promises. So, if this were my code, I would change or wrap saveImageToLocalTo() and Posts.insert() to return promises and then use promise features for coordinating them. If you're going to be writing much node.js code, I'd suggest you immediately invest in learning how promises work and start using them for all async behavior.
To solve your issue without promises, you'd have to implement a counter and keep track of when all the async operations are done:
var savedPath = []; var doneCnt = 0; for(i=0;i<n;i++) { savesaveImageToLocalTo(files[i], function(path) { ++doneCnt; savedPath.push(path); // if all the requests have finished now, then do the next steps if (doneCnt === n) { var post = req.body; post.images = savedPath; Posts.insert(postfunction(err, result) { res.send(err, result) }); } }); } This code looks like it missing error handling since most async operations have a possibility of errors and can return an error code.
-4229153 0 Making an Alarm Clock with multiple alarm timesI am trying to make a programmable alarm clock. It should output a melody (.wav) at different moments of time. I used a usercontrol to make a digital clock. I have a timer for showing a progressbar to every second and a button that starts the process. I know exactly the times I want so I don't need any other button. I made some functions where I complete the times I need.
public void suna3() { userControl11.Ora = 01; userControl11.Min = 37; userControl11.Sec = 50; } and on the button click I called them. But when I start the program it is taking only the last time I made (the last function). How can I make it take all the functions?
private void button3_Click(object sender, EventArgs e) { userControl11.Activ = true; suna1(); userControl11.Activ = true; suna2(); }
-35887372 0 def buildNR(nr): return 'http://file.server.com/content.asp?H=cat1&NR={}&T=abc'.format(nr) for line in csv.read(): nr = extract_nr(line) download_file(buildNR(nr)) Just read the csv file and extrace the NR field.
Some Points which should be true for most IDEs:
Eclipse against other IDEs:
So I have a matlab function I wrote that takes in a number and returns an array of numbers (transposed). I need to plot this function. I was trying to use fplot but it was giving me errors:
Error in fplot (line 105) x = xmin+minstep; y(2,:) = feval(fun,x,args{4:end}); Am I using the wrong plot function?
the function solves an equation of motion problem. I have this diff eq:
Mx'' + Cx'+ Kx = 0 where M, C, and K are 4x4 matrices and my function solves the general solution and outputs a vector of 4 values.
-9041967 0I think you need to use an adorner for a customized border. Create an adorner class that implements the OnRender to draw the chamfered corner. Then attach the adorner to the ellipse's adorner layer.
layer = AdornerLayer.GetAdornerLayer(myEllipse) layer.Add(New ChamferedAdorner(myEllipse))
-9564683 0 Looking at the code, the default seek for block devices is in fs/block_dev.c:
static loff_t block_llseek(struct file *file, loff_t offset, int origin) { struct inode *bd_inode = file->f_mapping->host; loff_t size; loff_t retval; mutex_lock(&bd_inode->i_mutex); size = i_size_read(bd_inode); retval = -EINVAL; switch (origin) { case SEEK_END: offset += size; break; case SEEK_CUR: offset += file->f_pos; case SEEK_SET: break; default: goto out; } if (offset >= 0 && offset <= size) { if (offset != file->f_pos) { file->f_pos = offset; } retval = offset; } out: mutex_unlock(&bd_inode->i_mutex); return retval; } No call to the specific block device. The only particular call is to i_size_read, that just does some SMP magic.
I would like the top half of this image to display by default, and then use some CSS to make the image shift upward so that the bottom half shows when the mouse hovers over it. Here is the code and what I've tried, but it is not working. Can anyone help me make this code work?
HTML:
<div id="next"> <a href="page2.html"><img src="images/next3.png" alt="next page"></a> </div> CSS:
#next a:hover{background: url('images/next3.png') 0 -45px;} 
EDIT: HTML:
<div id="next"> </div> CSS:
#next { height:40px; width:160px; background-image:url('images/next3.png'); } #next:hover{background-position: 100% 100%;}
-11568153 0 The useful difference between
data Point = Point Float Float data Radius = Radius Float data Shape = Circle Point Radius and
data LengthQty = Radius Float | Length Float | Width Float
is the way Haskell's type system handles them. Haskell has a powerful type system, which makes sure that a function is passed data that it can handle. The reason you'd write a definition like LengthQuantity is if you had a function which could take either a Radius, Length, or Width, which your function can't do.
If you did have a function which could take a Radius, Length, or Width, I'd write your types like this:
data Point = Point Float Float data Radius = Radius Float data Shape = Circle Point Radius data LengthQty = R Radius | L Length | W Width This way, functions that can only take a Radius benefit from that more specific type checking.
Given a variadic macro of the form:
#define MY_CALL_RETURN_F(FType, FId, ...) \ if(/*prelude omitted*/) { \ FType f = (FType)GetFuncFomId(FId); \ if(f) { \ return f(__VA_ARGS__); \ } else { \ throw invalid_function_id(FId); \ } \ } \ /**/ -- how can this be rewritten to a variadic function template?
template<typename FType, typename ...Args> /*return type?*/ tmpl_call_return_f(MyFunId const& FId, /*what goes here?*/) { ... FType f = (FType)GetFuncFomId(FId); return f(/*what goes here?*/); ... } Update: I'm specifically interested in how to declare the reference type for the Args: && or const& or what?
Update: Note that FType is supposed to be a "plain" function pointer.
-36067236 0did you try this
{% load games_tags %} at the top instead of pygmentize?
-12699006 0Solved similar case a few times. It's very difficult (I call it lucky) to find solution in complicated app just from your session logging. (Oracle kills one of these sessions. One is killed and the other one lives on happily)
Best solution is to ask your DBA (or if you have access to your oracle instalation, you can google and then get them yourself, it's not sou complicated) for trace file(this file is mentioned in exception of killed session, so search your alert log), there will be deadlock graph. (just fulltext trace file for DEADLOCK)
Just look here for exact information how to look into your trace file. LINK
-11525854 0 How to correctly grab and replace selected text in JavaScript?Here is code:
var selection; var edited_selection; var value; var string; $("#text").select(function(){ // $("#text") is textarea value = $("#text").val(); selection = window.getSelection(); string = selection.toString(); }); $("#bold").click(function(){ edited_selection = "<b>" + string + "</b>"; var replacing = value.replace(string, edited_selection); $("#text").val(replacing); }); When I click on some common number or character, it will wrap the first occurence of that character or number. For example easy sentence: "Hello there". If I will try to select the last "e" from that sentence, it will select the first occurence of "e" and it will wrap like e, but i wanted to select the last "e". How can I do it? Thank you for answers.
-1176932 0CLR does not allow multiple inheritance, which is precisely what you're trying to express. You want T to be Address, Email an Phone at the same time (I assume those are class names). Thus is impossible. What's event more, this whole method makes no sense. You'll either have to introduce a base interface for all three classes or use three overloads of an Add method.
The Framework Design Guidelines (2nd Ed., page 327) say:
CONSIDER providing method
Close(), in addition to theDispose(), if close is standard terminology in the area.When doing so, it is important that you make the Close implementation identical to
Disposeand consider implementingIDisposable.Disposemethod explicitly.
So, following the provided example, I've got this class:
public class SomeClass : IDisposable { private SomeDisposable someInnerDisposable; public void Open() { this.someInnerDisposable = new SomeDisposable(); } void IDisposable.Dispose() { this.Close(); } public void Close() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { this.someInnerDisposable.Dispose(); this.someInnerDisposable = null; } } } FxCop doesn't seem to like that:
CA1816 : Microsoft.Usage : 'SomeClass.Close()' calls 'GC.SuppressFinalize(object)', a method that is typically only called within an implementation of 'IDisposable.Dispose'. Refer to the IDisposable pattern for more information.
CA1816 : Microsoft.Usage : Change 'SomeClass.IDisposable.Dispose()' to call 'GC.SuppressFinalize(object)'. This will prevent unnecessary finalization of the object once it has been disposed and it has fallen out of scope.
CA1063 : Microsoft.Design : Modify 'SomeClass.IDisposable.Dispose()' so that it calls Dispose(true), then calls GC.SuppressFinalize on the current object instance ('this' or 'Me' in Visual Basic), and then returns.
CA1063 : Microsoft.Design : Rename 'SomeClass.IDisposable.Dispose()' to 'Dispose' and ensure that it is declared as public and sealed.
-or-
I tried
[SuppressMessage("Microsoft.Design", "CA1063:ImplementIDisposableCorrectly", Justification = "Framework Design Guidelines say it's ok.")] void IDisposable.Dispose() { this.Close(); } but FxCop 1.36 still reports them.
EDIT: Changing it around as suggested eliminates all but this warning:
CA1063 : Microsoft.Design : Rename 'SomeClass.IDisposable.Dispose()' to 'Dispose' and ensure that it is declared as public and sealed.
EDIT 2: CODE_ANALYSIS was indeed missing. Thanks.
-31177507 0what about commit. Is autocommit on?
or add 'commit' after your insert statement
-3112665 0What about just using typedefs?
typedef V& I; typedef const V& CI; Edit:
No. See comments :)
-22119836 0 How to Implement a Class/Database Listener?I am using the Parse.com database service for a PhoneGap app we are creating. We have users that can mark themselves (First User) "Available" for their friends (Second User), and I need a way to listen for that toggle in availability on the second user's side, so their friends list can update without having the refresh the page.
With Parse, your interaction with the database is monitored by # API calls and Burst Limit (Number of API calls per second) so I need to only call the database for the change in status when it is actually changed, I can't keep a setInterval on otherwise it will make the burst limit too small for other user, or it will cause to many API calls for no reason if the status isn't changing.
How can I got about this?
-22065349 0Your framework might have a default helper function which uses php's rawurlencode() function by default too. You might want to check the parameters you should pass for $this->html->link() since php's rawurlencode() function accepts only a string as a parameter.
-40907417 0 Why is infinity printed as "8" in the Windows 10 console?I was testing what was returned from division including zeroes i.e. 0/1, 1/0 and 0/0. For this I used something similar to the following:
Console.WriteLine(1d / 0d); However this code prints 8 not Infinity or some other string constant like PositiveInfinity.
For completeness all of the following print 8:
Console.WriteLine(1d / 0d); double value = 1d / 0d; Console.WriteLine(value); Console.WriteLine(Double.PositiveInfinity); And Console.WriteLine(Double.NegativeInfinity); prints -8.
Why does this infinity print 8?
For those of you who seem to think this is an infinity symbol not an eight the following program:
Console.WriteLine(1d / 0d); double value = 1d / 0d; Console.WriteLine(value); Console.WriteLine(Double.PositiveInfinity); Console.WriteLine(8); Outputs:
-25993860 0I used this simple html style of doing it. Works fine on ios7 and cordova 3.5 and android 4.4
<a href="mailto:abc@gmail.com" data-rel='external'> I'm not even using any plugins such as inappbrowser, just in case you have that doubt.
-29617983 0Here's how I'd approach this:
combiner <- function(n, ...) { ## Capture the unevaluated calls and symbols passed via ... ll <- as.list(substitute(list(...)))[-1] ## Process each one in turn lapply(ll, FUN = function(X) { ## Turn any symbols/names into calls if(is.name(X)) X <- as.call(list(X)) ## Add/replace an argument named n X$n <- n ## Evaluate the fixed up call eval(X) }) } combiner(6, fun1(), fun2, rnorm(), fun4(y=8)) # [[1]] # [1] 3 8 9 7 4 7 # # [[2]] # [1] "Z" "M" "U" "A" "Z" "U" # # [[3]] # [1] 0.6100340 -1.0323017 -0.6895327 1.2534378 -0.3513120 0.3116020 # # [[4]] # [1] 112.31979 91.96595 79.11932 108.30020 107.16828 89.46137
-14421589 0 You can use String array for holding three string
String names[]= {"com.example.adapters.Music","com.example.adapters.Video","com.example.adapters.Photo"};
-4579463 0 You just don't have that much control over a table's default header styles. Have your table view's delegate return a custom view for each header instead bu implementing -tableView:viewForHeaderInSection:. That view could probably be just a UILabel with the text color set to whatever you like.
-36042714 0 Enterprise Library MappingsIs there a way to map database fields to OOP complex type fields with Enterprise Library. I am calling stored procedures that retrieves all data that I would like to store into custom class.
Here I retrieve data from sp:
IEnumerable<WorkHistoryGrid> data = new List<WorkHistoryGrid>(); return db.ExecuteSprocAccessor<WorkHistoryGrid>("PensionPDF_RetrieveParticipantWorkHistoryForFund", pensionId, fund); And here is my class
public class WorkHistoryGrid : BindableBase { private string _rateType; private string _fundType; private string _employer; private string _employerName; private string _local; private string _dateBalanced; private string _plan; private string _fund; private WorkHistoryGridMergeData _mergeData; #region Properties public WorkHistoryGridMergeData MergeData { get { return _mergeData; } set { SetProperty(ref _mergeData, value); } } public string RateType { get { return _rateType; } set { SetProperty(ref _rateType, value); } } public string FundType { get { return _fundType; } set { SetProperty(ref _fundType, value); } } public string Employer { get { return _employer; } set { SetProperty(ref _employer, value); } } public string EmployerName { get { return _employerName; } set { SetProperty(ref _employerName, value); } } public string Local { get { return _local; } set { SetProperty(ref _local, value); } } public string DateBalanced { get { return _dateBalanced; } set { SetProperty(ref _dateBalanced, value); } } public string Plan { get { return _plan; } set { SetProperty(ref _plan, value); } } public string Fund { get { return _fund; } set { SetProperty(ref _fund, value); } } } } } It works fine if I would create one class with all database fields, but I would like to have more control over it by mapping database fields to custom complex type properties.
-17463397 0This example also may help you to understand:
void main() { var car = new CarProxy(new ProxyObjectImpl('Car')); testCar(car); var person = new PersonProxy(new ProxyObjectImpl('Person')); testPerson(person); } void testCar(Car car) { print(car.motor); } void testPerson(Person person) { print(person.age); print(person.name); } abstract class Car { String get motor; } abstract class Person { int get age; String get name; } class CarProxy implements Car { final ProxyObject _proxy; CarProxy(this._proxy); noSuchMethod(Invocation invocation) { return _proxy.handle(invocation); } } class PersonProxy implements Person { final ProxyObject _proxy; PersonProxy(this._proxy); noSuchMethod(Invocation invocation) { return _proxy.handle(invocation); } } abstract class ProxyObject { dynamic handle(Invocation invocation); } class ProxyObjectImpl implements ProxyObject { String type; int id; Map<Symbol, dynamic> properties; ProxyObjectImpl(this.type, [this.id]) { properties = ProxyManager.getProperties(type); } dynamic handle(Invocation invocation) { var memberName = invocation.memberName; if(invocation.isGetter) { if(properties.containsKey(memberName)) { return properties[memberName]; } } throw "Runtime Error: $type has no $memberName member"; } } class ProxyManager { static Map<Symbol, dynamic> getProperties(String name) { Map<Symbol, dynamic> properties = new Map<Symbol, dynamic>(); switch(name) { case 'Car': properties[new Symbol('motor')] = 'xPowerDrive2013'; break; case 'Person': properties[new Symbol('age')] = 42; properties[new Symbol('name')] = 'Bobby'; break; default: throw new StateError('Entity not found: $name'); } return properties; } }
-14355742 0 By checking with breakpoint it seems it is only called once.
-32262515 0Yes:
Application.EnableEvents = False Then when you are done with the procedure:
Application.EnableEvents = True
-23059370 0 Unfortunately, that's does not change anything in me most common cases.
Excellent response on which cases are improved : Does limiting a query to one record improve performance
And for your case, this article is about offest/limit performances : http://explainextended.com/2009/10/23/mysql-order-by-limit-performance-late-row-lookups/
-9251278 0Not a very clear question but you can use a query like this: (untested)
insert into pageview select 15, 'A VISITOR', 10, now() from pageview a where id_realestate=10 and DATE_ADD(now(),INTERVAL -30 MINUTE) > ( select max(news_release) from pageview b where a.id_realestate=b.id_realestate );
-18659009 0 The usual approach for picking off digits is to use n % 10 to get the value of the lowest digit then n /= 10 to remove the lowest digit. Repeat until done.
Position parameter of the getView() method gives the position of the newly created View (i.e the list item), it wont give the clicked item position.
Use listView.onClickListener in the Activity instead of Adater.
os.listdir() returns a list of strings much like the terminal command ls. It lists the names of the files, but it does not include the name of the directory. You need to add that yourself with os.path.join():
def replace(directory, oldData, newData): for file in os.listdir(directory): file = os.path.join(directory, file) f = open(file,'r') filedata = f.read() newdata = filedata.replace(oldData,newData) f = open(file, 'w') f.write(newdata) f.close() I would not recommend file as a variable name, however, because it conflicts with the built-in type. Also, it is recommended to use a with block when dealing with files. The following is my version:
def replace(directory, oldData, newData): for filename in os.listdir(directory): filename = os.path.join(directory, filename) with open(filename) as open_file: filedata = open_file.read() newfiledata = filedata.replace(oldData, newData) with open(filename, 'w') as write_file: f.write(newfiledata)
-40229455 0 It's because when you have comments you print new one. What i suggest to do is use JSON to get the comments array, pass an ID to each comment and check if the Id is allready present in the list. that way you only paste new comment, here's an example.:
html
<form action="" method="POST" id="comment-form"> <textarea id="home_comment" name="comment" placeholder="Write a comment..." maxlength="1000" required></textarea><br> <input type="hidden" name="token" value="<?php echo Token::generate(); ?>"> <input id="comment-button" name="submit" type="submit" value="Post"> </form> <div id="comment-container"> <div id="comment-1">bla bla bla</div> </div>
js
function commentRetrieve(){ $.ajax({ url: "ajax-php/comment-retrieve.php", type: "get", success: function (data) { // console.log(data); if (data == "Error!") { alert("Unable to retrieve comment!"); alert(data); } else { var array = JSON.parse(data); $(array).each(function($value) { if($('#comment-container').find('#comment-' + $value.id).length == 0) { $('#comment-container').prepend($value.html); } }); } }, error: function (xhr, textStatus, errorThrown) { alert(textStatus + " | " + errorThrown); console.log("error"); //otherwise error if status code is other than 200. } }); } setInterval(commentRetrieve, 300);
PHP
$user = new User(); $select_comments_sql = " SELECT c. *, p.user_id, p.img FROM home_comments AS c INNER JOIN (SELECT max(id) as id, user_id FROM profile_img GROUP BY user_id) PI on PI.user_id = c.user_id INNER JOIN profile_img p on PI.user_id = p.user_id and PI.id = p.id ORDER BY c.id DESC "; if ($select_comments_stmt = $con->prepare($select_comments_sql)) { //$select_comments_stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $select_comments_stmt->execute(); //$select_comments_stmt->bind_result($comment_id, $comment_user_id, $comment_username, $home_comments, $comment_date, $commenter_user_id, $commenter_img); //$comment_array = array(); $rows = $select_comments_stmt->fetchAll(PDO::FETCH_ASSOC); foreach ($rows as $row) { $comment_id = $row['id']; $comment_user_id = $row['user_id']; $comment_username = $row['username']; $home_comments = $row['comment']; $comment_date = $row['date']; $commenter_user_id = $row['user_id']; $commenter_img = $row['img']; $commenter_img = '<img class="home-comment-profile-pic" src=" '.$commenter_img.'">'; if ($home_comments === NULL) { echo 'No comments found.'; } else { $html = ""; $html .= '<div class="comment-post-box">'; $html .= $commenter_img; $html .= '<div class="comment-post-username">'.$comment_username. '</div>'; $html .= '<div>'.$comment_date. '</div>'; $html .= '<div class="comment-post-text">'.$home_comments. '</div>'; $html .= '</div>'; array('id' => $comment_id, 'html' => $html) } } }
For better improvement, i would suggest looking into NodeJs socket for more realtime update. Here's a few link.
Official NodeJs Website
Official SocketIo Website
Chat tutorial with socketIo and Nodejs
Hope it helps!
I'm obviously missing something fundamental here. I have the following Scala Code:
package org.carlskii import java.io._ import java.security.cert.CertificateFactory import java.security.Security import org.bouncycastle.jce.provider._ object Main extends App { Security.addProvider(new BouncyCastleProvider) val provider = new BouncyCastleProvider val in = new FileInputStream("cert.cer") val certificateFactory = CertificateFactory.getInstance("X509", provider) val certificate = certificateFactory.generateCertificate(file) println(certificate.getClass) } Which produces this:
class org.bouncycastle.jce.provider.X509CertificateObject So I have a Bouncy Castle X509CertificateObject object. If I call the certificate.getPublicKey method it correctly returns the public key for the certificate.
However if I call certificate.getSerialNumber it throws the following error:
error: value getSerialNumber is not a member of java.security.cert.Certificate println(certificate.getSerialNumber) The interesting thing here is that Scala thinks it's a java.security.cert.Certificate and not an org.bouncycastle.jce.provider.X509CertificateObject object. Why is this the case?
I am trying to use BigInt. My code is like this:
extern crate num; use num::bigint::BigInt; ... println!("{}", from_str::<BigInt>("1")); //this is line 91 in the code In my Cargo.toml file I have the following:
[dependencies] num = "0.1.30" What I did seem to match what was said in this document, also this document and also an answer here on Stack Overflow.
However I got the following error:
Compiling example v0.1.0 (file:///C:/src/rust/example) src\main.rs:91:20: 91:38 error: unresolved name `from_str` [E0425] src\main.rs:91 println!("{}", from_str::<BigInt>("1"));
-22919157 0 Why my QuickSort using ForkJoin is so slow? I have a simple program uses ForkJoin to accelerate QuickSort, but I found that the sort algorithm uses standard partition method is much faster than the one uses my partition methd.
If I don't use ForkJoin, the time performance of two partition method is almost the same. But I expect my partition method be faster.
Edit: The compare is between standard partition() using ForkJoin and mypartition using ForkJoin, so it doesn't relate with overheads of threading.
Edit:
When using standard partition method and 3 threads
sorted: true total time: 3368 sorted: true total time: 1578 When using my partition method and 3 threads
sorted: true total time: 3587 sorted: true total time: 2478 So the results shows that ForkJoin works well for standard partition method, but not well for my partition method.
package me.shu.lang.java.forkjoin; import java.util.Arrays; import java.util.Random; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.RecursiveAction; public class FJSort extends RecursiveAction { /** * */ private static final long serialVersionUID = 6386324579247067081L; final int threshold = 32; final int[] data; final int lo; final int hi; public FJSort(int n) { this.data = new int[n]; this.lo = 0; this.hi = n; Random rand = new Random(); for(int i = 0; i < n; i++) { this.data[i] = rand.nextInt(Integer.MAX_VALUE); } } public FJSort(FJSort o) { this.data = o.data.clone(); this.lo = 0; this.hi = this.data.length; } public FJSort(int[] array, int lo, int hi) { this.data = array; this.lo = lo; this.hi = hi; } void swap(int i, int j) { int temp = data[i]; data[i] = data[j]; data[j] = temp; } int mypartition() { int v = data[hi - 1]; int i = lo; for(int j = hi - 1; j > i;) { if(data[j] <= v) { swap(i, j); i++; } else { j--; } } if(data[i] < v) { i++; } return i; } int partition() { int v = data[hi - 1]; int i = lo; for(int j = lo; j < hi - 1; ) { if(data[j] <= v) { swap(i, j); i++; } j++; } swap(i, hi - 1); return i; } public void sort() { Arrays.sort(data, lo, hi); } public boolean sorted() { for(int i = lo; i + 1 < hi; i++) { if(data[i] > data[i+1]) { return false; } } return true; } protected void compute() { if (hi - lo < threshold) sort(); else { int midpoint = mypartition(); //change to mypartition() is slow FJSort left = new FJSort(data, lo, midpoint); FJSort right = new FJSort(data, midpoint, hi); invokeAll(left, right); } } public static void main(String[] args) { long startTime; long endTime; FJSort p = new FJSort(1000 * 1000 * 30); FJSort p1 = new FJSort(p); { startTime = System.currentTimeMillis(); p.sort(); endTime = System.currentTimeMillis(); System.out.println("sorted: " + p.sorted()); System.out.println("total time: " + (endTime - startTime)); } { startTime = System.currentTimeMillis(); ForkJoinPool fjPool = new ForkJoinPool(1); fjPool.invoke(p1); endTime = System.currentTimeMillis(); System.out.println("sorted: " + p1.sorted()); System.out.println("total time: " + (endTime - startTime)); } } }
-9610155 0 iOS - UITableView not displaying cells I have the following interface set up in storyboard:

The controller is a custom controller that extends from UITableViewController. When I run my app this is what I get:

I thought it might have something to do with the Reuse Identifiers so I changed them to something unique for each of the cells, and modified the code accordingly, but still nothing shows up.
-14601824 0While your pictures are fairly large and you should try to reduce the number and size, you can make gains through packaging the .png into pvr.ccz files. There are multiple different programs available to do this. I like to use Texture Packer which is available here: http://www.codeandweb.com/texturepacker
-39681282 0I found a simple trick. You can pass in headers object and update its pointer value.
const headers = { Authorization: '', }; Relay.injectNetworkLayer( new Relay.DefaultNetworkLayer('http://example.com/graphql', { headers: headers, }) ); // To update the authorization, set the field. headers.Authorization = 'Basic SSdsbCBmaW5kIHNvbWV0aGluZyB0byBwdXQgaGVyZQ=='
-13649327 0 Desire2Learn Valence API logout I'm trying to implement a way to actually logout from my application that is using the Valence API. I can obviously clear the session on my end, but is there a way through the API to actually log out of the Desire2Learn site as well? I've looked through the docs and didn't see anything.
-31928669 0 Is javascriptserializer needed when passing Json data back to my view?I ran a little test (bottom) to see if nested objects could be serialized and they can! So why do I see my co workers code base serialize before he returns to the view?
var js = new JavaScriptSerializer(); return Json(new { m = js.Serialize(movies), error = "none" }, JsonRequestBehavior.AllowGet); here is my example where I don't need to serialize, why not? and what does serializing accomplish?
var movies = new List<object>(); movies.Add(new { Title = "Ghostbusters", Genre = "Comedy", Year = 1984, br = new {Man = "Tall"} }); movies.Add(new { Title = "Gone with Wind", Genre = "Drama", Year = 1939 }); movies.Add(new { Title = "Star Wars", Genre = "Science Fiction", Year = 1977 }); return Json(new { m = movies, error = "none" }, JsonRequestBehavior.AllowGet);
-22312417 0 Extraing data from json array and separate according to type So I am currently trying to extract information from a json array using json_decode($result,true). The background here is that there is another php script getting information from a database and it is sending the data to me as json_encoded result.
using print_r($json) i get the following
Array ( [result] => 1 [message] => Query Successful [data] => Query Output [0] => Array ( //Several values [test] => test [Example] => catcatcat [choice2] => B ) [1] => Array [test]=> test //etc.... I understand we can use a simple for loop to get some stuff to display or in this case I used
for($i=0;$i<=count($json); $i++){ echo $json[$i]['test']; //etc etc } and that will display the value. But what I cant figure out is how to send that to my HTML page as an output as a list.
I am trying to get it to display as following
--This may be a separate question but for me to learn I want to know if it's possible to actually break down the array and send to html as radio input and turn it into a value to choose from.
-13841315 0For valid xHTML it should have the alt attribute.
Something like this would work:
$xml = new SimpleXMLElement($doc); // $doc is the html document. foreach ($xml->xpath('//img') as $img_tag) { if (isset($img_tag->attributes()->alt)) { unset($img_tag->attributes()->alt); } } $new_doc = $xml->asXML();
-24665912 0 I solved my problem. The problem is since I am using RGBA as internal format I am telling opengl to use 4 bytes per pixel. However it is actually 3.
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image->width, image->height, 0, GL_RGB,//The change is here GL_UNSIGNED_BYTE, image->pixels); When I made this change, it worked.
-30022795 0 Postgres Upgrade Interrupted, pg_version now inconsistentRecently attempted an upgrade from 9.3 to 9.4 on an Ubuntu 14.04 Postgres installation, something went awry and the system lost power midway through the upgrade. Now the cluster won't start and when I try to move the data file to a new system and start it, there are inconsistencies in the data files and PG_VERSIONs are varied between 9.3 and 9.4.
Is there any way to recover and make consistent the files to launch under a new cluster?
-30825138 0You need to have marked your files as localizable first. Select file (e. g. a storyboard) and then click the Localize button. Then, you will have that files listed when adding languages.
-20100986 0The features you are trying to use are part of Web API 2. Since you mentioned you're using MVC 4, I expect you will want to upgrade your references to MVC 5 and Web API 2.
Find out more about these features at http://www.strathweb.com/2013/06/ihttpactionresult-new-way-of-creating-responses-in-asp-net-web-api-2/
-17452864 0This answer is probably going to need a little refinement from the community, since it's been a long while since I worked in this environment, but here's a start -
Since you're new to multi-threading in C++, start with a simple project to create a bunch of pthreads doing a simple task.
Here's a quick and small example of creating pthreads:
#include <stdio.h> #include <stdlib.h> #include <pthread.h> void* ThreadStart(void* arg); int main( int count, char** argv) { pthread_t thread1, thread2; int* threadArg1 = (int*)malloc(sizeof(int)); int* threadArg2 = (int*)malloc(sizeof(int)); *threadArg1 = 1; *threadArg2 = 2; pthread_create(&thread1, NULL, &ThreadStart, (void*)threadArg1 ); pthread_create(&thread2, NULL, &ThreadStart, (void*)threadArg2 ); pthread_join(thread1, NULL); pthread_join(thread2, NULL); free(threadArg1); free(threadArg2); } void* ThreadStart(void* arg) { int threadNum = *((int*)arg); printf("hello world from thread %d\n", threadNum); return NULL; } Next, you're going to be using multiple opus decoders. Opus appears to be thread safe, so long as you create separate OpusDecoder objects for each thread.
To feed jobs to your threads, you'll need a list of pending work units that can be accessed in a thread safe manner. You can use std::vector or std::queue, but you'll have to use locks around it when adding to it and when removing from it, and you'll want to use a counting semaphore so that the threads will block, but stay alive, while you slowly add workunits to the queue (say, buffers of files read from disk).
Here's some example code similar from above that shows how to use a shared queue, and how to make the threads wait while you fill the queue:
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <queue> #include <semaphore.h> #include <unistd.h> void* ThreadStart(void* arg); static std::queue<int> workunits; static pthread_mutex_t workunitLock; static sem_t workunitCount; int main( int count, char** argv) { pthread_t thread1, thread2; pthread_mutex_init(&workunitLock, NULL); sem_init(&workunitCount, 0, 0); pthread_create(&thread1, NULL, &ThreadStart, NULL); pthread_create(&thread2, NULL, &ThreadStart, NULL); // Make a bunch of workunits while the threads are running. for (int i = 0; i < 200; i++ ){ pthread_mutex_lock(&workunitLock); workunits.push(i); sem_post(&workunitCount); pthread_mutex_unlock(&workunitLock); // Pretend that it takes some effort to create work units; // this shows that the threads really do block patiently // while we generate workunits. usleep(5000); } // Sometime in the next while, the threads will be blocked on // sem_wait because they're waiting for more workunits. None // of them are quitting because they never saw an empty queue. // Pump the semaphore once for each thread so they can wake // up, see the empty queue, and return. sem_post(&workunitCount); sem_post(&workunitCount); pthread_join(thread1, NULL); pthread_join(thread2, NULL); pthread_mutex_destroy(&workunitLock); sem_destroy(&workunitCount); } void* ThreadStart(void* arg) { int workUnit; bool haveUnit = true; while(haveUnit) { sem_wait(&workunitCount); pthread_mutex_lock(&workunitLock); // Figure out if there's a unit, grab it under // the lock, then release the lock as soon as we can. // After we release the lock, then we can 'process' // the unit without blocking everybody else. haveUnit = !workunits.empty(); if ( haveUnit ) { workUnit = workunits.front(); workunits.pop(); } pthread_mutex_unlock(&workunitLock); // Now that we're not under the lock, we can spend // as much time as we want processing the workunit. if ( haveUnit ) { printf("Got workunit %d\n", workUnit); } } return NULL; }
-14432346 0 How can I build a OSGi bundle with maven that includes non-code resources from an OSGi fragment? I have an OSGi fragment containing non-code resources - that is effectively a jar file containing a set of resources (image files, etc) - that I have built with maven.
I would like to build another bundle with maven which depends on the fragments with the resources. That is, when the code in this bundle is executed, I want the resources from my fragment to be loaded and available with Java's getResources() command.
How can I do this?
-39997713 0You want an outer join to get all rows from table_1 and the matching ones from table2
select t1.id, t1.val - coalesce(t2.val, 0) as result from table_1 t1 left join table_2 t2 on t1.id = t2.id; The coalesce(t2.val, 0) is necessary because the outer join will return null for those rows where no id exists in table_2 but t1.val - null would yield null
First implementation i.e. the array implementation is correct and preferred. But it depends on the programmer. Best practice is not to change/alter the pointer i.e. starting/base address should be preserved, should not be incremented or decremented.
-19800259 0 VBA Writing Array to Range Causing Run-Time Error '7': Out Of MemoryThe Task
I'm working on a VBA project wherein I store the data from a sheet in a Variant Array, do a bunch of calculations with the data in the Array, store the results of those computations in a few other Arrays, then finally I store all the "results arrays" in another Variant Array and write that array to a range in a new sheet.
Note: this process has been working fine ever since I first wrote the procedure.
The Issue
After a very minor logic change, my final Array will no longer write to the specified range. I get Run-time error '7': Out of memory when I try. I changed the logic back in case that was my issue, but I still get the error.
After doing some research, I tried to erase all the arrays (including the one containing all the sheet data) before writing to the range, but that didn't work either. I've checked Task Manager and that shows my RAM as having a lot of free space (almost 6K MBs available and over 1k Mbs "free"). (Task Manager shows the Excel process as using around 120 MBs.)
The Code (Snippet)
Dim R As Range Dim ALCount As Long Dim All(5) As Variant Dim sht As Worksheet Dim Arr1() As Long Dim Arr2() As Date Dim Arr3() As Date Dim Arr4() As Long Dim Arr5() As String All(1) = Arr1 All(2) = Arr2 All(3) = Arr3 All(4) = Arr4 All(5) = Arr5 Set R = sht.Cells(2,1) R.Resize(ALCount - 1, 5).Value = Application.Transpose(All) More Details
My device: Win 7 64-Bit Excel: 2010 32-Bit File Size: <20 MBs Macro Location: Personal Workbook Personal WB Size: < 3 MBs Edit: Array Size: 773x5
Any thoughts on why this might be happening?
-7493744 0The only php based solution that I know is PHP Manual Creator from kubelabs.com (http://www.kubelabs.com/phpmanualcreator/)
-3444956 0Set the HeaderContainerStyle on the first column explicitly so it will not fall back to using the implicit one:
<ListView Name="lvEverything"> <ListView.Resources> <Style TargetType="{x:Type GridViewColumnHeader}"> <Setter Property="LayoutTransform"> <Setter.Value> <RotateTransform Angle="-90"/> </Setter.Value> </Setter> <Setter Property="Width" Value="250"></Setter> </Style> <Style x:Key="FirstColumnStyle" TargetType="GridViewColumnHeader"/> </ListView.Resources> <ListView.View> <GridView> <GridViewColumn Header="First Column" DisplayMemberBinding="{Binding FirstColumn}" HeaderContainerStyle="{StaticResource FirstColumnStyle}"/> <GridViewColumn Header="Second Column" DisplayMemberBinding="{Binding SecondColumn}"/> </GridView> </ListView.View> </ListView> Or, if you are creating the columns in code:
GridViewColumn firstColumn = ...; firstColumn.HeaderContainerStyle = new Style();
-6354547 0 it's a bit of an usual approach of trying to 'grab' the active outlook object... Especially, if there isn't an active object. A more standard approach is something to the effect of:
outlookApplication = new Application(); outlookNamespace = m_OutlookApplication.GetNamespace("mapi"); // If an outlook app is already open, then it will reuse that // session. Else it will perform a fresh logon. outlookNamespace.Logon(accountName, password, true, true);
-22756732 0 Kurty is correct in that you shouldn't need to subclass DragShadowBuilder in this case. My thought is that the view you're passing to the DragShadowBuilder doesn't actually exist in the layout, and therefore it doesn't render.
Rather than passing null as the second argument to inflater.inflate, try actually adding the inflated View to the hierarchy somewhere, and then passing it to a regular DragShadowBuilder:
View dragView = findViewById(R.id.dragged_item); mDragShadowBuilder = new DragShadowBuilder(dragView); v.startDrag(null, mDragShadowBuilder, null, 0); EDIT
I'm aware that having the dragged_item view being rendered all the time isn't what you want, but if it works then at least we know where the problem is and can look for a solution to that instead!
I created two spring boot projects, one is with JPA and the other with Web. I initially combined both of them into one project and everything works perfectly.
I now want to separate the JPA portion from the Web. So I added the JPA project as a dependency of the Web. But spring-boot is unable to detect the beans on JPA.
Is there any examples on how to implement this?
I am getting the exception when I tried to autowire the beans from the JPA project.
BeanCreationException: Could not autowire field:
-21516047 0 Are you running the whole import in one big transaction? Try to split it up in transactions of, say, 10k nodes. You should still however not run into "too many open files". If you do an "lsof" (terminal command) at that time, can you see which files are open?
Data that is committed stays persisted in a neo4j database. I think that the import fails with this error and nothing stays imported since the whole import runs in one big transaction.
-24517247 0 Artifact 'com.android.tools.build:gradle:0.12.1:gradle.jar' not found on Android Studio 0.8.1I've upgraded to Android Studio 0.8.1 and when I try to compile any app it fails with the following error:
Error:Artifact 'com.android.tools.build:gradle:0.12.1:gradle.jar' not found on Android Studio 0.8.1 I tried to update manually the plugin from gradle.org and it does not contain any gradle.jar binary.
How to resolve this error?
-17287528 0Try this:
> d <- as.Date("01-01-2013", "%d-%m-%Y") + 0:7 # first 8 days of 2013 > d [1] "2013-01-01" "2013-01-02" "2013-01-03" "2013-01-04" "2013-01-05" [6] "2013-01-06" "2013-01-07" "2013-01-08" > > ufmt <- function(x) as.numeric(format(as.Date(x), "%U")) > ufmt(d) - ufmt(cut(d, "year")) + 1 [1] 1 1 1 1 1 2 2 2 Note: The first Sunday in the year is defined as the start of week 1 by %U which means that if the year does not start on Sunday then we must add 1 to the week so that the first week is week 1 rather than week 0. ufmt(cut(d, "year")) equals one if d's year starts on Sunday and zero otherwise so the formula above reduces to ufmt(d) if d's year starts on Sunday and ufmt(d)+1 if not.
UPDATE: corrections so Jan starts at week 1 even if year starts on a Sunday, e.g. 2006.
-2334943 0Heuristics are algorithms, so in that sense there is none, however, heuristics take a 'guess' approach to problem solving, yielding a 'good enough' answer, rather than finding a 'best possible' solution.
A good example is where you have a very hard (read NP-complete) problem you want a solution for but don't have the time to arrive to it, so have to use a good enough solution based on a heuristic algorithm, such as finding a solution to a travelling salesman problem using a genetic algorithm.
-16314092 0have you tried like below one
Call below Method From the TableView DataSource Method (cellForAtIndexPath) For Doing the same Task
- (void)setCellBGColorNormalAndSelectedForTableViewCell:(UITableViewCell*)cell cellForRowAtIndexPath:(NSIndexPath*)indexPath { UIImageView *normalCellBG = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height)]; [normalCellBG setImage:[UIImage imageNamed:@"box_nonselected.png"]];//Set Image for Normal [normalCellBG setBackgroundColor:[UIColor clearColor]]; [cell setBackgroundView:normalCellBG]; UIImageView *selecetedCellBG = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height)]; [selecetedCellBG setImage:[UIImage imageNamed:@"box_selected.png"]];//Set Name for selected Cell [selecetedCellBG setBackgroundColor:[UIColor clearColor]]; [cell setSelectedBackgroundView:selecetedCellBG ]; }
-17504066 0 c++ error when use parallel_for I'm trying to use parallel_for, but I get an error, the code is:
#include "stdafx.h" #include <iostream> #include <windows.h> #include <ppl.h> using namespace std; using namespace concurrency; int _tmain(int argc, _TCHAR* argv[]) { parallel_for(size_t(0), 50, [&](size_t i) { cout << i << ","; } cout << endl; getchar(); return 0; } The error is:
IntelliSense: no instance of overloaded function "parallel_for" matches the argument list >argument types are: (size_t, int, lambda []void (size_t i)->void
This is only example, I have to use it in bigger project, but first of all I want to understand how to use it properly.
*edit*
i changed the code to:
parallel_for(size_t(0), 50, [&](size_t i) { cout << i << ","; }); but still i get the annoying error: IntelliSense: no instance of overloaded function "parallel_for" matches the argument list argument types are: (size_t, int, lambda []void (size_t i)->void)
-38052724 0format is a method of str so you should call that from your string, then pass the result of that into print.
print ("So you are {name} and you are{age}".format(name=my_name,age=my_age))
-32670003 0 RSpec - How to get a better error message? I am used to PHPUnit, so I found RSpec to be inferior when it comes to showing what has gone wrong, where and why.
For example, in PHPUnit, I can get the stack trace when an exception is raised (and even with -b option in RSpec, all I can get is the stack trace of RSpec exceptions, and not Rails's)
Also, when some error occurs, it shows you the ACTUAL value and the EXPECTED value.
Those two features I'd like to achieve in RSpec. Getting a detailed error message that includes the stack trace, in case of an Exception of Ruby or of Rails, and to know what was the actual value.
Any ideas of how to accomplish this?
-40786590 0 Java 8 type inference cause to omit generic type on invocationI have a Problem with a generic method after upgrading to Java 1.8, which was fine with Java 1.6 and 1.7 Consider the following code:
public class ExtraSortList<E> extends ArrayList<E> { ExtraSortList(E... elements) { super(Arrays.asList(elements)); } public List<E> sortedCopy(Comparator<? super E> c) { List<E> sorted = new ArrayList<E>(this); Collections.sort(sorted, c); return sorted; } public static void main(String[] args) { ExtraSortList<String> stringList = new ExtraSortList<>("foo", "bar"); Comparator<? super String> compGen = null; String firstGen = stringList.sortedCopy(compGen).get(0); // works fine Comparator compRaw = null; String firstRaw = stringList.sortedCopy(compRaw).get(0); // compiler ERROR: Type mismatch: cannot convert from Object to String } } I tried this with the Oracle javac (1.8.0_92) and with Eclipse JDT (4.6.1) compiler. It is the same result for both. (the error message is a bit different, but essentially the same)
Beside the fact, that it is possible to prevent the error by avoiding raw types, it puzzles me, because i don't understand the reason.
Why does the raw method parameter of the sortedCopy-Method have any effect on the generic type of the return value? The generic type is already defined at class level. The method does not define a seperate generic type. The reference list is typed to <String>, so should the returned List.
Why does Java 8 discard the generic type from the class on the return value?
EDIT: If the method signature of sortedCopy is changed (as pointed out by biziclop) to
public List<E> sortedCopy(Comparator c) { then the compiler does consider the generic type E from the type ExtraSortList<E> and no error appears. But now the parameter c is a raw type and thus the compiler cannot validate the generic type of the provided Comparator.
EDIT: I did some review of the Java Language Specification and now i think about, whether i have a lack of understanding or this is a flaw in the compiler. Because:
E is the class ExtraSortList, this includes the method sortedCopy.sortedCopy itself does not declare a generic type variable, it just refers to the type variable E from the class scope. see Generic Methods in the JLSType arguments may not need to be provided explicitly when a generic method is invoked, as they can often be inferred (§18 (Type Inference)).
stringList is defined with String, thus the compiler does not need to infer a type forE on the invocation of sortedCopy because it is already defined.stringList already has a reified type for E, the parameter c should be Comparator<? super String> for the given invocation.E, thus it should be List<String>.This is my current understanding of how i think the Java compiler should evaluate the invocation. If i am wrong, an explanation why my assumptions are wrong would be nice.
-19203427 0Check out Superfeedr (which I created!) for the RSS polling aspects. We will send your server a notification (including the update!) every time a feed has a new entry. Then, you'll have to fanout that update to all of your app users using Google Cloud Messaging.
-40417777 0 log4cplusud.lib missing when building with VisualStudioi already have a complete VS Solution (that is working on other systems) and i am trying to get it to build on my computer aswell.
The program is using log4cplus to (obviously) log - i already included the needed files, but when building VS tells me, that log4cplusUD.lib is missing. When searching through log4cplus i only found log4cplusS.lib and log4cplusD.lib
Does somebody know how to get this library or how to adjust VS to accept the other libraries? Thanks in advance :)
-13495840 0 postgresql UPDATE error " ERROR: invalid input syntax for type boolean: "I'm trying to make a simple update query on postgresql. I don't really understand the error as there is no boolean value or column type. Here is the log :
cat=> UPDATE categories SET epekcategoryid='27af8b1e-c0c9-4084-8304-256b2ae0c8b2' and epekparentcategoryid='root' WHERE categoryId='281' and siteid='0' and categoryparentid='-1'; ERROR: invalid input syntax for type boolean: "27af8b1e-c0c9-4084-8304-256b2ae0c8b2" LINE 1: UPDATE categories SET epekcategoryid='27af8b1e-c0c9-4084-830...
The table config :
cat=> \d categories; Table "public.categories" Column | Type | Modifiers ----------------------+-----------------------+----------- categoryid | character varying(32) | categoryname | text | siteid | integer | categoryparentid | character varying(32) | status | integer | default 0 epekcategoryid | text | epekparentcategoryid | text | categorylevel | character varying(37) | categoryidpath | character varying(37) |-38255048 0 Separating axes from plot area in MATLAB
I find that data points that lie on or near the axes are difficult to see. The obvious fix, of course, is to simply change the plot area using axis([xmin xmax ymin ymax]), but this is not preferable in all cases; for example, if the x axis is time, then moving the minimum x value to -1 to show activity at 0 does not make sense.
Instead, I was hoping to simply move the x and y axes away from the plot area, like I have done here:
left: MATLAB generated, right: desired (image editing software)
Is there a way to automatically do this in MATLAB? I thought there might be a way to do it by using the outerposition axes property (i.e., set it to [0 0 0.9 0.9] and drawing new axes where they originally were?), but I didn't get anywhere with that strategy.
If you want to validate that your query (as corrected per discussion in comments) does in fact work with other XQuery implementations when entered exactly as given in the question, you can run it as follows (tested in BaseX):
declare context item := document { <actors> <actor filmcount="4" sex="m" id="15">Anderson, Jeff</actor> <actor filmcount="9" sex="m" id="38">Bishop, Kevin</actor> </actors> }; //actor/@id Oxygen XML doesn't support serializing attributes, and consequently discards them from a result sequence when that sequence would otherwise be provided to the user.
Thus, you can work around this with a query such as the following:
//actor/@id/string(.)data(//actor/@id)Frankly, I would not expect //actors/@id to return anything against that data with any valid XPath or XQuery engine, ever.
The reason is that there's only one place you're recursing -- one // -- and that's looking for actors. The single / between the actors and the @id means that they need to be directly connected, but that's not the case in the data you give here -- there's an actor element between them.
Thus, you need to fix your query. There are numerous queries you could write that would find the data you wanted in this document -- knowing which one is appropriate would require more information than you've provided:
//actor/@id - Find actor elements anywhere, and take their id attribute values.//actors/actor/@id - Find actors elements anywhere; look for actor elements directly under them, and take the id attribute of such actor elements.//actors//@id - Find all id attributes in subtrees of actors elements.//@id - Find id attributes anywhere in the document....etc.
-18590755 0 How to split a csv file 20 lines at a time using Splitter EIP, in apache camel?I have a csv file having 2000 lines. I wish to split it 20 lines at a time and send each to a processor in apache camel. How do I do it using Splitter EIP ? Please help ..
-25650791 0You can change the raw data from "<0" to "-1" before you tabulate it with:
credit_arff$checking_status[ credit_arff$checking_status=="<0" ] <- "-1" Or you can tabulate it first and then get the headings with
rownames(table(credit_arff$checking_status) ...and change it there if you want. The limiting factor is that the vector of data, or the vector of rownames, will not contain a mix of numeric and character data. Even if you omit the doublequotes around "-1" from the code above, the data will change to "-1". Whether that's acceptable depends what you're doing with the numbers next. Or will you be changing all the other contents to numeric as well?
-7864869 0 Using awk for conditional find/replaceI want to solve a common but very specific problem: due to OCR errors, a lot of subtitle files contain the character "I" (upper case i) instead of "l" (lower case L).
My plan of attack is:
I could certainly tokenize and reconstruct the entire file in a script, but before I go down that path I was wondering if it is possible to use awk and/or sed for these kinds of conditional operations at the word-level?
Any other suggested approaches would also be very welcome!
-27273909 0 CHECK_LIBRARY_EXISTS library with dependenciesI'm using cmake to build my c++-project that uses a library that is located in my "/usr/local/bin/" directory. The relevant part in the CMakeList.txt reads:
CHECK_INCLUDE_FILES("/usr/local/include/fann.h" HAVE_FANN_HEADER) CHECK_LIBRARY_EXISTS(fann fann_get_errno "/usr/local/lib/" HAVE_FANN_LIB) if(${HAVE_FANN_HEADER} AND ${HAVE_FANN_LIB}) the header is found without a problem the while library is not. Looking into the CMakeError.txt shows:
`/usr/bin/cc -DCHECK_FUNCTION_EXISTS=fann_get_errno CMakeFiles/cmTryCompileExec2973046031.dir/CheckFunctionExists.c.o -o cmTryCompileExec2973046031 -L/usr/local/lib -rdynamic -lfann -Wl,-rpath,/usr/local/lib /usr/local/lib/libfann.so: undefined reference to 'sin' /usr/local/lib/libfann.so: undefined reference to 'exp' /usr/local/lib/libfann.so: undefined reference to 'cos' /usr/local/lib/libfann.so: undefined reference to 'log' /usr/local/lib/libfann.so: undefined reference to 'pow' /usr/local/lib/libfann.so: undefined reference to 'sqrt' /usr/local/lib/libfann.so: undefined reference to 'floor'` in the subsequent if-statement the second variable is therefore undefined.
I suspect that this is because the test program is not linked with the standard math library. However in my main program the libm.so will be linked.
How do I fix the linking of the cmake test program?
I would be happy about any comments Thank you
Arne
-5813550 0 Call win32 CreateProfile() from C# managed codeQuick question (hopefully), how do I properly call the win32 function CreateProfile() from C# (managed code)? I have tried to devise a solution on my own with no avail.
The syntax for CreateProfile() is:
HRESULT WINAPI CreateProfile( __in LPCWSTR pszUserSid, __in LPCWSTR pszUserName, __out LPWSTR pszProfilePath, __in DWORD cchProfilePath ); The supporting documents can be found in the MSDN library.
The code I have so far is posted below.
DLL Import:
[DllImport("userenv.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern int CreateProfile( [MarshalAs(UnmanagedType.LPWStr)] string pszUserSid, [MarshalAs(UnmanagedType.LPWStr)] string pszUserName, [Out][MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszProfilePath, uint cchProfilePath); Invoking the function:
/* Assume that a user has been created using: net user TestUser password /ADD */ // Get the SID for the user TestUser NTAccount acct = new NTAccount("TestUser"); SecurityIdentifier si = (SecurityIdentifier)acct.Translate(typeof(SecurityIdentifier)); String sidString = si.ToString(); // Create string buffer StringBuilder pathBuf = new StringBuilder(260); uint pathLen = (uint)pathBuf.Capacity; // Invoke function int result = CreateProfile(sidString, "TestUser", pathBuf, pathLen);
The problem is that no user profile is ever created and CreateProfile() returns an error code of: 0x800706f7. Any helpful information on this matter is more than welcomed.
Thanks,
-Sean
Update: Solved! string buffer for pszProfilePath cannot have a length greater than 260.
The database I am accessing has a whole API of stored procedures (several hundred) in several packages. I working on new client software to interact with this database and I need to invoke these stored procedures using OCI. Since I am new at this, I decided to start with the easiest one first. It is not working.
It would be helpful if I could get the actual PL/SQL code of the stored procedure. The package does not reside in my user schema, but I do have execute privileges on it. When I query the ALL_SOURCE view I get the package declarations, but not the package body. I also tried the dbms_metadata.get_ddl view, but it just says "Package PTAPI not found in schema for ". Are there any other ways to get the actual PL/SQL code from the package body?
Here is the PL/SQL package declaration of the example procedure I am trying to use. This particular one creates a textual error message given an error code and some optional parameters that depend on the specific error code.
-- format an error message from ERRMSGS table PROCEDURE formatmessage( p_error IN errmsgs.error%TYPE -- index into ERRMSGS , p_errnum OUT errmsgs.error%TYPE -- adjusted error number , p_errmsg OUT errmsgs.MESSAGE%TYPE -- formatted message , p_a IN VARCHAR2 DEFAULT NULL , p_b IN VARCHAR2 DEFAULT NULL , p_c IN VARCHAR2 DEFAULT NULL , p_d IN VARCHAR2 DEFAULT NULL , p_e IN VARCHAR2 DEFAULT NULL ); -- formatmessage My code to invoke the procedure is below [statement and err are OCI handles passed into this function from higher up]
char errmsg[256]; //buffer to receive the error message long errnum; //buffer to receive the adjusted error number memset(errmsg,0,256); errnum = 0; //start the message buffer empty OCIBind* bind1 = NULL, *bind2 = NULL; //to receive the bind handles ub4 curelep1 = 1; //1 errnum element ub4 curelep2 = 1; //1 errmsg element ub2 alenp1 = sizeof(long); //errnum element size ub2 alenp2 = 256; //errmsg element size char sql[] = "BEGIN PTAPI.FORMATMESSAGE(193,:P_ERRNUM,:P_ERRMSG, '','','','',''); END;\0" OCIStmtPrepare(statement,err,(text*)sql,strlen(sql),OCI_NTV_SYNTAX, OCI_DEFAULT); //parse the SQL statement OCIBindByName(statement,&bind1,err,(text*)":P_ERRNUM",-1,&errnum, sizeof(long),SQLT_INT,NULL,&alenp1,NULL,1,&curelep1,OCI_DEFAULT); //bind errnum OCIBindByName(statement,&bind2,err,(text*)":P_ERRMSG",-1,errmsg,256, SQLT_STR,NULL,&alenp2,NULL,1,&curelep2,OCI_DEFAULT); //bind errmsg if(OCIStmtExecute(svcctx,statement,err,1,0,NULL,NULL,OCI_DEFAULT) != OCI_SUCCESS) //execute the statement { long errcode; char errbuf[512]; OCIErrorGet (err,1,NULL,(sb4*)&errcode,(OraText*)errbuf,512, OCI_HTYPE_ERROR); //check to see what the error was printf("ERROR %d - %s\n",errcode,errbuf); return FAIL; } The statement parses properly and the two binds succeed, but I get an error on execute. The error I get is
ERROR 6550 - ORA-06550: line 1, column 7: PLS-00306: wrong number or types of arguments in call to 'FORMATMESSAGE' ORA-06550: line 1, column 7: PLS-00306: wrong number or types of arguments in call to 'FORMATMESSAGE' ORA-06550: line 1, column 7: PL/SQL: Statement ignored I am confused by this error because I imitated a call to this same function from the old client software that works properly. I definitely have the right number and types of arguments. Any ideas why I would be getting this error?
---- UPDATE ----
I found a better example procedure to test. This one is not stored in a package, it is a standalone procedure, and so I have the full PL/SQL code. I get the exact same error. It has to be something to do with how I am invoking them. Thanks for any ideas.
This one deletes an item of a certain type from the database (entries on 3 different tables).
Here is the PL/SQL
PROCEDURE DELSTL(comp IN 3DCOMPS.COMPID%TYPE, rowcount OUT integer, errorcode OUT number) AS tempcount INTEGER; BEGIN errorcode := 0; DELETE FROM 3DCOMPS WHERE COMPID = comp; tempcount := sql%rowcount; IF (sql%rowcount < 1) THEN errorcode := 330; END IF; DELETE FROM IDINF WHERE COMPID = comp; IF (sql%rowcount < 1) THEN errorcode := 332; ELSIF (tempcount < sql%rowcount) THEN tempcount := sql%rowcount; END IF; rowcount := tempcount; DELETE FROM ATTLOC WHERE COMPID1 = comp OR COMPID2 = comp; END; Here is my slightly modified code for this new test procedure
long errnum; //buffer to receive the error number long rowcnt; //buffer to receive the row count OCIBind* bind1 = NULL, *bind2 = NULL; //to receive the bind handles ub4 curelep1 = 1; //1 errnum element ub4 curelep2 = 1; //1 rowcnt element ub2 alenp1 = sizeof(long); //errnum element size ub2 alenp2 = sizeof(long); //rowcnt element size char sql[] = "BEGIN DELSTL('FAKEIDNUM',:P_ROWCNT,:P_ERRNUM); END;\0" OCIStmtPrepare(statement,err,(text*)sql,strlen(sql),OCI_NTV_SYNTAX, OCI_DEFAULT); //parse the SQL statement OCIBindByName(statement,&bind1,err,(text*)":P_ERRNUM",-1,&errnum, sizeof(long),SQLT_INT,NULL,&alenp1,NULL,1,&curelep1,OCI_DEFAULT); //bind errnum OCIBindByName(statement,&bind2,err,(text*)":P_ROWCNT",-1,&rowcnt, sizeof(long),SQLT_INT,NULL,&alenp2,NULL,1,&curelep2,OCI_DEFAULT); //bind rowcnt if(OCIStmtExecute(svcctx,statement,err,1,0,NULL,NULL,OCI_DEFAULT) != OCI_SUCCESS) //execute the statement { long errcode; char errbuf[512]; OCIErrorGet (err,1,NULL,(sb4*)&errcode,(OraText*)errbuf,512, OCI_HTYPE_ERROR); //check to see what the error was printf("ERROR %d - %s\n",errcode,errbuf); return FAIL; } I use 'FAKEIDNUM' since I obviously dont want to actually delete anything during this test. Since that doesnt exist in those tables, rowcnt should be 0 and errnum should be 332 when the procedure ends.
I get exactly the same error as with the other procedure.
ERROR 6550 - ORA-06550: line 1, column 7: PLS-00306: wrong number or types of arguments in call to 'DELSTL' ORA-06550: line 1, column 7: PLS-00306: wrong number or types of arguments in call to 'DELSTL' ORA-06550: line 1, column 7: PL/SQL: Statement ignored Does this give anyone any ideas? Thanks!
-35020279 0 Edit image in UIImageView and use new imageI have an app where you enter information into some forms and press a button to email the image with the information from the forms put on the image. I turn the strings from the forms into UILabels and place those on the UIImageView and then I try to get that image and email it as an attachments. When I do press the button, I just get the original image in the email. Here's my code:
-(IBAction)emailToCustomer:(id)sender { UIImage *rebateImage = [UIImage imageNamed:@"rebate.png"]; UIImageView *rebateImView = [[UIImageView alloc]initWithImage:rebateImage]; UILabel *rebateLabel = [[UILabel alloc]init]; rebateLabel.text = productField.text; [rebateImView addSubview:rebateLabel]; NSData *rebateData = UIImagePNGRepresentation(rebateImView.image); MFMailCOmposeViewController *mailVC = [[MFMailComposeViewController alloc]init]; [mailVC setMailComposeDelegate:self]; if([MFMailComposeViewController canSendMail]) { [mailVC setSubject:@"Rebate"]; [mailVC addAttachmentData:rebateData mimeType:@"image/png" filename:@"RebateCoupon.png"]; [self presentViewController:mailVC animated:YES completion:nil]; } else { NSLog(@"Can't Send Mail"); } } All I get in the email is the original rebate image, even though I enter information in the fields. I want the text from productField to be put on the image from the UIImageView and attach the new image to the email.
-32187702 0 How to call Pinch and Zoom class on am ImageView?I am a newbie to android development. Here I am trying to add pinch and zoom an image in my image view. The image is loaded on an activity called FullScreenView
Here is my FullScreenView.java file
public class FullScreenViewActivity extends Activity implements OnClickListener { private static final String TAG = FullScreenViewActivity.class .getSimpleName(); public static final String TAG_SEL_IMAGE = "selectedImage"; private Wallpaper selectedPhoto; private ImageView fullImageView; private LinearLayout llSetWallpaper, llDownloadWallpaper,btShare; private Utils utils; private ProgressBar pbLoader; InterstitialAd mInterstitialAd; // Picasa JSON response node keys private static final String TAG_ENTRY = "entry", TAG_MEDIA_GROUP = "media$group", TAG_MEDIA_CONTENT = "media$content", TAG_IMG_URL = "url", TAG_IMG_WIDTH = "width", TAG_IMG_HEIGHT = "height"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fullscreen_image); //add code AdView mAdView = (AdView) findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().build(); mAdView.loadAd(adRequest); mInterstitialAd = new InterstitialAd(this); mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712"); requestNewInterstitial(); fullImageView = (ImageView) findViewById(R.id.imgFullscreen); llSetWallpaper = (LinearLayout) findViewById(R.id.llSetWallpaper); llDownloadWallpaper = (LinearLayout) findViewById(R.id.llDownloadWallpaper); btShare = (LinearLayout) findViewById(R.id.btShare); pbLoader = (ProgressBar) findViewById(R.id.pbLoader); // hide the action bar in fullscreen mode getActionBar().hide(); utils = new Utils(getApplicationContext()); // layout click listeners llSetWallpaper.setOnClickListener(this); llDownloadWallpaper.setOnClickListener(this); btShare.setOnClickListener(this); // setting layout buttons alpha/opacity llSetWallpaper.getBackground().setAlpha(70); llDownloadWallpaper.getBackground().setAlpha(70); btShare.getBackground().setAlpha(70); Intent i = getIntent(); selectedPhoto = (Wallpaper) i.getSerializableExtra(TAG_SEL_IMAGE); // check for selected photo null if (selectedPhoto != null) { // fetch photo full resolution image by making another json request fetchFullResolutionImage(); } else { Toast.makeText(getApplicationContext(), getString(R.string.msg_unknown_error), Toast.LENGTH_SHORT) .show(); } } private void requestNewInterstitial() { AdRequest adRequest = new AdRequest.Builder() .addTestDevice("PFSW5H65PRTS9TTO") .build(); mInterstitialAd.loadAd(adRequest); } /** * Fetching image fullresolution json * */ private void fetchFullResolutionImage() { String url = selectedPhoto.getPhotoJson(); // show loader before making request pbLoader.setVisibility(View.VISIBLE); llSetWallpaper.setVisibility(View.GONE); llDownloadWallpaper.setVisibility(View.GONE); btShare.setVisibility(View.GONE); // volley's json obj request JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d(TAG, "Image full resolution json: " + response.toString()); try { // Parsing the json response JSONObject entry = response .getJSONObject(TAG_ENTRY); JSONArray mediacontentArry = entry.getJSONObject( TAG_MEDIA_GROUP).getJSONArray( TAG_MEDIA_CONTENT); JSONObject mediaObj = (JSONObject) mediacontentArry .get(0); final String fullResolutionUrl = mediaObj .getString(TAG_IMG_URL); // image full resolution widht and height final int width = mediaObj.getInt(TAG_IMG_WIDTH); final int height = mediaObj.getInt(TAG_IMG_HEIGHT); Log.d(TAG, "Full resolution image. url: " + fullResolutionUrl + ", w: " + width + ", h: " + height); ImageLoader imageLoader = AppController .getInstance().getImageLoader(); // We download image into ImageView instead of // NetworkImageView to have callback methods // Currently NetworkImageView doesn't have callback // methods imageLoader.get(fullResolutionUrl, new ImageListener() { @Override public void onErrorResponse( VolleyError arg0) { Toast.makeText( getApplicationContext(), getString(R.string.msg_wall_fetch_error), Toast.LENGTH_LONG).show(); } @Override public void onResponse( ImageContainer response, boolean arg1) { if (response.getBitmap() != null) { // load bitmap into imageview fullImageView .setImageBitmap(response .getBitmap()); adjustImageAspect(width, height); // hide loader and show set & // download buttons pbLoader.setVisibility(View.GONE); llSetWallpaper .setVisibility(View.VISIBLE); llDownloadWallpaper .setVisibility(View.VISIBLE); btShare .setVisibility(View.VISIBLE); } } }); } catch (JSONException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), getString(R.string.msg_unknown_error), Toast.LENGTH_LONG).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "Error: " + error.getMessage()); // unable to fetch wallpapers // either google username is wrong or // devices doesn't have internet connection Toast.makeText(getApplicationContext(), getString(R.string.msg_wall_fetch_error), Toast.LENGTH_LONG).show(); } }); // Remove the url from cache AppController.getInstance().getRequestQueue().getCache().remove(url); // Disable the cache for this url, so that it always fetches updated // json jsonObjReq.setShouldCache(false); // Adding request to request queue AppController.getInstance().addToRequestQueue(jsonObjReq); } /** * Adjusting the image aspect ration to scroll horizontally, Image height * will be screen height, width will be calculated respected to height * */ @SuppressWarnings("deprecation") @SuppressLint("NewApi") private void adjustImageAspect(int bWidth, int bHeight) { LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT , LayoutParams.FILL_PARENT); if (bWidth == 0 || bHeight == 0) return; int sHeight = 0; if (android.os.Build.VERSION.SDK_INT >= 13) { Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); sHeight = size.y; } else { Display display = getWindowManager().getDefaultDisplay(); sHeight = display.getHeight(); } int new_width = (int) Math.floor((double) bWidth * (double) sHeight / (double) bHeight); params.width = new_width; params.height = sHeight; Log.d(TAG, "Fullscreen image new dimensions: w = " + new_width + ", h = " + sHeight); //fullImageView.setLayoutParams(params); // fullImageView.setAdjustViewBounds(true); fullImageView.setScaleType(ImageView.ScaleType.FIT_CENTER); } /** * View click listener * */ @Override public void onClick(View v) { if (mInterstitialAd.isLoaded()) { mInterstitialAd.show(); } //else //{ // beginPlayingGame(); // } Bitmap bitmap = ((BitmapDrawable) fullImageView.getDrawable()) .getBitmap(); File cache = getApplicationContext().getExternalCacheDir(); File sharefile = new File(cache, "toshare.png"); try { FileOutputStream out = new FileOutputStream(sharefile); bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); out.flush(); out.close(); } catch (IOException e) { } switch (v.getId()) { // button Download Wallpaper tapped case R.id.llDownloadWallpaper: utils.saveImageToSDCard(bitmap); break; // button Set As Wallpaper tapped case R.id.llSetWallpaper: utils.setAsWallpaper(bitmap); break; case R.id.btShare: Intent share = new Intent(android.content.Intent.ACTION_SEND); share.setType("image/*"); share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + sharefile)); try { startActivity(Intent.createChooser(share, "Share photo")); } catch (Exception e) { } break; default: break; } } } I also create the class for bringing pinch and zoom facility to this.
ZoomableImageView.java
public class ZoomableImageView extends View { //Code goes here } How to call this ZoomableImageView java class file to FullScreenViewActivity so that,when i pinch and zoom, it get works...
-40682298 0You should have a Source and Design button in your project, so when you select Design button, it lets you update properties of all objects. You have it?
-28844383 0 Deploy Node.js app to AWS elastic beanstalk that contains static assetsI'm having some trouble visualizing how I should handle static assets with my EB Node.js app. It only deploys whats committed in the git repo when you do eb deploy (correct?) but I don't want to commit all our static files. Currently we are uploading to S3 and the app references those (the.s3.url.com/ourbucket/built.js), but now that we are setting up dev, staging, and prod envs we can reference built.js since there can be up to 3 versions of it.
Also, there's a timespan where the files are uploaded and the app is rolling out and the static assets don't work with the two versions up on the servers (i.e. built.js works with app version 0.0.2 but server one is deploy 0.0.1 and server two is running version 0.0.2)
How do keep track of these mismatches or is there a way to just deploy a static assets to the EB instance directly.
-11039790 0Per this link it is to externalize the search function from the portal.
Using Solr instead of Lucene gives you the additional capabilities of Solr such as Replication, Sharding, Result clustering through Carrot2, Use of custom Analyzers/Stemmers etc.
It also can offload search server processing to a separate cluster.
Opens up the possibilities of search driven UI (facetted classification etc) separate from your portal UI.
-2271532 0 Android: Forcing a WebView to a certain height (or triggering scrolling for a div)I am building an app which contains an input form and a WebView. The project is available at http://code.google.com/p/android-sap-note-viewer/
The WebView will render a website based on the input and this page has a DIV with the main contents (could be hundreds of lines). I have no control of the contents on the website.
Android WebKit doesn't seem to do any scrolling in a DIV, ref http://www.gregbugaj.com/?p=147. Therefore, only parts of the DIV is shown to the user, with no method of retrieving the rest of the text. My challenge is to find a way that all the text of the DIV is shown.
My view is defined as the following:
<LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content"> <TextView android:layout_width="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:layout_height="wrap_content" android:text="@string/lblNote" /> <EditText android:id="@+id/txtNote" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:numeric="decimal" android:maxLength="10" /> <Button android:id="@+id/bView" android:text="@string/bView" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> <WebView android:id="@+id/webview" android:layout_width="fill_parent" android:layout_height="wrap_content" android:isScrollContainer="false" android:keepScreenOn="false" android:minHeight="4096px" /> </LinearLayout> Here I've tried to hardcode the WebView to a large height in order to make sure the DIV is stretched out and shows all the text, and also force the LinearLayout to do the scrolling.
However, the WebView is always adapting to the screen size (which would be good in most cases, but not this).
Any ideas on how to solve this problem?
(only solution I see now is to fetch the HTML myself, remove the DIV and send it to the WebView)
-959692 0I guess it's a hard thing to do. Firstly you need to read the text in that pdf, and then use some mechanism of synthetic voice generation to create the audio content. Then you have to store it as an mp3.
-27270532 1 better way to find pattern in string?I have two strings from which I want to extract IPs.
These are:
a = """+CGCONTRDP: 1,0,"open.internet","100.80.54.162.255.255.255.255","100.80.54.162","8.8.8.8 ","62.40.32.33","0.0.0.0","0.0.0.0",0 OK """ b = """+UIPADDR: 1,"usb0:0","100.80.54.93","255.255.255.255","","" OK """ From the first I want 100.80.54.162 and the second I want 100.80.54.162. Now obviously lengths of numbers in an IP changes. For the moment I am spitting on "," and finding the numbers before the first 4 .'s. What is a better way to do this as it seems dirty, perhaps the first occurrence of digits.digits.digits.digits and stopping at the next non digit character, a pattern looking for that? How would you do it?
The code in your question compiles. Does your real code have public static void Order() instead?
Either way, I'm guessing you meant to do this in a constructor, so remove the void:
public class Order { private static int totalOrdersPlaced; public final int orderID; public Order() { totalOrdersPlaced++; orderID = totalOrdersPlaced; } }
-13769307 0 product_size alone will not be a PK and so I cannot reference it
Imagine you have two rows in product_stock table that have the same product_size (and different product_code). Now imagine one of these rows (but not the other) is deleted.
orderline rows that reference it? product_stock row, that orderline rows also reference?(Similar problems exist for ON DELETE CASCADE / SET NULL and also when UPDATE-ing the PK.)
To avoid these kinds of ambiguities, the DBMS won't let you create a foreign key unless you can uniquely identify parent row, meaning you must use the whole key after the REFERENCES clause of your FK.
That being said, you could create both...
FOREIGN KEY (product_code) REFERENCES product (product_code) ...and...
FOREIGN KEY (product_code, product_size) REFERENCES product_stock (product_code, product_size) Although, if you have the latter, the former is probably redundant.
In fact, (since you already have the FK product_stock -> product), having both FKs would create a "diamond shaped" dependency. BTW, some DMBSes have restrictions on diamond-shaped FKs (MS SQL Server doesn't support cascading referential actions on them).
So I seem to have run into a bit of a dead end. I'm making a page which has an image slider. The slider has three images, one centered on the screen, the other two overflow on the left and right. When you click on the button to advance the slides it runs this code....
$('#slideRight').click(function() { if ($('.container').is(':animated')) {return false;} var next=parseInt($('.container img:last-of-type').attr('id')) + 1; if (next == 12) { next = 0; } var diff = galsize() - 700; if ($('.thumbs').css("left") == "0px") { var plus = 78; } else { var plus = 0; } var app='<img id="' + next + '" src="' + imgs[next].src + '">'; $('.container').width('2800px').append(app); $('.container').animate({marginLeft: (diff + plus) + "px"}, 300, function() { $('.container img:first-of-type').remove(); $('.container').width('2100px').css("margin-left", (galsize() + plus) + "px"); }); }); // end right click This works just fine, not a problem..... I also have an interval set up to run this automatically every 5 seconds to form a slideshow...
var slideShow = setInterval(function() { $('#slideRight').trigger("click"); }, 5000); This also works perfectly, not a problem.... However my problem is this.... I have thumbnails, when you click on a thumbnail, it should run this code until the current picture is the same as the thumbnail.... here is the code....
$('img.thumbnail').click(function() { clearInterval(slideShow); var src = $(this).attr("src"); while ($('.container img:eq(1)').attr('src') != src) { $('#slideRight').trigger("click"); } }); When I click on the thumbnail nothing happens... I've used alert statements to try and debug, what ends up happening is this....
The while loop executes, however nothing happens the first time. The slide is not advanced at all. Starting with the second execution, the is('::animated') is triggered EVERY TIME and the remainder of the slideRight event is not executed...
So my first problem, can anyone shed some light on why it doesn't run the first time?
And my second question, is there any way to wait until the animation is complete before continuing with the loop?
Any help would be appreciated. Thank you!
-17143195 0Use Include method for eager loading related entities, like described here: http://msdn.microsoft.com/en-US/data/jj574232
-32937832 0I believe you want something like this
//class hierarchy to set the priority for type matching struct second_priority { }; struct first_priority : public second_priority {}; template<typename T> auto size_impl(T const & data, second_priority t) -> int { return sizeof(data); } template<typename T> auto size_impl(T const & data , first_priority t) -> decltype(data.size(),int()) { return data.size(); } template<typename T> int size(T const & data ) { return size_impl(data,first_priority{}); }
-25497505 0 Wrong reallocation.
// filename = realloc(filename, i+1); filename = realloc(filename,(i+1) * sizeof *filename);` BTW: No need to differentiate memory allocation calls. Since the pointer is initialized to NULL, use realloc() the first and subsequent times.
char **filename = NULL; ... // if (i == 0) filename = malloc(sizeof(char*)*(i+1)); // else filename = realloc(filename,i+1); filename = realloc(filename,(i+1) * sizeof *filename);` @PaulMcKenzie well points out code should check for problem return values. Further, fileanme should be free() in the end.
I'm working on a project that includes BeagleBoneBlack and web server written in NodeJs. The idea is that when Beaglebone detects something from enviroment sends it to web server, and if connection is lost for some reason BBB stores the log in it's own database.
So I use SocketIO, and I emit when BBB detects something. I use flag variable isConnected that I put on false on "disconnect" event, and if isConnected is false I'm not emiting to server, just writing in database.
Problem is that when computer, where server is running, goes to sleep (simulating lost connection), SocketIo needs sometimes more than a minute to detect that connection is lost, and emit disconnect event. Is there any way to get this info faster, because the program tries to send readings to server and can't, but it's not written in database.
-20993115 0I don't know if it is related, I had a lot of trouble with embedded script in jade file. Syntax changed. You might have to add a dot to the script tags in jade file, if JS is followed in next lines.
There is another evil change, you need to write doctype html instead of doctype 5
script var x=1 is now script. var x=1-21454159 0
If I understand you correctly you have one table with words (or more general text). This is your table $nome. Now you want to select all rows from another table table_dediche, where column dediche does not containt anything that is in the table $nome. Is this correct?
That is not possible, if you get the values from another table. There is nothing like combining like and in with the result of a subquery. You can have a look at MySQL LIKE IN()? where they solve that problem using an regex. Not sure if that works in your case.
-23468464 0I've put an example directive here: http://embed.plnkr.co/fQhNUGHJ3iAYiWTGI9mn/preview
It activates on the my-grid attribute and inserts a checkbox column. The checkbox is bound to the selected property of each item (note that it's an Angular template and it uses dataItem to refer to the current item). To figure out the selected items you can do something like:
var selection = $scope.grid.dataSource.data().filter(function(item){ return item.selected; }); The checkbox that is added in the header will toggle the selection.
HTH.
-8638847 0 Google Cloud Print is built on the idea that printing can be more intuitive, accessible, and useful. Using Google Cloud Print you can make your printers available to you from any Google Cloud Print enabled web, desktop or mobile app. -7381723 0PS1=.. Is setting the value of the prompt that is displayed
export LC_ALL is settiing an environment variable that will be available to programmes that bash executes. See http://pubs.opengroup.org/onlinepubs/7908799/xbd/envvar.html
-17329927 0 WiX Make a Sub-Dir a Component Group when running heatHello all my fellow WiX'ers,
I was wondering if it possible, and if so where I can go to learn how to do it, to run heat on a directory and have each directory inside that one be it's own Component Group.
Example:
Then run a heat command in the Build Event of the VS2010 project (example below):
heat dir "Root Directory" -gg -sfrag -srd -dr INSTALLFOLDER -out MyWXS.wxs and then have that WXS file structured like so:
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"> <Fragment> <DirecotryRef Id="INSTALLFOLDER"> <Directory Id="dir84156489" Name="Sub Dir 1"> ... </Directory> <Directory Id="dir84156489" Name="Sub Dir 2"> ... </Directory> <Directory Id="dir84156489" Name="Sub Dir 3"> ... </Directory> </DirectoryRed> </Fragment> <Fragment> <ComponentGroup Id="Sub Dir 1"> ... </ComponentGroup> <ComponentGroup Id="Sub Dir 2"> ... </ComponentGroup> <ComponentGroup Id="Sub Dir 3"> ... </ComponentGroup> </Fragment> </wix> If there is any confusion in my question or if anyone has any additional questions for me please let me know. Thank you and I look forward to hearing from you.
EDIT Using the following xslt file I am getting the WXS structure that follows after:
**XLST File** <?xml version="1.0" encoding="utf-8"?>
**WXS File Result** <Wix> <Fragment> <DirectoryRef Id="INSTALLFOLDER"> <Directory Id="dir846546" Name="SubDir1"> ... </Directory> <Directory Id="dir846546" Name="SubDir2"> ... </Directory> <Directory Id="dir846546" Name="SubDir3"> ... </Directory> </DirectoryRef> </Fragment> <wix:Fragment xmlns:wix="http://schemas.microsoft.com/wix/2006/wi"> <wix:ComponentGroup Id="SubDur1"> ... </wix:ComponentGroup> </wix:Fragment> <wix:Fragment xmlns:wix="http://schemas.microsoft.com/wix/2006/wi"> <wix:ComponentGroup Id="SubDur2"> ... </wix:ComponentGroup> </wix:Fragment> <wix:Fragment xmlns:wix="http://schemas.microsoft.com/wix/2006/wi"> <wix:ComponentGroup Id="SubDur3"> ... </wix:ComponentGroup> </wix:Fragment> </Wix> No matter what I do I cannot get the Directories to be created as component groups...
-24260321 0 Work with version control Offline \ OnlineHow can I change the status from version control work offline to working online using the API?
Can I do it to all of the model or to a particular package?
-8403394 0If you have multiple CTE's, they need to be at the beginning of your statement (comma-separated, and only one ;WITH to start the list of CTE's):
;WITH CTE AS (......), [UserDefined] AS (.......) SELECT..... and then you can use both (or even more than two) in your SELECT statement.
Following is the layout of app. It has two views under viewflipper. In the second view, there are 3 rows, row 1 has 3 buttons, row 2 has a image and row 3 has 3 buttons. I want row 1 to be aligned with the top of screen, row 3 to be aligned with the bottom of screen and the image to take the rest of space in between. Could anybody tell me how to achieve that ?
<?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/LinearLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical"> <ViewFlipper android:id="@+id/ViewFlipper01" android:layout_width="fill_parent" android:layout_height="fill_parent"> <!--adding views to ViewFlipper--> <!--view=1--> <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/tv1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/hello" > </TextView> <VideoView android:id="@+id/myvideoview" android:layout_width="wrap_content" android:layout_height="match_parent" /> <Button android:id="@+id/b" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> </LinearLayout> <!--view=2--> <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <!--row 1--> <RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" xmlns:android="http://schemas.android.com/apk/res/android" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:text="Back" /> <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:text="Upload to Facebook" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toLeftOf="@id/button3" android:text="Save" /> </RelativeLayout> <!--row 2--> <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" > <ImageView android:id="@+id/img" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout> <!--row 3--> <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" > <Button android:id="@+id/button4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Previous" /> <Spinner android:id="@+id/spinner" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/button4"> </Spinner> <Button android:id="@+id/button5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/spinner" android:text="Next" /> </RelativeLayout> </LinearLayout> </ViewFlipper> </LinearLayout>
-38487553 0 I would go with the first option as it makes little sense to make different actions just for filtering articles/content.
Also using enums in the route doesn't seem to be the perfect choice. Meaningful strings are better.
-17770510 0 sum of date difference of different id in sqlI have user defined function like this:
create FUNCTION dbo.FormattedTimeDiff (@Date1 DATETIME, @Date2 DATETIME) RETURNS VARCHAR(10) AS BEGIN DECLARE @DiffSeconds INT = sum(DATEDIFF(SECOND, @Date1, @Date2) ) DECLARE @DiffHours INT = @DiffSeconds / 3600 DECLARE @DiffMinutes INT = (@DiffSeconds - (@DiffHours * 3600)) / 60 DECLARE @RemainderSeconds INT = @DiffSeconds % 60 DECLARE @ReturnString VARCHAR(10) SET @ReturnString = RIGHT('00' + CAST(@DiffHours AS VARCHAR(2)), 2) + ':' + RIGHT('00' + CAST(@DiffMinutes AS VARCHAR(2)), 2) + ':' + RIGHT('00' + CAST(@RemainderSeconds AS VARCHAR(2)), 2) RETURN @ReturnString END I try execute out put like this:
SELECT t.vtid, dbo.FormattedTimeDiff(PayDate, DelDate) FROM dbo.Transaction_tbl t where t.Locid = 5 but I am getting output like this:
vtid ----------- ---------- 7 00:21:42 7 01:05:30 7 00:37:43 7 NULL 8 00:00:42 8 00:07:25 7 00:25:36. I want to get sum of date difference of vtid 7 and 8
Expected output:
vtid 7 01:25:45 8 00:07:45 I tried giving group by but showing error, so where I have to made changes in my stored procedure?
-17586806 0
2.You can select one of default locations (here is list)

If you need a custom location
Create new file : File -> New ->File (Resources tab) GPX file click (at the bottom of locations list) "Add GPX File to workspace"
I wonder how to make store sorters ignore if the first letter of a name is small or capitalized? I want to have the list items with the same first letter be grouped together or at least having the small first letter beneath the capitalized and not like it is initially first having a list ob capitalized names and the following the list of small first letters.
I found something like
var sorter = new Ext.util.Sorter({ property : 'myField', sorterFn: function(o1, o2) { // compare o1 and o2 } }); var store = new Ext.data.Store({ model: 'myModel', sorters: [sorter] }); store.sort(); which could be usefull.
thanx!
edit: this seems to work:
var mySubStore = app.stores.myStore.findRecord('id', recordID).websites(); app.stores.myStore.findRecord('id', recordID).websites().getGroupString = function(instance) { return instance.get('name')[0].toUpperCase(); }; var sorter = new Ext.util.Sorter({ property : 'name', sorterFn: function(o1, o2) { var v1 = this.getRoot(o1).get(this.property).toLowerCase(), v2 = this.getRoot(o2).get(this.property).toLowerCase(); return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0); }, clear: function(){} }); //mySubStore.sorters = [sorter]; mySubStore.sort(sorter);
-15731615 0 a simple option is to combine the two scripts
-3802067 0just read the list from *.sln file. There are "Project"-"EndProject" sections.
Here is an article from MSDN.
I am getting an error at position 1996250 in my mysql replication. How can I find out what table/row is at that position?
-31790012 0The RedirectsUsers class is a trait so you cloud override the redirectPath method in your AuthController, to do so just copy the method and paste it in your AuthController making the modifications you need, something like this.
/** * Get the post register / login redirect path. * * @return string */ public function redirectPath() { return route('home'); }
-25765221 0 What is the point of splitting up a project into 2 separate projects? A lot of times I see people splitting up a Project into 2 separate projects, like in this screenshot:

What is the point of seperating Ingot and IngotAPI instead of putting them both in the same project because they get compiled together anyways?
-15119711 0Let's say branches A and B, standing on A, file f was modified (and not checked into A), while B contains another version. If I try to rebase B onto A, the local changes for f are lost. Solution: Commit the changes to f, or stash them away for later, or perhaps discard them by git checkout f.
That is what the message says, in a nutshell.
If you "tried again until it worked", you probably lost changes like the above.
Morals of the story: If you want to do any more complex operation with git (like pulling from upstream, rebasing, changing last commit, ...) make sure everything is tidy. I.e., git status says it is clean, and hopefully no untracked files.
Trying to use Spring security for authentication process, but getting Bad credentials exception.here is how I have defined things in my spring-security.xml file
<beans:bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder"> </beans:bean> <beans:bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder"> </beans:bean> <authentication-manager id="customerAuthenticationManager"> <authentication-provider user-service-ref="customerDetailsService"> <password-encoder hash="sha" /> </authentication-provider> </authentication-manager> customerDetailsService is our own implementation being provided to spring security.In my Java code while registering user, I am encoding provided password before adding password to Database something like
import org.springframework.security.authentication.encoding.PasswordEncoder; @Autowired private PasswordEncoder passwordEncoder; customerModel.setPassword(passwordEncoder.encodePassword(customer.getPwd(), null)); When I tried to debug my application, it seems Spring is calling AbstractUserDetailsAuthenticationProvider authenticate method and when its performing additionalAuthenticationCheck with additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken) authentication); of DaoAuthenticationProvider, it throwing Bad credential exception at following point
if (authentication.getCredentials() == null) { logger.debug("Authentication failed: no credentials provided"); throw new BadCredentialsException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"), userDetails); } I am not sure where I am doing wrong and what needs to be done here to put things in right place, I already checked customer is there in database and password is encoded.
-16775346 0This will work:
var re = /^FIXED(?:-[a-zA-Z0-9]{4}){3}$/; You could as well use the charactergroup \w which usually is pretty much equivalent to [a-zA-Z0-9] but that might contain several characters (ASCII <> UTF) you might not want to have.
Is there any way to check a user has like a facebook page without permission request?
Only if your app is running as a page tab app on that Facebook page.
If so, the info is contained inside the signed_request parameter.
I followed the support link you provided, which states the following:
With SAS® 9.3, the following message occurs in your SAS log when you use aliases for the value of SMTP MAIL FROM:email address and your SMTP server does not support aliases.
The code above does not appear to contain a value for the FROM email address. Try configuring the following option at the start of your process:
options emailid="bobby1232@email.com"; /* adjust as appropriate */ Alternatively, try adding it to your filename as follows:
filename mymail email to=("&to.@email.com") from="bobby123@email.com" TYPE = "TEXT/PLAIN" SUBJECT = "Report Status";
-30460279 0 following query works fine for delete the record based on current timestamp.
-7856401 0 TTLauncherView move item to other pageDELETE FROM table WHERE datecolumn = date('Y-m-d h:i A'); //'2012-05-05 10:00PM'
I have a TTLauncherView in my ios app. I have allowed users to edit and move their items around, however it does not appear that you can move the item from one screen to another, does anyone know how to do this?
-6017914 0There's no guarantee, but one thing you can do to protect yourself is hide the persistence implementation details behind a well-designed interface. It won't keep you from having to rewrite implementation if you switch, but it will isolate clients from the changes. You'll be able to test implementations separately and swap them in and out in a declarative fashion if you're using a dependency injection engine.
-5248219 0 about number of bits required for Fibonacci numberI am reading a algorithms book by S.DasGupta. Following is text snippet from the text regarding number of bits required for nth Fibonacci number.
It is reasonable to treat addition as a single computer step if small numbers are being added, 32-bit numbers say. But the nth Fibonacci number is about 0.694n bits long, and this can far exceed 32 as n grows. Arithmetic operations on arbitrarily large numbers cannot possibly be performed in a single, constant-time step.
My question is for eg, for Fibonacci number F1 = 1, F2 =1, F3=2, and so on. then substituting "n" in above formula i.e., 0.694n for F1 is approximately 1, F2 is approximately 2 bits, but for F3 and so on above formula fails. I think i didn't understand propely what author mean here, can any one please help me in understanding this?
Thanks
-27599571 0 white space below footerThere seems to be random white space after the footer at the bottom of the site. When I try to use inspect element, the white space doesn't seem to fall under any tags. It doesn't seem tied to any footer tags either as removing them didn't change anything.
I'm using Ryan Fait's Sticky Footer solution for my footer.
You can test it at: http://www.edmhunters.com/martin-garrix/
Any ideas what I'm doing wrong?
-36544976 0 JQuery not working after null ajax responceI have Jquery code
$(document).ready(function(){ $('#login').click( function () { $.post('/profile/ajax/login', { username: $('#username').val(), password: $('#password').val(), }, function (res) { if (res != null) { $.each(res, function (i, val) { $('#login-error').html('<div class="alert alert-danger fade in"><a class="close" data-dismiss="alert" href="#">×</a>' + val + '!</div>'); return false; }); } else { location.reload(); } }, 'json' ); } ); } And have PHP code
if($_POST) { $username = $_POST['username']; $password = $_POST['password']; $post = Validation::factory($_POST); $post->rule('username', 'not_empty'); $post->rule('password', 'not_empty'); if($post->check()) { if(!Auth::instance()->login($username, $password, true)) { echo json_encode(array('Неверный Логин или Пароль')); } } else { $errors = $post->errors('validation'); echo json_encode($errors); } } If Ajax return some text with errors (res != null) - Jquery work normally. If Ajax returned without any information nothing happens in "else" block.
How I can solve this problem?
-19217964 0For version 2.0
create c# code to invoke power shell and execute 1st command for mailbox creation then dispose and write another set of c# code to invoke and execute the Active sync command and dispose.
Note: the Domain controller should be the same for mailbox creation and Active sync.
-21164297 0This is how to do it:
You need to send a special APDU to ask for the remaining data and look for status 0x61xx cl, ins, p1, p2, = (0x00, 0xa5, 0x00, 0x00)
def _cmd_ok(self, *args, **kwargs): data, status = self._cmd(*args, **kwargs) #get high bits low = status & 0xFF; high = status >> 8; if status != 0x9000: if high != 0x61: raise Exception('APDU error: 0x%04x' % status) else: while status != 0x9000: part, status = self._cmd(0x00, 0xa5, 0x00, 0x00) data = data + part return ''.join(map(chr, data))
-7649881 0 According to http://www.php.net/manual/en/function.is-numeric.php, is_numeric alows something like "+0123.45e6" or "0xFF". I think this not what you expect.
preg_match can be slow, and you can have something like 0000 or 0051.
I prefer using ctype_digit (works only with strings, it's ok with $_GET).
<?php $id = $_GET['id']; if (ctype_digit($id)) { echo 'ok'; } else { echo 'nok'; } ?>
-6942014 0 There is a blog post about using activity indicators here: http://www.edumobile.org/iphone/iphone-programming-tutorials/use-activityindicator-in-iphone/
The most important pieces of code are:
[activityView startAnimating]; [activityView stopAnimating]; //To Test for a Conditional [activityView isAnimating];
-13795380 0 Rails find by condition Just wondering if there is any function that allows to do that:
MyModel.find_by_conditon(method_a - method_b > 0)
MyModel.class
def method_a next_service_date.to_i end def method_b last_service_date.to_i end
def next_service_date service_date.present? ? calculated_time_estimation : row_time_estimation end def calculated_time_estimation service_date + calculated_service_period end def calculated_service_period case(service_frequency_period) when 'Year' service_frequency_number.to_i.year when 'Month' service_frequency_number.to_i.month when 'Week' service_frequency_number.to_i.day * 7 when 'Day' service_frequency_number.to_i.day end end
service_frequency_number, service_frequency_period, service_date are attributes for MyModel
Seems it can't be done with the C preprocessor, at least the gcc docs states it bluntly:
-22996315 0There is no way to convert a macro argument into a character constant.
SpringApplication has a property webEnvironment. It defaults to true if Tomcat is on the classpath but you can set it to false (programmatically or with spring.main.webEnvironment).
I'm supposed to download a table from MS-SQL server.
The number of row is larger than 6million. The server cannot return entire data at once.
So, I wrote a code that downloads 10,000 rows at a time. and, it binds rows in the loop.
Assume that getData() function returns a data frame contains 10000 rows at a time. (Pseudo Code)
for(i in 1:600) { tempValue <- getData() wannagetValue <- rbind(wannagetValue,tempValue) print(i) } The problem is that it gets slower as time goes by.
I think using rbind like that way is not a good idea.
Any advice will be very helpful. Thank you in advance.
-28172523 0something like this? http://jsfiddle.net/93zb8Lzs/6/
<img src="https://www.google.at/images/srpr/logo11w.png" width="368" height="138" alt="Logo" /> <!-- Nvigationselemente --> <div class="nav"> </div> img { display:block; margin:auto; }
-8782240 0 EDIT - The following will convert UTF-16 with BOM. I don't think it works with any of the other UTF formats. I know it doesn't work for UTF-8. I'm not sure about UTF-32 with BOM
for %%F in (*.txt) do type "%%F" >"%%~nF.converted" If run from the command line then use single percent % instead of double percent %%.
After you verify the converted files are correct, you can
del *.txt ren *.converted *.txt
-14507173 0 Copy TabControl Tab I searched the internet for this but i couldn't find how to do it with C#
What i am trying to do is make it so that when i click on my NewTab button, a new tab appears with the same controls that were on the first tab. I saw some information on how to add a UserControl to your form, but C# doesn't have anything like that.
And for everyone who would say "Post your code", i don't have any, so don't bother saying that, the only code i have is the code for the program and that wouldn't help anyone.
-39372636 0 Slow Small Webpack 2 Build - Tree Shaking - Sass - ChunkingI've put together a very basic webpack 2 build, but it seems to be slow for the project size. The three things I wanted have were:
Webpack seemed to be a good choice for being able to do these things. I've been using Gulp and Rollup, but the SCSS/Chunking along side of the tree shaking is a nice thing.
It takes around 4000 - 5000ms to compile the build, which wouldn't be the end of the world except the project is so small, so I'm worried about that becoming much larger as a project grows.
I've tried a couple things to improve the speed.
resolve : { root: path.resolve(__dirname,'src') } This did help, reducing the time by a couple hundred ms, so that was great. I tried to take this further by also resolving alias, but that didn't really show any gains as far as I could tell.
I set devTool to eval as well. Beyond this I haven't really been able to improve things, but I'm sure it's something in the way I've set things up. It's worth noting that while 'webpack' compiles the build, running the webpack-dev-server doesn't. It's starts up, hangs on the compile and then crashes. This may or may not be a separate issue, but I thought it was worth including.
I'm also using ES6 System.import for chunking (just as a note).
I put the project up on git, so feel free to pull it down: https://github.com/loriensleafs/trying-out-webpack2
The webpack.config.js is:
var path = require('path'), webpack = require('webpack'), CleanPlugin = require('clean-webpack-plugin'), ExtractTextPlugin = require('extract-text-webpack-plugin'), production = process.env.NODE_ENV === 'production'; var plugins = [ new ExtractTextPlugin({ filename: 'bundle.css', allChunks: true}), new webpack.optimize.CommonsChunkPlugin({ name : 'vendor', children : true, minChunks : 2 }) ]; if (production) { plugins = plugins.concat([ new CleanPlugin('builds'), new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.MinChunkSizePlugin({ minChunkSize: 51200, // ~50kb }), new webpack.optimize.UglifyJsPlugin({ mangle: true, compress: { warnings: false, // Suppress uglification warnings }, }), new webpack.DefinePlugin({ __SERVER__ : !production, __DEVELOPMENT__ : !production, __DEVTOOLS__ : !production, 'process.env': { BABEL_ENV: JSON.stringify(process.env.NODE_ENV), } }) ]); } module.exports = { // debug : !production, devTool : production ? false : 'eval', entry : './src', output : { path : 'builds', filename : 'bundle.js', chunkFilename : 'chunk.js', publicPath : 'builds/' }, resolve : { root: path.resolve(__dirname,'src') }, plugins : plugins, module : { loaders: [ { test : /\.(png|gif|jpe?g|svg)$/i, loader : 'url', query : { limit: 10000 } }, { test : /\.js$/, include : /src/, exclude : /node_modules/, loader : 'babel' }, { test : /\.scss$/, include : /src/, exclude : /node_modules/, loader : ExtractTextPlugin.extract(['css','sass']) }, { test : /\.html$/, loader : 'html' } ] } }; Thanks for any advice/help folks have on this. If there's any other helpful info I can post on here please let me know.
-33292092 0You can print "test->data" correctly because that's an int. The issue is that "test->left" and "test->right" are pointers, and pointers are basically numbers that refer to where another object is stored.
If you wanted to print the left node's data, you'd have to do this:
cout << "left: " << test->left->data << endl; And then you'd have to do the same for the right node.
-12207419 0 R: How do I use coord_cartesian on facet_grid with free-ranging axisConsider some facet_grid plot
mt <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) + geom_point() mt + facet_grid(vs ~ am, scales = "free") 
Imagine I just want to zoom on just the top row in the plots above to only show the y-axes values between 3 and 4. I could do this with coord_cartesian() if they weren't faceted or if I wanted to zoom on all plots, but don't have a good solution in this case. I suppose I could subset the data first, but that is taboo for good reason (e.g. would throw off any statistical layer, etc).
(Note that the question is related to this: R: {ggplot2}: How / Can I independently adjust the x-axis limits on a facet_grid plot? but the answer there will not work for this purpose.)
-14108374 0 The condition doesn't seem to work. (while (dAmount != (2*dbAmount))) Also, the first calculation isn't correct o.OMy friend and I are learning C++, and we can't seem to get this program running as it should be. So basically, what we are now attempting, is a tasks that requires us to script a program in which the user is asked two variables. One of these variables is a tax percentage (in the form of 1.X) and the other is any positive, real number. Now what it is we need to know, is why our condition isn't prompting? We would really appreciate an answer to our question. Here is the code:
#include <iostream> #include <iomanip> #include <ctype.h> #include <math.h> #include <cstdlib> using namespace std; int main() { double dTax; double dbAmount; double dAmount; cout << "Tax? (In the form of 1.05)" << endl; cin >> dTax; cout << "Amount?" << endl; cin >> dbAmount; cout << dbAmount << " is the amount without taxes incalculated." << endl; dAmount = (dbAmount*dTax); while (dAmount != (2*dbAmount)) { dAmount = (dAmount*dTax); cout << dAmount << " is the next amount, with taxes incalculated." << endl; break; } cin.get(); return 0; }
-24897853 0 Check again FieldError constructor, according to JavaDocs, 3rd parameter is rejected field value:
rejectedValue - the rejected field value The exact part of code which overrides value is in AbstractBindingResult class:
public Object getFieldValue(String field) { FieldError fieldError = getFieldError(field); // Use rejected value in case of error, current bean property value else. Object value = (fieldError != null ? fieldError.getRejectedValue() : getActualFieldValue(fixedField(field))); // Apply formatting, but not on binding failures like type mismatches. if (fieldError == null || !fieldError.isBindingFailure()) { value = formatFieldValue(field, value); } return value; } So while you provide FieldError class with null rejectedValue, the form field is cleared. As or me, I've always used rejectValue instead of addError:
result.rejectValue( "field", "errorCode" );
-18002992 0 You could try to put it in a document.ready call. And as Samuel Reid pointed out, a hover function is what you need. Like so:
$(document).ready(function () { $('.baixo-tudo').find('.botao').each(function (i) { var imge = $('img'); var t = $('.botao'), src1 = t.find('.src1').text(), src2 = t.find('.src2').text(); imge.hover(function () { t.attr('src', src1); }, function () { t.attr('src', src2); }); }); }); EDIT, building on your fiddle.
I am guessing this is what you want?
$('.baixo-tudo').find('.botao').each(function (i) { var t = $(this), imge = t.children("img"), src1 = t.children('.src1').text(), src2 = t.children('.src2').text(); imge.mouseover(function () { imge.attr('src', src1); }); imge.mouseout(function () { imge.attr('src', src2); }); }); And even shorter.
$('.baixo-tudo').find('.botao').each(function (i) { var t = $(this), imge = t.children("img"), src1 = t.children('.src1').text(), src2 = t.children('.src2').text(); imge.hover(function () { imge.attr('src', src1); }, function () { imge.attr('src', src2); }); });
-16287000 0 I think the easiest way is to map the id to the name directly where you use it, as follows:
svg.selectAll("text") [...] .text( function(d) { return namesMap[d.name]; }); assuming that namesMap converts node_id to node_name.
Now you just have to create aforementioned namesMap, e.g. like this:
d3.csv("nodes.csv", function(names) { var namesMap = {}; names.forEach(function(d) { namesMap[d.node_id] = d.node_name; }); // code using namesMap goes here }); A slighly modified code (with the csv data loading from <pre> nodes in HTML) is available in this fiddle.
Possible Duplicate:
node.js global variables?
How can i include a file or a script in node js, that i can access it global. I would like to extend the standard Array Object with some functions, but i dont like to do this in app.js and wenn i declare it in a module, it is not possible to access it global.
Is there a possibility with a other command to do this?
-27337715 0 how do I create search bar which will update search on typingI created an application with the search on button click. How do I create search bar which will update search on typing letter? Something similar like in a google chrome. I was looking for an answer but I could not find it. Tnx a lot!
SearchableDictionary.java
package com.bogdanskoric.searchdictionary; import android.app.Activity; import android.app.SearchManager; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SearchView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; public class SearchableDictionary extends Activity { private TextView mTextView; private ListView mListView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mTextView = (TextView) findViewById(R.id.text); mListView = (ListView) findViewById(R.id.list); handleIntent(getIntent()); } @Override protected void onNewIntent(Intent intent) { handleIntent(intent); } private void handleIntent(Intent intent) { if (Intent.ACTION_VIEW.equals(intent.getAction())) { // handles a click on a search suggestion; launches activity to show word Intent wordIntent = new Intent(this, WordActivity.class); wordIntent.setData(intent.getData()); startActivity(wordIntent); } else if (Intent.ACTION_SEARCH.equals(intent.getAction())) { // handles a search query String query = intent.getStringExtra(SearchManager.QUERY); showResults(query); } } /** * Searches the dictionary and displays results for the given query. * @param query The search query */ private void showResults(String query) { Cursor cursor = managedQuery(DictionaryProvider.CONTENT_URI, null, null, new String[] {query}, null); if (cursor == null) { // There are no results mTextView.setText(getString(R.string.no_results, new Object[] {query})); } else { // Display the number of results int count = cursor.getCount(); String countString = getResources().getQuantityString(R.plurals.search_results, count, new Object[] {count, query}); mTextView.setText(countString); // Specify the columns we want to display in the result String[] from = new String[] { DictionaryDatabase.KEY_WORD, DictionaryDatabase.KEY_DEFINITION }; // Specify the corresponding layout elements where we want the columns to go int[] to = new int[] { R.id.word }; // Create a simple cursor adapter for the definitions and apply them to the ListView SimpleCursorAdapter words = new SimpleCursorAdapter(this, R.layout.result, cursor, from, to); mListView.setAdapter(words); // Define the on-click listener for the list items mListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Build the Intent used to open WordActivity with a specific word Uri Intent wordIntent = new Intent(getApplicationContext(), WordActivity.class); Uri data = Uri.withAppendedPath(DictionaryProvider.CONTENT_URI, String.valueOf(id)); wordIntent.setData(data); startActivity(wordIntent); finish(); } }); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.searchable_dictionary, menu); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){ SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView(); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setIconifiedByDefault(false); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.search: onSearchRequested(); return true; default: return false; } } } DictionaryDatabase.java
package com.bogdanskoric.searchdictionary; import android.app.SearchManager; import android.content.ContentValues; import android.content.Context; import android.content.res.Resources; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.provider.BaseColumns; import android.text.TextUtils; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; public class DictionaryDatabase { private static final String TAG = "DictionaryDatabase"; //The columns we'll include in the dictionary table public static final String KEY_WORD = SearchManager.SUGGEST_COLUMN_TEXT_1; public static final String KEY_DEFINITION = SearchManager.SUGGEST_COLUMN_TEXT_2; private static final String DATABASE_NAME = "dictionary"; private static final String FTS_VIRTUAL_TABLE = "FTSdictionary"; private static final int DATABASE_VERSION = 2; private final DictionaryOpenHelper mDatabaseOpenHelper; private static final HashMap<String,String> mColumnMap = buildColumnMap(); public DictionaryDatabase(Context context) { mDatabaseOpenHelper = new DictionaryOpenHelper(context); } private static HashMap<String,String> buildColumnMap() { HashMap<String,String> map = new HashMap<String,String>(); map.put(KEY_WORD, KEY_WORD); map.put(KEY_DEFINITION, KEY_DEFINITION); map.put(BaseColumns._ID, "rowid AS " + BaseColumns._ID); map.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID, "rowid AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID); map.put(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, "rowid AS " + SearchManager.SUGGEST_COLUMN_SHORTCUT_ID); return map; } public Cursor getWord(String rowId, String[] columns) { String selection = "rowid = ?"; String[] selectionArgs = new String[] {rowId}; return query(selection, selectionArgs, columns); } public Cursor getWordMatches(String query, String[] columns) { String selection = KEY_WORD + " MATCH ?"; String[] selectionArgs = new String[] {query+"*"}; return query(selection, selectionArgs, columns); } private Cursor query(String selection, String[] selectionArgs, String[] columns) { SQLiteQueryBuilder builder = new SQLiteQueryBuilder(); builder.setTables(FTS_VIRTUAL_TABLE); builder.setProjectionMap(mColumnMap); Cursor cursor = builder.query(mDatabaseOpenHelper.getReadableDatabase(), columns, selection, selectionArgs, null, null, null); if (cursor == null) { return null; } else if (!cursor.moveToFirst()) { cursor.close(); return null; } return cursor; } private static class DictionaryOpenHelper extends SQLiteOpenHelper { private final Context mHelperContext; private SQLiteDatabase mDatabase; private static final String FTS_TABLE_CREATE = "CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE + " USING fts3 (" + KEY_WORD + ", " + KEY_DEFINITION + ");"; DictionaryOpenHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); mHelperContext = context; } @Override public void onCreate(SQLiteDatabase db) { mDatabase = db; mDatabase.execSQL(FTS_TABLE_CREATE); loadDictionary(); } /** * Starts a thread to load the database table with words */ private void loadDictionary() { new Thread(new Runnable() { public void run() { try { loadWords(); } catch (IOException e) { throw new RuntimeException(e); } } }).start(); } private void loadWords() throws IOException { Log.d(TAG, "Loading words..."); final Resources resources = mHelperContext.getResources(); InputStream inputStream = resources.openRawResource(R.raw.definitions); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); try { String line; while ((line = reader.readLine()) != null) { String[] strings = TextUtils.split(line, "-"); if (strings.length < 2) continue; long id = addWord(strings[0].trim(), strings[1].trim()); if (id < 0) { Log.e(TAG, "unable to add word: " + strings[0].trim()); } } } finally { reader.close(); } Log.d(TAG, "DONE loading words."); } public long addWord(String word, String definition) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_WORD, word); initialValues.put(KEY_DEFINITION, definition); return mDatabase.insert(FTS_VIRTUAL_TABLE, null, initialValues); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS " + FTS_VIRTUAL_TABLE); onCreate(db); } } } DictionaryProvider.java
package com.bogdanskoric.searchdictionary; import android.app.SearchManager; import android.content.ContentProvider; import android.content.ContentResolver; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.net.Uri; import android.provider.BaseColumns; public class DictionaryProvider extends ContentProvider { String TAG = "DictionaryProvider"; public static String AUTHORITY = "com.bogdanskoric.searchdictionary.DictionaryProvider"; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/dictionary"); // MIME types used for searching words or looking up a single definition public static final String WORDS_MIME_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/vnd.bogdanskoric.searchdictionary"; public static final String DEFINITION_MIME_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/vnd.bogdanskoric.searchdictionary"; private DictionaryDatabase mDictionary; // UriMatcher stuff private static final int SEARCH_WORDS = 0; private static final int GET_WORD = 1; private static final int SEARCH_SUGGEST = 2; private static final int REFRESH_SHORTCUT = 3; private static final UriMatcher sURIMatcher = buildUriMatcher(); /** * Builds up a UriMatcher for search suggestion and shortcut refresh queries. */ private static UriMatcher buildUriMatcher() { UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); // to get definitions... matcher.addURI(AUTHORITY, "dictionary", SEARCH_WORDS); matcher.addURI(AUTHORITY, "dictionary/#", GET_WORD); // to get suggestions... matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, SEARCH_SUGGEST); matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", SEARCH_SUGGEST); matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_SHORTCUT, REFRESH_SHORTCUT); matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_SHORTCUT + "/*", REFRESH_SHORTCUT); return matcher; } @Override public boolean onCreate() { mDictionary = new DictionaryDatabase(getContext()); return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // Use the UriMatcher to see what kind of query we have and format the db query accordingly switch (sURIMatcher.match(uri)) { case SEARCH_SUGGEST: if (selectionArgs == null) { throw new IllegalArgumentException( "selectionArgs must be provided for the Uri: " + uri); } return getSuggestions(selectionArgs[0]); case SEARCH_WORDS: if (selectionArgs == null) { throw new IllegalArgumentException( "selectionArgs must be provided for the Uri: " + uri); } return search(selectionArgs[0]); case GET_WORD: return getWord(uri); case REFRESH_SHORTCUT: return refreshShortcut(uri); default: throw new IllegalArgumentException("Unknown Uri: " + uri); } } private Cursor getSuggestions(String query) { query = query.toLowerCase(); String[] columns = new String[] { BaseColumns._ID, DictionaryDatabase.KEY_WORD, DictionaryDatabase.KEY_DEFINITION, /* SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, (only if you want to refresh shortcuts) */ SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID}; return mDictionary.getWordMatches(query, columns); } private Cursor search(String query) { query = query.toLowerCase(); String[] columns = new String[] { BaseColumns._ID, DictionaryDatabase.KEY_WORD, DictionaryDatabase.KEY_DEFINITION}; return mDictionary.getWordMatches(query, columns); } private Cursor getWord(Uri uri) { String rowId = uri.getLastPathSegment(); String[] columns = new String[] { DictionaryDatabase.KEY_WORD, DictionaryDatabase.KEY_DEFINITION}; return mDictionary.getWord(rowId, columns); } private Cursor refreshShortcut(Uri uri) { String rowId = uri.getLastPathSegment(); String[] columns = new String[] { BaseColumns._ID, DictionaryDatabase.KEY_WORD, DictionaryDatabase.KEY_DEFINITION, SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID}; return mDictionary.getWord(rowId, columns); } @Override public String getType(Uri uri) { switch (sURIMatcher.match(uri)) { case SEARCH_WORDS: return WORDS_MIME_TYPE; case GET_WORD: return DEFINITION_MIME_TYPE; case SEARCH_SUGGEST: return SearchManager.SUGGEST_MIME_TYPE; case REFRESH_SHORTCUT: return SearchManager.SHORTCUT_MIME_TYPE; default: throw new IllegalArgumentException("Unknown URL " + uri); } } @Override public Uri insert(Uri uri, ContentValues values) { throw new UnsupportedOperationException(); } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { throw new UnsupportedOperationException(); } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { throw new UnsupportedOperationException(); } } searchable.xml
<?xml version="1.0" encoding="utf-8"?> <searchable xmlns:android ="http://schemas.android.com/apk/res/android" android:label="@string/search_label" android:hint ="@string/search_hint" android:searchSuggestAuthority="searchdictionary.DictionaryProvider" android:searchSuggestIntentAction="android.intent.action.VIEW" android:searchSuggestIntentData="content://searchdictionary.DictionaryProvider/dictionary" android:searchSuggestSelection=" ?" android:searchSuggestThreshold="1" android:includeInGlobalSearch="true" android:searchSettingsDescription="@string/settings_description" > </searchable> raw/definition.txt
Adikcija - Podložnost nekoj štetnoj navici, najcešce, psihofiziološka zavisnost od droge ili alkohola (toksikomanija, alkoholizam). Adolescencija - Period prelaska iz detinjstva u zrelo doba obeležen biološkim rastom, seksualnim.. etc.
-3791466 0 How do I know if the user clicks the "back" button? I'm using anchors for dealing with unique urls for an ajaxy website. However, I want to reload the content when the user hits the Browser's "back" button so the contents always matches the url.
How can I achieve this? Is there a jQuery event triggering when user clicks "Back"?
-34741206 0Ok, I finally used a piece of code that uses ctypes lib to provide some kind of killing thread function. I know this is not a clean way to proceed but in my case, there are no resources shared by the threads so it shouldn't have any impact ...
If it can help, here is the piece of code that can easily be found on the net:
def terminate_thread(thread): """Terminates a python thread from another thread. :param thread: a threading.Thread instance """ if not thread.isAlive(): return exc = ctypes.py_object(SystemExit) res = ctypes.pythonapi.PyThreadState_SetAsyncExc( ctypes.c_long(thread.ident), exc) if res == 0: raise ValueError("nonexistent thread id") elif res > 1: # """if it returns a number greater than one, you're in trouble, # and you should call it again with exc=NULL to revert the effect""" ctypes.pythonapi.PyThreadState_SetAsyncExc(thread.ident, None) raise SystemError("PyThreadState_SetAsyncExc failed")
-4825949 0 Set the PuTTY charset to UTF-8 in the options.
-9763404 0 SaaS Platform - Different database user for each user or one master accountI have a SaaS platform that I am working on; written in PHP and using a MySQL database (using the PHP PDO class).
The application is already functional and I have decided to use a separate database for each instance.
One of the reasons for using multiple databases is to ensure that client data is separated (and hopefully secure). This also allows us to easily transfer their instance into the on-premise version.
Security is always something that I worry about. I want to ensure this system is as secure as possible before it goes live.
Currently we are using a single MySQL username & password that has access to every database (on that specific MySQL Farm).
Theoretically if there was a security breach then the attacker might be able to access a different database (username & password is unset after the PDO/Database connection is made, but they might be able to run a query such as "use databaseB").
Is this something that I should be concerned about? For example a SaaS platform that simply uses database partitioning is already less secure as a simple SQL error could expose client data.
I've already started looking into using different database usernames & passwords, but it does add to the complexity of the SaaS platform, and keeping things simple is always a good idea.
Thanks!
I have decided to go with different usernames and password for each instance.
This is another layer of security and that cannot hurt.
-9278626 0Why Can't you do some thing like below, Just fetch the user inside the closure.
Login.withNewSession { def user = grails.admin.User.read(appCtx.springSecurityService.currentUser.id) login = new Login(user: user) } OR
Login.withTransaction{ def user = grails.admin.User.read(appCtx.springSecurityService.currentUser.id) login = new Login(user: user) }
-9533408 0 Converting time so it can used in a Integer I'm working on some code in VB that can get the average time from the speed of button press. I've got the maths done however I'm having a problem converting a TimeSpan declaration into a Integer where it can be divided and made into a average. Can you please help. Thanks!
Maths for code:
2nd click
click count = 2 average= current time / 1 so current = time \ click count - 1 3rd click
adveragetime + Current Time \ clickcount - 1 4th click
average time * (click count -2) + Current Time \ clickcount -1
-23344254 0 [Adding this here since you want a way to do it purely in XAML. I think that insisting on pure XAML here is not essential and @bit's answer is the right way to go, IMO.]
You can use style to have triggers that do the change.
Let's say your UC is called MyUC and currently you have an instance of it similar to: <local:MyUC/> in some other view/UC/window. You can change the instance to look like so:
<local:MyUC> <local:MyUC.Style> <Style TargetType="{x:Type local:MyUC}"> <Setter Property="DataContext" Value="{Binding SelectedItem, ElementName=MyDataGrid}"/> <Style.Triggers> <DataTrigger Binding="{Binding ElementName=MyCheckbox, Path=IsChecked}" Value="True"> <Setter Property="DataContext" Value="{Binding APerson}"/> </DataTrigger> </Style.Triggers> </Style> </local:MyUC.Style> </local:MyUC> I'm changing here the data context property, but you can change any other dependency property on MyUC.
Again, I think this is a less favorite approach to tackle this functionality, but it's pure XAML.
-1389139 0Compiling MSIL to Native Code Ngen.exe
SUMMARY:
The runtime supplies another mode of compilation called install-time code generation. The install-time code generation mode converts MSIL to native code just as the regular JIT compiler does, but it converts larger units of code at a time, storing the resulting native code for use when the assembly is subsequently loaded and run. When using install-time code generation, the entire assembly that is being installed is converted into native code, taking into account what is known about other assemblies that are already installed.
Take look at - How to compile a .NET application to native code?
-30391341 0You could try writing a small wrapper around the List of your object type, and giving it a string based [] overloaded accessor. Like this:
public class ComplexType { public string PropertyName { get; set; } public string Layer { get; set; } public string DisplayName { get; set; } } public class DebuggableList : List<ComplexType> { public ComplexType this[string key] { get { return this.FirstOrDefault(i => i.PropertyName == key); } } } class Program { static void Main(string[] args) { var myList= new DebuggableList(); myList.Add(new ComplexType { DisplayName = "XXX", Layer = "YYY", PropertyName = "ZZZ" }); myList.Add(new ComplexType { DisplayName = "AAA", Layer = "BBB", PropertyName = "CCC" }); myList.Add(new ComplexType { DisplayName = "DDD", Layer = "EEE", PropertyName = "FFF" }); } } In the watch window, you can then access your desired object using myList["XXX"], and the object with PropertyName=="XXX" will be displayed.
Not without writing it somewhere. You have the following options:
1- Write it to a file (or touch a file and check for its existence)
2- Manually update a CONFIG file with a GLOBAL variable
3- Use a database.
-13678635 0One solution can be NSNotifications. Post a notification when mute button is tapped and add observer on each of the view where you want play/mute sounds.
See this NSNotificationCenter Tutorial for how to post and add observe for NSNotification
I have a gridview which is bounded as
<asp:GridView runat="server" ID="gvShipDetails" AutoGenerateColumns="false" OnRowDataBound="gvShipDetails_RowDataBound"> <Columns> <asp:TemplateField> <HeaderTemplate> Ship name <br /> <asp:TextBox class="search_textbox" runat="server" BorderStyle="None" Width="100%"> </asp:TextBox> </HeaderTemplate> <ItemTemplate> <%#Eval("VesselName")%> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> The problem is the finally rendered html table td is rendered as
<td> sample vessel name </td> A lot of spaces inside td.How is this possible.
If I replace this bound code as
<asp:BoundField HeaderText="vessel name" DataField="vesselname" /> Then html is renderd as <td>sample vessel name<td>
Why is it so? I wanted to use headertemplate and i wanted to avoid these trailing spaces. How to do it
Any help will be appreciated
-13138156 0If you need to avoid the final slide back to the first and just restart, I would suggest a slight change over Pushpesh's answer:
$(document).ready(function() { var currentPosition = 0; var slideWidth = 500; var slides = $('.slide'); var numberOfSlides = slides.length; var slideShowInterval; var speed = 900; var lastSlideReached = false; slides.wrapAll('<div id="slidesHolder"></div>'); slides.css({ 'float' : 'left' }); $('#slidesHolder').css('width', slideWidth * numberOfSlides); slideShowInterval = setInterval(changePosition, speed); function changePosition() { if( ! lastSlideReached ) { if(currentPosition == (numberOfSlides-1)) { lastSlideReached = true; } else { currentPosition++; } moveSlide(); } else { resetSlide() } } function moveSlide() { $('#slidesHolder').animate({'marginLeft' : slideWidth*(-currentPosition)}); } function resetSlide(){ currentPosition = 0; $('#slidesHolder').css('marginLeft', currentPosition ); lastSlideReached = false; } });
cheers
-13211993 0 Estimating the variance of eigenvalues of sample covariance matrices in MatlabI am trying to investigate the statistical variance of the eigenvalues of sample covariance matrices using Matlab. To clarify, each sample covariance matrix is constructed from a finite number of vector snapshots (afflicted with random white Gaussian noise). Then, over a large number of trials, a large number of such matrices are generated and eigendecomposed in order to estimate the theoretical statistics of the eigenvalues.
According to several sources (see, for example, [1, Eq.3] and [2, Eq.11]), the variance of each sample eigenvalue should be equal to that theoretical eigenvalue squared, divided by the number of vector snapshots used for each covariance matrix. However, the results I get from Matlab aren't even close.
Is this an issue with my code? With Matlab? (I've never had such trouble working on similar problems).
Here's a very simple example:
% Data vector length Lvec = 5; % Number of snapshots per sample covariance matrix N = 200; % Number of simulation trials Ntrials = 10000; % Noise variance sigma2 = 10; % Theoretical covariance matrix Rnn_th = sigma2*eye(Lvec); % Theoretical eigenvalues (should all be sigma2) lambda_th = sort(eig(Rnn_th),'descend'); lambda = zeros(Lvec,Ntrials); for trial = 1:Ntrials % Generate new (complex) white Gaussian noise data n = sqrt(sigma2/2)*(randn(Lvec,N) + 1j*randn(Lvec,N)); % Sample covariance matrix Rnn = n*n'/N; % Save sample eigenvalues lambda(:,trial) = sort(eig(Rnn),'descend'); end % Estimated eigenvalue covariance matrix b = lambda - lambda_th(:,ones(1,Ntrials)); Rbb = b*b'/Ntrials % Predicted (approximate) theoretical result Rbb_th_approx = diag(lambda_th.^2/N) References:
[1] Friedlander, B.; Weiss, A.J.; , "On the second-order statistics of the eigenvectors of sample covariance matrices," Signal Processing, IEEE Transactions on , vol.46, no.11, pp.3136-3139, Nov 1998 [2] Kaveh, M.; Barabell, A.; , "The statistical performance of the MUSIC and the minimum-norm algorithms in resolving plane waves in noise," Acoustics, Speech and Signal Processing, IEEE Transactions on , vol.34, no.2, pp. 331- 341, Apr 1986
-11052078 0 SQL Server factors that can contribute to high CPU usageI am trying to figure out or enlist factors that contribute to persistent high CPU utilization related to SQL Server
Here are few that I came up with
a) Compilation or Frequent Recompilation of stored procs or queries
b) Poor performing queries that perform huge sort or ended up using Hash Join
c) Parallelism (multiple threads are span so it can keep CPU busy)
d) Looping construct in T-SQL for e.g. WHILE Loop or use of CURSOR
e) Missing or inappropriate indexes that leads to table scan
What are other SQL server operations can lead for a high CPU use?
-3879203 0 Tab focus granting eventI need to capture tab focus granting event in Firefox browser. Is there any type of listener implement for this event?
-8435774 0Check out lucene.net. While it won't directly integrate with your collection you can index things in memory using the RAMDirectory.
-16984929 0 double array in cell, how to indexing?I have an cell including array as below format
a{x,y,z}(i,j) a is 3 dimensional cell and each cell have i*j array
a <79x95x68 cell> val(:,:,1) = Columns 1 through 2 [6x6 double] [6x6 double] [6x6 double] [6x6 double] [6x6 double] [6x6 double] i want to rearrange that as below format
a{i,j}(x,y,z) how to? any good idea? i have to do iteration?
matlab say, a{:,:}(x,y,z) is bad cell referencing.........
-37010539 0 Wrong button sizes while using wpf xceed toolkit wizardI'm using the wizard from the wpf xceed toolkit. The problem is that the buttons are not the same sizes. All examples I can find show the buttons the same sizes. When I use it, the Cancel and Finish buttons are larger, and the Cancel button is clipped on the left side. Has anyone else experienced this, and do you have solutions?
Thanks.
-7849410 0 Already initialized constant warningsI'm using Nokogiri code to extract text between HTML nodes, and getting these errors when I read in a list of files. I didn't get the errors using simple embedded HTML. I'd like to eliminate or suppress the warnings but don't know how. The warnings come at the end of each block:
extract.rb:18: warning: already initialized constant EXTRACT_RANGES extract.rb:25: warning: already initialized constant DELIMITER_TAGS Here is my code:
#!/usr/bin/env ruby -wKU require 'rubygems' require 'nokogiri' require 'fileutils' source = File.open('/documents.txt') source.readlines.each do |line| line.strip! if File.exists? line file = File.open(line) doc = Nokogiri::HTML(File.read(line)) # suggested by dan healy, stackoverflow # Specify the range between delimiter tags that you want to extract # triple dot is used to exclude the end point # 1...2 means 1 and not 2 EXTRACT_RANGES = [ 1...2 ] # Tags which count as delimiters, not to be extracted DELIMITER_TAGS = [ "h1", "h2", "h3" ] extracted_text = [] i = 0 # Change /"html"/"body" to the correct path of the tag which contains this list (doc/"html"/"body").children.each do |el| if (DELIMITER_TAGS.include? el.name) i += 1 else extract = false EXTRACT_RANGES.each do |cur_range| if (cur_range.include? i) extract = true break end end if extract s = el.inner_text.strip unless s.empty? extracted_text << el.inner_text.strip end end end end print("\n") puts line print(",\n") # Print out extracted text (each element's inner text is separated by newlines) puts extracted_text.join("\n\n") end end
-18644597 0 I'm an FPDF noob myself but have you tried the AcceptPageBreak function?
Something like this (copied from fpdf website):
function AcceptPageBreak() { // Method accepting or not automatic page break if($this->col<2) { // Go to next column $this->SetCol($this->col+1); // Set ordinate to top $this->SetY($this->y0); // Keep on page return false; } else { // Go back to first column $this->SetCol(0); // Page break return true; } } As a reference, the fpdf tutorials are really helpful. I suspect this one in particular would help you for what you're doing.
-3326797 0You could add line-height:30px; to your li elements, (the same as the height of the menu bar)
DisplayLandlord PHP: I couldn't get the output.The query is not fetching the result
<?php include("dbconfig.php"); ?> <?php $query = "SELECT * FROM rmuruge4_landlord"; $result = mysqli_query(mysqli_connect(),$query); if ($result === false) {die(mysqli_error(mysqli_connect())); } echo "<div class='bs-example'>"; echo "<table class='table table-striped'>"; echo "<tr><th>LLID</th><th>LName</th><th>Phone</th><th>Address</th></td>"; while($row = mysqli_fetch_array($result)){ echo "<tr><td>" . $row['LLID'] . "</td><td >" . $row['LName'] . "</td><td >". $row['Phone'] . "</td><td >" . $row['Address'] . "</td></tr>"; } echo "</table>"; echo "</div>"; mysqli_close(mysqli_connect()); ?> dbconfig.php: Connection is successful
-23504102 0 Instead of Redirect you can use RedirectMatch directive for its regex capability:
RedirectMatch 301 ^/cars/?$ https://www.mydomain.com/cars/carshome/
-7946771 0 UIDocumentInteractionController or QLPreviewController can't zoom PDF on iOS5? I use QLPreviewController to view PDF files in one of my apps. However, ever since iOS5, users can no longer pinch to zoom in/out of the PDF. This is terrible for iPhone users, as they can't read anything.
I have also tried using UIDocumentInteractionController but have had the same problem.
Anyone know what's going on with this?
-28928062 0 Hovercard not displaying in knockoutJS with-bindingI got this hover card and I want to display it inside a sub-menu. It works int the header, but somehow the hover effect does not kick in when inside the sub-menu "with:$root.chosenMenu"-bindings.
This is my code:
HTML:
<div> <span class="previewCard"> <label class="hovercardName" data-bind="text: displayName"></label> <span class="hovercardDetails"> <span data-bind="text: miniBio"></span>.<br/> <a data-bind="attr: { href: webpage, title: webpage }, text: webpage">My blog</a> </span> </span> <br/><br/> <div class="wysClear wysLeft buttonRow"> <a href="#pid1" data-bind="click: function(){$root.chosenMenu('a');return false;}">Panel A</a> <a href="#pid2" data-bind="click: function(){$root.chosenMenu('b');return false;}">Panel B</a> </div> </div> <hr/> <div data-bind="with: $root.chosenMenu"> <div id="pid1" data-bind="visible: $root.chosenMenu() === 'a'"> panel A: <br/><br/> <span class="previewCard"> <label class="hovercardName" data-bind="text: $root.displayName"></label> <span class="hovercardDetails"> <span data-bind="text: $root.miniBio"></span>.<br/> <a data-bind="attr: { href: $root.webpage, title: $root.webpage }, text: $root.webpage">My blog</a> </span> </span> </div> <div id="pid2" data-bind="visible: $root.chosenMenu() === 'b'"> panel B: <br/><br/> <span class="previewCard"> <label class="hovercardName" data-bind="text: $root.displayName"></label> <span class="hovercardDetails"> <span data-bind="text: $root.miniBio"></span>.<br/> <a data-bind="attr: { href: $root.webpage, title: $root.webpage }, text: $root.webpage">My blog</a> </span> </span> </div> </div> Javascript:
viewModel = function(){ var self = this; self.chosenMenu = ko.observable(); self.displayName = ko.observable("Asle G"); self.miniBio = ko.observable("Everywhere we go - there you are!"); self.webpage = ko.observable("http://blog.a-changing.com") }; ko.applyBindings( new viewModel() ); // hovercard $(".previewCard").hover(function() { $(this).find(".hovercardDetails").stop(true, true).fadeIn(); }, function() { $(this).find(".hovercardDetails").stop(true, true).fadeOut(); }); CSS:
.previewCard { position:relative; } .hovercardName { font-weight:bold; position:relative; z-index:100; /*greater than details, to still appear in card*/ } .hovercardDetails { background:#fff ; border:solid 1px #ddd; position:absolute ; width:300px; left:-10px; top:-10px; z-index:50; /*less than name*/ padding:2em 10px 10px; /*leave enough padding on top for the name*/ display:none; } Fiddle: http://jsfiddle.net/AsleG/jb6b61oh/
-10152052 0You can send a direct update statement to the Oracle Engine in this way.
using (OracleConnection cnn = new OracleConnection(connString)) using (OracleCommand cmd = new OracleCommand("UPDATE TABLE1 SET BIRHDATE=:NewDate WHERE ID=:ID", cnn)) { cmd.Parameters.AddWithValue(":NewDate", YourDateTimeValue); cmd.Parameters.AddWithValue(":ID", 111); cnn.Open(); cmd.ExecuteNonQuery(); } EDIT:
If you don't know which fields are changed (and don't want to use a ORM Tool) then you need to keep the original DataSource (a datatable, dataset?) used to populate initially your fields. Then update the related row and use a OracleDataAdapter.
using(OracleConnection cnn = new OracleConnection(connString)) using (OracleCommand cmd = new OracleCommand("SELECT * FROM TABLE1 WHERE 1=0", cnn)) { OracleAdapter adp = new OracleDataAdapter(); adp.SelectCommand = cmd; // The OracleDataAdapter will build the required string for the update command // and will act on the rows inside the datatable who have the // RowState = RowState.Changed Or Inserted Or Deleted adp.Update(yourDataTable); } Keep in mind that this approach is inefficient because it requires two trip to the database. The first to discover your table structure, the second to update the row/s changed. Moreover, for the OracleDataAdapter to prepare the UpdateCommand/InsertCommand/DeleteCommand required, it needs a primary key in your table.
On the contrary, this is handy if you have many rows to update.
The last alternative (and probably the fastest) is a StoredProcedure, but in this case you need to go back to my first example and adapt the OracleCommand to use a StoredProcedure, (Add all fields as parameters, change CommandType to CommandType.StoredProcedure and change the text of the command to be the name of the StoredProcedure). Then the StoredProcedure will choose which fields need to be updated.
-3698683 0You should replace the ArrayList with an ObservableCollection<string> which will communicate to the ListBox when its contents change.
-29126463 0 Angularjs $scope is confusing meI really need some help here... I´m trying for hours now and can´t get it to work...
I have a .json file with 100 products like this:
[{ "ean": "3613132010420", "brand": "NewBrand", "desc": "A description", "feature1": "", "feature2": "", "feature3": "", "feature4": "", "feature5": "", "img": "", "metric": { "gender": "female", }, "score":"" }, { "ean": "3613132010420", "brand": "NewBrand", "desc": "A description", "feature1": "", "feature2": "", "feature3": "", "feature4": "", "feature5": "", "img": "", "metric": { "gender": "female", }, "score":"" }] I read the json with $http and put everything in $scope.products. The data is shown in a list, everything is fine. Now I want to filter the products and alter the score variable (after swipe on a option slider).
The view should then also be updated due to the angular data-binding.
How can I change this variable in the $scope? This is what I tried and nothing works:
$('.find-style-slider .slick-list').bind('touchstart click', function(){ angular.forEach($scope.products, function(value, key) { $scope.products[key].score = '25'; //nothing happens var obj = { score: '25' }; $scope.products[key].push(obj); //Uncaught TypeError: undefined is not a function $scope.products.splice(key, 0, obj); //no error but $scope variable does not change $scope.products[key].unshift(obj); //Uncaught TypeError: undefined is not a function }); }); Do I need to update something or $apply()? I would be thankful for any help/hint...
Edit: I think the $scope is not working like I thought.... I fill the $scope.products with a service:
productService.initDb().then(function(products) { $scope.products = products; }); When I put this
var obj = { score: '25' }; $scope.products.splice(0, 0, obj); INSIDE the initDb function then the first elements gets updated! But not outside.
The question is now: WHY? And how can I access the $scope.products from outside the service function?
I thought the $scope is the same for the whole controller... confused
-15691866 0Basically you need to find the li.k-item and pass it to the select method. Here comes the jQuery:
var ts = $('#tabstrip').data().kendoTabStrip; var item = ts.tabGroup.find(':contains("What you look for")'); ts.select(item);
-6342781 0 javax.validation.ConstraintValidationException: validation failed for classes I am developing a web application using Spring 3.1, Hibernate 3 and Hibernate Validator 4 in the backend. I'm using JSR 303 for the validation. This is done via annotations in the domain class.
public class StaffMember implements Serializable { @NotNull @Size(max = 30) // All letters, spaces and hyphens are allowed @Pattern(regexp = "^[^0-9_.]+$", message = ("Es sind nur Buchstaben, Leerzeichen und Bindestrich erlaubt.")) private String firstname; } I have written a test class for testing the CRUD operations in the DAO class. This class runs without errors for valid data. Now I want to edit an existing object. Therefore I change the first name. I specify an invalid name because I want to write a negative test case.
// Allows Spring to configure the test @RunWith(SpringJUnit4ClassRunner.class) // Define which configuration should be used @ContextConfiguration(locations = { "classpath:portal-test.xml" }) @TransactionConfiguration(transactionManager = "transactionManager", defaultRollback=false) // All methods are transactional @Transactional public class StaffMemberDAOTest { private StaffMember staffMember, nextStaffMember; @Autowired private StaffMemberDAO staffMemberDao; @Autowired private Validator validator; @Test(expected = ConstraintViolationException.class) @Transactional @Rollback(true) public void testUpdateStaffMemberWithInvalidData() { System.out.println("--- update a staffMember (with invalid data) ---"); // check if database is empty Assert.assertEquals(0, staffMemberDao.getAllStaffMembers().size()); // add staffMember createStaffMember(); // validate Set<ConstraintViolation<StaffMember>> violations = validator .validate(staffMember); // object is valid if(violations.size() == 0) { staffMemberDao.addStaffMember(staffMember); } else { System.out.println("Object is not valid."); } // get staffMember StaffMember staffMemberExpected = staffMemberDao.getStaffMember(staffMember.getStaffMemberID()); // check data Assert.assertEquals(staffMember, staffMemberExpected); // edit data staffMemberExpected.setFirstname("George No 1"); // validate Set<ConstraintViolation<StaffMember>> violationsUpdate = validator .validate(staffMemberExpected); // object is valid if(violationsUpdate.size() == 0) { staffMemberDao.editStaffMember(staffMemberExpected); } else { System.out.println("Object is not valid."); } } The system rightly raises the following error message: javax.validation.ConstraintValidationException In this case the expected exception must to be indicated. In JUnit 4 is this possible about @Test(expected).
I do this but i get the following error message:
java.lang.AssertionError: Expected exception: javax.validation.ConstraintViolationException at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:32) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:236) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) javax.validation.ConstraintViolationException: validation failed for classes [de.softwareinmotion.portal.domain.StaffMember] during update time for groups [javax.validation.groups.Default, ] at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.validate(BeanValidationEventListener.java:155) at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.onPreUpdate(BeanValidationEventListener.java:102) at org.hibernate.action.EntityUpdateAction.preUpdate(EntityUpdateAction.java:235) at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:86) at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:265) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:185) at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321) at org.hibernate.event.def.DefaultAutoFlushEventListener.onAutoFlush(DefaultAutoFlushEventListener.java:64) at org.hibernate.impl.SessionImpl.autoFlushIfRequired(SessionImpl.java:1185) at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1261) at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102) at de.softwareinmotion.portal.persistence.StaffMemberDAO.getAllStaffMembers(StaffMemberDAO.java:37) at de.softwareinmotion.portal.persistence.StaffMemberDAO$$FastClassByCGLIB$$ae2a690a.invoke(<generated>) at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:688) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:621) at de.softwareinmotion.portal.persistence.StaffMemberDAO$$EnhancerByCGLIB$$8fbc7a01.getAllStaffMembers(<generated>) at de.softwareinmotion.portal.persistence.StaffMemberDAOTest.tearDown(StaffMemberDAOTest.java:542) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:37) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:236) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) Here is my portal-test.xml file:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> <context:property-placeholder location="classpath:jdbcTest.properties" /> <context:annotation-config/> <tx:annotation-driven transaction-manager="transactionManager"/> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${db.driverClass}" /> <property name="url" value="${db.jdbcUrl}" /> <property name="username" value="${db.user}" /> <property name="password" value="${db.password}" /> </bean> <!-- Hibernate config --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="annotatedClasses"> <list> <!-- Each domain class must be listed here --> <value>de.softwareinmotion.portal.domain.StaffMember</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">create</prop> </props> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- Necessary for validation --> <bean name="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <!-- <property name="validationMessageSource"> <ref bean="resourceBundleLocator"/> </property> --> </bean> <!-- <bean name="resourceBundleLocator" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="/WEB-INF/validation-messages" /> </bean> --> <!-- Each DAO object must be declared here! --> <bean id="staffMemberDao" class="de.softwareinmotion.portal.persistence.StaffMemberDAO"> <property name="sessionFactory" ref="sessionFactory"/> </bean> </beans> What I'm doing wrong? Can anybody help me?
-27795202 0It's not flushed at this moment, changes kept in memory for a while. If you need to force Grails to update DB exactly at this moment, add flush: true parameter:
person.save(flush: true)
-30085992 0 I found this:
https://github.com/facebook/stetho/issues/42
TL;DR: If you are using proguard add this to your config:
-keep class com.facebook.stetho.** {*;}
Here is the problem. I have a radiobutton group (two radiobuttons).
These guys are initialy disabled. When the user clicks a checkbox, I dynamically enable radiobuttons in javascript by setting rbtn.disabled = false; and doing the same for it's parent (span element) so it correctly works in IE. The problem is that these dynamically enabled radiobuttons are not returned on postback (I see rbtn.Checked == false on serverside and request.form does not contain proper value).
Why is this happening? Is there another fix except for a workaround with hidden fields?
Expected answer decribes post-back policy, why/how decides which fields are included in postback and fix to this problem.
-21883693 0Try This:
int maxNo = 4; //you can change this no and logic works till 9 comboboxes void clearPreceding(ComboBox cmbBox) { int cmbBoxNo = Convert.ToInt32(cmbBox.Name.Substring(cmbBox.Name.Length - 1)); for (int i = cmbBoxNo; i <= maxNo; i++) { ((ComboBox)this.Controls.Find("comboBox" + i, true)[0]).Text = ""; } } You can Subscribe to One EventHandler for all Combobox's SelectedIndexChanges Event as below:
comboBox1.SelectedIndexChanged += AllCombobox_SelectedIndexChanged; comboBox2.SelectedIndexChanged += AllCombobox_SelectedIndexChanged; comboBox3.SelectedIndexChanged += AllCombobox_SelectedIndexChanged; comboBox4.SelectedIndexChanged += AllCombobox_SelectedIndexChanged; and the EventHandler is:
private void AllCombobox_SelectedIndexChanged(object sender, EventArgs e) { clearPreceding((ComboBox)sender); } Complete Code:
public partial class Form1 : Form { int maxNo = 4; public Form1() { InitializeComponent(); comboBox1.SelectedIndexChanged+=AllCombobox_SelectedIndexChanged; comboBox2.SelectedIndexChanged += AllCombobox_SelectedIndexChanged; comboBox3.SelectedIndexChanged += AllCombobox_SelectedIndexChanged; comboBox4.SelectedIndexChanged += AllCombobox_SelectedIndexChanged; } private void AllCombobox_SelectedIndexChanged(object sender, EventArgs e) { clearPreceding((ComboBox)sender); } void clearPreceding(ComboBox cmbBox) { int cmbBoxNo = Convert.ToInt32(cmbBox.Name.Substring(cmbBox.Name.Length - 1)); for (int i = cmbBoxNo; i <= maxNo; i++) { ((ComboBox)this.Controls.Find("comboBox" + i, true)[0]).Text = ""; } } }
-16844290 0 Excel Loading via c# Try to Load an excel file using this code below gives me this error
The Microsoft Access database engine could not find the object 'Sheet Name'. Make sure the object exists and that you spell its name and the path name correctly. If 'Sheet Name' is not a local object, check your network connection or contact the server administrator.
i am sure the Sheet Name is correct.
Any suggestions?
if (strFile.Trim().EndsWith(".xlsx")) { strConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", strFile); } else if (strFile.Trim().EndsWith(".xls")) { strConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", strFile); } OleDbConnection SQLConn = new OleDbConnection(strConnectionString); SQLConn.Open(); OleDbDataAdapter SQLAdapter = new OleDbDataAdapter(); string sql = "SELECT * FROM [" + sheetName + "]"; OleDbCommand selectCMD = new OleDbCommand(sql, SQLConn); SQLAdapter.SelectCommand = selectCMD; ///error in this line SQLAdapter.Fill(dtXLS); SQLConn.Close();
-7197592 0 This strike me as odd- Why do you use
label.text = [[NSString alloc] initWithString:@"Manufacture :"]; as opposed to
label.text = @"Manufacture :"; The way it is, your not releasing your strings. using the @"xxx" short hand creates a string that is autoreleased. Not confident that this is the cause of your problem but screwy memory mgmt with strings can produce effects like your seeing. So cleaning it up would be a good start.
Also, make sure that in IB you made the cell have a reference to the file owners' vehicleSearchCell property. More of a stab in the dark.
-17545781 0As others have said, IE8 does not support the nth-child() selector in CSS.
You have the following options:
Refactor your code to use an alternative method rather than nth-child(). Maybe just add a class to the relevant elements.
Use a javascript polyfill such a IE9.js or Selectivizr, which back-ports the nth-child() selector (and others) to IE8.
Use jQuery or a similar library that supports nth-child() to set the styles rather than doing it in CSS.
Drop support for IE8.
Which of those options you decide to use will depend on what matters to you.
If you've got code that works in other browsers and you need it to work in IE8 with the least amount of additional work, then I would suggest trying out the Selectivizr library. Or IE9.js. But I'd suggest trying Selectivizr first, as IE9.js does a lot of other stuff to the browser that may or may not affect your site.
If you don't want to have to use a Javascript library for this but you still need IE8 support, then you'll need to take option 1, and refactor your code. That may or may not be a lot of work, depending how your code is structured and how much code there is. Bit of a shame to have to make a backward step when the CSS is there.
Option 4 sounds like the worst option, but might be more suitable than it sounds. If the nth-child styling is being used for something like zebra striping, it may not be the end of the world for IE8 users just to not get the stripes. If everything else in the site works okay, they may not even miss it. And if they do miss it, you can tell them to upgrade their browser.
Dear if you are working on a local server just like XAMPP or APPSERV or whatsoever you have to install mail server on you local machine
and if you are working on a real host server make sure the the php setting in the server allow you to use mail function cuse many server has stop this function.
so i recommend you to use smtp to send mail take a look here
http://email.about.com/od/emailprogrammingtips/qt/PHP_Email_SMTP_Authentication.htm
and there is a supper powerful library to send email PHPMailer
https://code.google.com/a/apache-extras.org/p/phpmailer/
-30910328 0The vector handles its memory outside of the structure, in the heap as mentioned in another answer. So resizing or reallocating the vector inside the structure won't change the structure's size at all, not even the vector containing that structure.
http://www.cplusplus.com/reference/vector/vector/
The vector handles its own memory dynamically ( in the heap ).
-6334498 0 Recognize "Invalid" URLs without Trying to Resolve ThemI'm building a Facebook App which grabs the URLs from various sources in a user's Facebook acount--e.g., a user's likes.
A problem I've encountered is that many Facebook entries have string which are not URLs in their "website" and "link" fields. Facebook does no checking on user input so these fields can essentially contain any string.
I want to be able to process the strings in these field such that URLs like "http://google.com", "https://www.bankofamerica.com", "http://www.nytimes.com/2011/06/13/us/13fbi.html?_r=1&hp", "bit.ly", "www.pbs.org" are all accepted.
And all the strings like "here is a random string of text the user entered", "here'\s ano!!! #%#$^ther weird random string" are all rejected.
It seems to me the only way to be "sure" of a URL is to attempt to resolve it, but I believe that will be prohibitively resource intensive.
Can anyone think of clever way to regex or otherwise analyze these strings such that "a lot" of the URLS are properly captured--80%? 95% 99.995% of URLs?
Thanks!
EDIT: FYI, I'm developing in Python. But a language agnostic solution is great as well.
-24200387 0You are using latest one so it get like this. Don't worry about it.
public class MainActivity extends ActionBarActivity instead of
public class MainActivity extends Activity Remove all code in your MainActivity except OnCreate(). Then you follow your tutorial.
You onCreate should be
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }
-26345236 0 In order to fix the 'shifting' of the entire page, add this between the second and third sub-story element (Basically, where a new row starts). That issue is caused by float positioning of elements of different heights.
<div style="clear:both;"></div>
-32085596 0 The if statement is not reachable because you always showed button1content
$('#button1content').toggle('show'); So var wasVisible = $("#button1content").is(":visible"); will always result to true
i´m trying to update rows in mysql table, i´m using html form for data insertion. In html form attribute value i´m using an existing data from database.
Edit.jsp
<form action="Update.jsp"> <% Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root"); Statement st = con.createStatement(); ResultSet rs = st.executeQuery("select u.login,i.name,i.surname,i.age,i.tel,i.email,a.street,a.town,a.zip,ul.name,t.name from users u join info i on i.user_id=u.user_id join user_level ul on ul.ulevel=u.ulevel join teams t on t.team_id=u.team_id join adress a on a.info_id=i.info_id where u.login='" + session.getAttribute("uzivatel") + "'"); while (rs.next()) { %> <div class="well well-large"> <font size="2"><b>Welcome, </b></font><font color="RED"><i><%= session.getAttribute("uzivatel")%></i></font><br> <b>Name:</b> <input type="text" name="name" value="<%= rs.getString(2)%>"><input type="text" name="surname" value="<%= rs.getString(3)%>"> <br> <b>Age:</b> <input type="text" name="age" value="<%= rs.getString(4)%>"><br> <b>Telephone:</b> <input type="text" name="tel" value="0<%= rs.getString(5)%>"><br> <b>E-mail:</b> <input type="text" name="email" value="<%= rs.getString(6)%>"><br> <b>Adress:</b> <input type="text" name="street" value="<%= rs.getString(7)%>"><input type="text" name="town" value="<%= rs.getString(8)%>"><input type="text" name="zip" value="<%= rs.getString(9)%>"><br> <b>User level:</b> <%= rs.getString(10)%><br> <b>Team:</b> <%= rs.getString(11)%><br> <input type="submit" name="Submit" value="Update" /> </div> </form> Update.jsp
<% String name = request.getParameter("name"); String surname = request.getParameter("surname"); String age = request.getParameter("age"); String telephone = request.getParameter("tel"); String email = request.getParameter("email"); String street = request.getParameter("street"); String town = request.getParameter("town"); String zip = request.getParameter("zip"); try { Connection conn = null; Class.forName("com.mysql.jdbc.Driver").newInstance(); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root"); Statement st1 = null; st1 = conn.createStatement(); System.out.println(session.getAttribute("uzivatel")); st1.executeUpdate("UPDATE users JOIN info ON users.user_id = info.user_id" + " JOIN adress ON info.info_id = adress.info_id" + "SET info.name = '"+name+"',info.surname = '"+surname+"'," + "info.age = '"+age+"',info.tel = '"+telephone+"',info.email = '"+email+"'," + "adress.street = '"+street+"',adress.town = '"+town+"',adress.zip = '"+zip+"'," + "WHERE users.login ='" + session.getAttribute("uzivatel") + "' "); response.sendRedirect("AdministrationControlPanel.jsp"); } catch (Exception e) { System.out.println(e.getMessage()); } %> When I pressed the Submit button, it redirected me to Update.jsp and nothing was changed.
I understand that in Javascript a function can return another function and it can be called immediately. But I don't understand the reason to do this. Can someone please explain the reason and benefit why you might want to do this in your code? Also, is the function that returns 'hello' considered a closure?
function a () { return function () { console.log('hello'); } } //then calling the function a()();
-39927136 0 Javascript swapping values I need to be able to go through a randomized 3 x 3 matrix and check to see if the numbers are in order (i.e. that the top row is 1-3, center 4-6 and bottom 7-9). So far i wrote this function in JS:
function winningorder(topleft, topcenter, topright, centerleft, centercenter, centerright, bottomleft, bottomcenter, bottomright){ if(document.getElementById(topleft).innerHTML = 1 && document.getElementById(topcenter).innerHTML = 2 && document.getElementById(topright).innerHTML = 3 && document.getElementById(centerleft).innerHTML = 4 && document.getElementById(centercenter).innerHTML = 5 && document.getElementById(centerright).innerHTML = 6 &&document.getElementById(bottomleft).innerHTML = 7 && document.getElementById(bottomcenter).innerHTML = 8 && document.getElementById(bottomright).innerHTML = 9){ setTimeout(function(){ alert("Well Done!"); }, 250); } I do not know if i need to put all the locations (the HTML id of each cell) as the parameters, so that is my first question. Secondly, where would i put my function in the HTML code. the code is:
<table border=1> <tr class="numberrow"> <td id="topleft" class="numbertile" onclick="processclick(this.id)" onchange=="winningorder(id)" ></td> <td id="topcenter" class="numbertile" onclick="processclick(this.id)" onchange=="winningorder(id)"></td> <td id="topright" class="numbertile" onclick="processclick(this.id)" onchange=="winningorder(id)"></td> </tr> <tr class="numberrow"> <td id="centerleft" class="numbertile" onclick="processclick(this.id)" onchange=="winningorder(id)"></td> <td id="centercenter" class="numbertile" onclick="processclick(this.id)" onchange=="winningorder(id)"></td> <td id="centerright" class="numbertile" onclick="processclick(this.id)" onchange=="winningorder(id)"></td> </tr> <tr class="numberrow"> <td id="bottomleft" class="numbertile" onclick="processclick(this.id)" onchange=="winningorder(id)"></td> <td id="bottomcenter" class="numbertile" onclick="processclick(this.id)" onchange=="winningorder(id)"></td> <td id="bottomright" class="numbertile" onclick="processclick(this.id)" onchange=="winningorder(id)"></td> </tr> My first though was to use an onchange event and run the function but that is not working. Thanks for any help!
-15428036 0 how to remove 3 lines in row if the first line contain a specific character?I have a data file (which a matrix with 290 lines and 2 columns) like this:
# RIR1 ABABABABABABABABAA ABABABABABABABABBA # WR ABABABABABABABABAB BABABBABABABABABAA # BR2 ABABABABABABABBABA ABBABABABABABABABA # SL AAABABABABABABBABA AAABBABABABABABABA I would like to remove all the data that are for SL and WR (as example). So I will have only:
# RIR1 ABABABABABABABABAA ABABABABABABABABBA # BR2 ABABABABABABABBABA ABBABABABABABABABA I know how to remove one line that start or contain something but no idea how to do with 3 lines in row.
this is what I use for one line:
old<-old[!substr(old[1,],1,5)=="# BR2",] old<-old[!substr(old[1,],1,6)=="# RIR1",] thanks in advance.
-398193 0This is what transactions are for. Your booking code should BEGIN a transaction, confirm that the time is available using SELECT, and if it is available, INSERT or UPDATE the database to make the reservation, finally COMMITing the transaction.
If the time is not available, either don't INSERT or UPDATE the database to make the reservation, or ROLLBACK the transaction.
-11368162 0 8Bit Grayscale Bitmap to ArrayI am wondering, from here how would I go about storing the pixel values into a matrix? I would like to print out the intensity (grayscale) value.
Example Array[5] = 4 Or Array[3][1] = 17
I really have no idea how to go about this. All the examples I see seem way to complicated, is there a simple way to do this?
#include <stdio.h> #include <stdlib.h> #include <string.h> struct BitMap { short Type; long Size; short Reserve1; short Reserve2; long OffBits; long biSize; long biWidth; long biHeight; short biPlanes; short biBitCount; long biCompression; long biSizeImage; long biXPelsPerMeter; long biYPelsPerMeter; long biClrUsed; long biClrImportant; }Header; int main( void ){ FILE *BMPFile = fopen ("MriHotrod.bmp", "rb"); if(BMPFile == NULL){ return; } unsigned char DataBuff[128*128]; int i; int j; memset(&Header, 0, sizeof(Header)); fread(&Header.Type, 2, 1, BMPFile); fread(&Header.Size, 4, 1, BMPFile); fread(&Header.Reserve1, 2, 1, BMPFile); fread(&Header.Reserve2, 2, 1, BMPFile); fread(&Header.OffBits, 4, 1, BMPFile); fread(&Header.biSize, 4, 1, BMPFile); fread(&Header.biWidth, 4, 1, BMPFile); fread(&Header.biHeight, 4, 1, BMPFile); fread(&Header.biPlanes, 2, 1, BMPFile); fread(&Header.biBitCount, 2, 1, BMPFile); fread(&Header.biCompression, 4, 1, BMPFile); fread(&Header.biSizeImage, 4, 1, BMPFile); fread(&Header.biXPelsPerMeter, 4, 1, BMPFile); fread(&Header.biYPelsPerMeter, 4, 1, BMPFile); fread(&Header.biClrUsed, 4, 1, BMPFile); fread(&Header.biClrImportant, 4, 1, BMPFile); printf("\nType:%hd\n", Header.Type); printf("Size:%ld\n", Header.Size); printf("Reserve1:%hd\n", Header.Reserve1); printf("Reserve2:%hd\n", Header.Reserve2); printf("OffBits:%ld\n", Header.OffBits); printf("biSize:%ld\n", Header.biSize); printf("Width:%ld\n", Header.biWidth); printf("Height:%ld\n", Header.biHeight); printf("biPlanes:%hd\n", Header.biPlanes); printf("biBitCount:%hd\n", Header.biBitCount); printf("biCompression:%ld\n", Header.biCompression); printf("biSizeImage:%ld\n", Header.biSizeImage); printf("biXPelsPerMeter:%ld\n", Header.biXPelsPerMeter); printf("biYPelsPerMeter:%ld\n", Header.biYPelsPerMeter); printf("biClrUsed:%ld\n", Header.biClrUsed); printf("biClrImportant:%ld\n\n", Header.biClrImportant); fread(DataBuff, sizeof(DataBuff), 128*128, BMPFile); for(i=0; i<20; i++){ printf("%d\n", DataBuff[i]); } fclose(BMPFile); return 0; } Output Type:19778 Size:17462 Reserve1:0 Reserve2:0 OffBits:1078 biSize:40 Width:128 Height:128 biPlanes:1 biBitCount:8 biCompression:0 biSizeImage:0 biXPelsPerMeter:0 biYPelsPerMeter:0 biClrUsed:256 biClrImportant:0 0 0 0 0 1 1 1 0 2 2 2 0 3 3 3 0 4 4 4 0 I think the header info is correct, and the number of elements is correct (16384). I am just unsure how to print out the pixel values. The above is clearly not right...
Does this have to do with padding?
Thanks!
-26748141 0 can't find mpif.h compiling error?i have download a big ecosystem model (Ecosystem Demography) which must e compiled in linux and it uses MPI and hdf5. i have installed the mpich (on centOS 7) to compile the ED model with Gfortran compiler. but it gives me the famous error
Can't find file: mpif.h i have looked for the file by "which mpif.h" and it returns nothing so i set the PATH as follow :
PATH=/home/hamid/edpacks/mpich-install/bin:$PATH export PATH now which mpif.h returns the path to the file but again when i try to ./install the model it give me the same error. problem is i don't know how to set this path and also path to mpich from inside the model. Do i have to set the path from include file or makefile?
-26202667 0 In AngularJS, how does $scope get passed to scope?I'm a bit confused with the use of $scope in controllers and of scope in directives. Please verify if my understanding is correct (and also provide some alternative ways how to do this).
Let's say I have an html:
<div ng-controller="app1_Ctrl"> . . . <input type="text" ng-model="value"/> <input type="checkbox" /> <button ng-click="submit()"></button> </div> And my main.js
(function() { angular.module('mainApp', ['app1']); })(); And my app1 looks like this (based on official AngularJS documentation here)
(function() { var app = angular.module('app1', []); app.controller('app1_Ctrl', ["$scope", function($scope) { . . . }]); app.directive('app1_Dir1', [function() { function link(scope, element, attr) { scope.$watch(attr.someAttrOfCheckBox, function() { // some logic here }); function submit() { // some logic here } } return link; }]); })(); How does $scope.value passed in scope in directive so that I can do some manipulations there? Will ng-click fire the function submit() in the directive link? Is it correct to use scope.$watch to listen for an action (ticked or unticked of course) in checkbox element?
Many thanks to those who can explain.
-26893775 0Try something like
connect(Bgn,End,Path) :- % to find a path between two nodes in the graph connected(Bgn,End,[],P) , % - we invoke the helper, seeding the visited list as the empty list reverse(P,Path) % - on success, since the path built has stack semantics, we need to reverse it, unifying it with the result . connected(X,Y,V,[X,Y|V]) :- % can we get directly from X to Y? path(X,_,Y) % - if so, we succeed, marking X and Y as visited . % connected(X,Y,V,P) :- % otherwise... path(X,_,T) , % - if a path exists from X to another room (T) T \= Y , % - such that T is not Y \+ member(X,V) , % - and we have not yet visited X connected(T,Y,[X|V],P) % - we continue on, marking X as visited. . You'll note the test for having visited the room before. If your graph has cycles, if you don't have some sort of test for having previously visited the node, you'll wind up going around and around in circles...until you get a stack overflow.
-16179110 0That is not valid JSON, so you cannot do it with standard methods.
You either have to escape the quotes like this: "sport is \" " or else you need to write your own sanitizer
I am creating an app in which there are two UIViews and in those UIViews I am loading Tableviews.. When I click a tablecell in one TableView then I am unable to redirect it to another TableView and getting error:Program received signal SIGABRT.But if I want to load a UIView when a tablecell is clicked it gets executed perfectly.I couldn't understand where Am I going wrong.... This is the code i'm writing
ViewController1: #import ViewController2.h" -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { ViewController2 *v2 = [ViewController alloc] initWithNibName:@"ViewController2" bundle:[NSBundle mainBundle]]; [self presentModalViewController:v2 animated:NO]; **//getting error at this line** [v2 release]; } ViewController2.h #import"ViewController1.h" - (void)viewDidLoad { [super viewDidLoad]; tableView1 = [[UITableView alloc]initWithFrame:CGRectMake(10, 10, 320, 460)]; tableView1.delegate = self; tableView1.dataSource = self; [self.view addSubview:tableView1]; } Couldn't understand what could be the possible cause of this error..
-34104103 0In BigInt, note /% operation which delivers a pair with the division and the reminder (see API). Note for instance
scala> BigInt(3) /% BigInt(2) (scala.math.BigInt, scala.math.BigInt) = (1,1) scala> BigInt(3) /% 2 (scala.math.BigInt, scala.math.BigInt) = (1,1) where the second example involves an implicit conversion from Int to BigInt.
I use this code:
public void getDefaultLauncher() { final Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); PackageManager pm = getPackageManager(); final List<ResolveInfo> list = pm.queryIntentActivities(intent, 0); pm.clearPackagePreferredActivities(getApplicationContext().getPackageName()); for(ResolveInfo ri : list) { if(!ri.activityInfo.packageName.equals(getApplicationContext().getPackageName())) { startSpecificActivity(ri); return; } } } private void startSpecificActivity(ResolveInfo launchable) { ActivityInfo activity=launchable.activityInfo; ComponentName name=new ComponentName(activity.applicationInfo.packageName, activity.name); Intent i=new Intent(Intent.ACTION_MAIN); i.addCategory(Intent.CATEGORY_LAUNCHER); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); i.setComponent(name); startActivity(i); } Maybe it works for you as well.
-25294939 0 How to make a JButton add user input to an ArrayList and display it in a JListI have an app that contains 3 classes - main gui (Book), add, contact.
I have a JList in my phonebook class. I have a dialog window as my add class as it needs to add a contact, now I can add the data but storing it into an array and then placing that into a JList is proving tricky.
Would anyone be able to help? I am new to java and I understand that I will need to use defaultListModel at some point but I don't quite understand where
My button in the add class is called btnOK my arraylist is just ArrayListcontact my JList is just called list.
Thanks to anyone who can help!
-35737341 0You are referencing to the wrong API. The link you have provided is for the Google Play Developer API which is for subscription, in-app purchase and publishing. The API for sharing progress and other in-game API calls is the Google Play Games Services which has a default quota of 50000000 requests/day and in which the user can have 500 requests per second(The quotas can be seen in the Developer's Console). You could also see Managing Quota and Rate Limiting for other info about the quota and limits.
-21983359 0 Compojure/Clojure error with routesI am making a web-app using Clojure/ring/compojure and am having trouble with the routing. I have two files: web.clj and landing.clj. I want to route the user who navigates to the uri from the web.clj handler to the landing.clj one and for the home function to be called which will render the front page of my app. I can't for the life of me seem to grok the semantics, please help. Documentation that I read assumes a lot of web-dev knowledge and I am a beginner. I am now getting a 404 error message in the browser when I run the local server from Leiningen. I know That it is going through the defroutes in the landing.clj file, because the address bar shows http://0.0.0.0:5000/landing, when I load http://0.0.0.0:5000.
This is the code for my web.clj file, which successfully redirects to the landing.clj file:
(defroutes app (ANY "/repl" {:as req} (drawbridge req)) (GET "/" [] (redirect "landing")) ;; come fix this later (ANY "*" [] (route/not-found (slurp (io/resource "404.html"))))) This is from the landing.clj file, the error is located somewhere with the GET "/" function:
(defroutes app (GET "/" [] {:status 200 :headers {"Content-Type" "text/html"} :body (home)}) (POST "/" [weights grades] ((process-grades (read-string weights) (read-string grades)) )) (ANY "*" [] (route/not-found (slurp (io/resource "404.html")))))
-6101225 0 You can also comment a block with =begin and =end like this:
<% =begin %> <%= link_to "Sign up now!", signup_path, :class => "signup_button round" %> <% =end %>
-37818981 0 By default the body on the page has this css:
body { display: block; margin: 8px; } body:focus { outline: none; } at the top of your css file just add:
body { margin:0; } this way you're working with 0 margins to begin with.
-7556033 0 Load or functional testing of GWT app using JMeterI am new to JMeter. I wanted to do some functional testing of my GWT application using JMeter. Does it support GWT testing? For example I would like to write a script that might check if the login module of my GWT application is doing good or not. Please let me know if we have some sort of documentation specific to GWT testing with JMeter.
Thanks a million.
-- Mohyt
-4139738 0 Need help with a mIRC macroI'm trying to make a script that will automatically says "see you later" as soon as one specific handle in a channel says the words "going home". I tried to do it on my own but got lost. Could anyone help me out?
-7257281 0 Using doxygen to create documentation for existing C# code with XML commentsI've read everywhere that doxygen is the way to go for generating documentation for C# code. I've got a single interface that I want to document first (baby steps), and it already has the XML comments (///) present.
Because of the vast number of posts and information available (including doxygen.org) that say these comments are already supported, I'm surprised that when I run doxywizard, I get errors like "warning: Compound Company::Product::MyInterface is not documented".
This leads me to believe that I have somehow misunderstood XML documentation (hopefully not, according to MSDN I am talking about the right thing), or I have misconfigured doxywizard.
I first ran doxywizard via the Wizard tab, and specified that I want to support C#/Java. When I run it, my HTML page is blank, presumably because of the previously-mentioned warnings. I then tried specifying a single file via the Expert tab and ran again -- same behavior.
Can anyone tell me what switch or setting I'm missing to get doxygen to generate the HTML?
Here's an example of what a documented property/method looks like in my interface:
/// <summary> /// Retrieve the version of the device /// </summary> String Version { get; } /// <summary> /// Does something cool or really cool /// </summary> /// <param name="thing">0 = something cool, 1 = something really cool</param> void DoSomething( Int32 thing); I do have a comment above the interface, like this:
/// <summary> /// MyInterface /// </summary> public interface MyInterface {...}
-26267570 0 How to select rows from Table X who share the least relationships with Table Y? suppose we have the following two tables
TABLE: PEOPLE +----+------+ | id | name | +----+------+ | 1 | john | +----+------+ | 2 | mike | +----+------+ | 3 | derp | +----+------+ TABLE: Images +----+-----------+----------+ | id | person_id | image | +----+-----------+----------+ | 1 | 3 | img1.jpg | +----+-----------+----------+ | 2 | 3 | img2.jpg | +----+-----------+----------+ | 3 | 2 | img3.jpg | +----+-----------+----------+ I need to a query that selects all people from people table and orders them ASC by the ones that have the least images in the images table
So the order of the returned rows would be
John Mike Derp
-25096117 0 $ cat file [foo] name = 3 name = 17 [bar] name = 24 name = 5 $ awk -v id="foo" '/\[/{f=index($0,"["id"]")} f' file [foo] name = 3 name = 17 $ awk -v id="bar" '/\[/{f=index($0,"["id"]")} f' file [bar] name = 24 name = 5 The above just sets a flag (f for found) when it finds a line containing [foo], for example, and clears it when it finds the next line containing a [. When f is set it prints the line.
Note also that unlike any possible sed solution, the above will be unaffected by RE metacharacters or delimiter characters in the search variable (e.g. ., ?, *, +, /, (, etc.) since it is looking for a STRING not a regular expression.
In a small Delphi program I create few TCharts and TBarSeries programmatically on the runtime but then I want to be able to click on a bar of the chart and fire, for example, a Chart1ClickSeries event to display information of that bar. Is that possible??
-40642093 0Your best bet is to:
It will be pretty straight forward with jQuery. Below Fiddle will help you.
http://jsfiddle.net/17g6q8k0/2/
var sourceSwap = function () { var $this = $(this); var newSource = $this.data('alt-src'); $this.data('alt-src', $this.attr('src')); $this.attr('src', newSource); } $(function() { $('img[data-alt-src]').each(function() { new Image().src = $(this).data('alt-src'); }).hover(sourceSwap, sourceSwap); });
-40486918 0 Are AWS Security Group Port Ranges Inclusive or Exclusive AWS security groups allow a port range to be specified for permitted traffic, written in the form 1234-5678: would that be inclusive of ports 1234 and 5678, or exclusive of either/both of those ports?
The documentation doesn't seem to describe this.
-744275 0On the whole topic of IE6, whenever you get to that point of moving IT out of the past, you could use this:
http://code.google.com/p/ie6-upgrade-warning/
-18857214 0I also ran into the same issue. It would seem that the transactionReceipt on the originalTransaction will always return nil when restoring purchases. From the Discussion in the apple docs for transactionReceipt:
Discussion
The contents of this property are undefined except when transactionState is set to SKPaymentTransactionStateRestored.
Since during a restore (of a consumable item) the transactionState is always set to SKPaymentTransactionStatePurchased, the originalTransaction.transactionReceipt property will always be nil.
I have a simple flash video player that streams the video from a streaming media server. The stream plays fine and I have no problems with playing the video and doing simple functions. However, my problem is that on a mouse over of the video, I have the controls come up and when I do a seek or scrub on the video, I get little weird boxes that show over the video - like little pockets - of the video playing super fast (you can basically see it seeking) until it gets to the point it needs to be at and then these little boxes disappear. Is anybody else having these problems and if so, how do I fix this? I thought it might be some kind of masking problem, but I haven't been able to figure it out. Please Help!!!
-27319283 0If you took time to read the FineManual for pandas.DataFrame.to_sql, you would have found out by yourself:
if_exists : {‘fail’, ‘replace’, ‘append’}, default ‘fail’
fail: If table exists, do nothing. replace: If table exists, drop it, recreate it, and insert data. append: If table exists, insert data. Create if does not exist.
http://pandas.pydata.org/pandas-docs/version/0.15.1/generated/pandas.DataFrame.to_sql.html
For the record, it took me exactly 23s to find this once I had confirmation you were talking about Pandas.
-27900886 0The file's content includes $variables wich are expanded. To avoid variable expansion, I had to use single-quote escapes 'END'.
Perhaps this is something you are looking for:
from numpy.random import randint n = 50 R = randint(0,2,n) def get_number_of_zeros(x): return sum(0 == ele for ele in x) while(len(R) > 0): number_of_zeros = get_number_of_zeros(R) print 'number of zeros is {}'.format(number_of_zeros) R = randint(0, 2, number_of_zeros) Result:
number of zeros is 25 number of zeros is 11 number of zeros is 7 number of zeros is 4 number of zeros is 1 number of zeros is 1 number of zeros is 1 number of zeros is 0
-8678371 0 How to convert GPS degree to decimal and vice-versa in jquery or javascript and PHP? does someone know how to convert GPS degree to decimal values or vice versa?
I have to develop a way where users can insert an address and get the GPS values (both degree and/or decimal), but the main thing i need to know is how to convert the values, cause users can also insert GPS values (degree or decimal). Because i need to get the map from google maps this needs decimal.
I've tryed some codes but i get big numbers...like this one:
function ConvertDMSToDD(days, minutes, seconds, direction) { var dd = days + minutes/60 + seconds/(60*60); //alert(dd); if (direction == "S" || direction == "W") { dd = '-' + dd; } // Don't do anything for N or E return dd; } Any one?
Thank you.
-22980046 0 how to solve onTouchListener androidi have problem, I am successfully to display image in alert dialog custom, but when I want to add event onTouchListener to the image, i cannot get problem : the method setonTouchListener in Type View is not applicable. Here my source code :
public class ViewDetailItem extends Activity implements OnTouchListener{ bla bla... onloaditem() } here onloaditem() sourcecode :
imgmain.setImageResource(imgID); imgmain.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub /*Intent MyIntentDetailItem=new Intent(getBaseContext(), ViewDetailItemFullscreen.class); Other_class.setItemCode(timgName); startActivity(MyIntentDetailItem);*/ LayoutInflater li = LayoutInflater.from(ViewDetailItem.this); final View inputdialogcustom = li.inflate(R.layout.activity_view_detail_item_fullscreen2, null); final AlertDialog.Builder alert = new AlertDialog.Builder(ViewDetailItem.this); final ImageView imgmainbig=((ImageView) inputdialogcustom.findViewById(R.id.imgmainbig)); imgID=getBaseContext().getResources().getIdentifier(imgName2+"_1", "drawable", getBaseContext().getPackageName()); imgmainbig.setImageResource(imgID); imgmainbig.setOnTouchListener(this); } } The problem refers to imgmainbig.setOnTouchListener(this);
I'm working on a schedule generator where every team plays a match with each other teams. My Database table and the output I need like below, 
What I have tried so far is
<% ResultSet rsteams = clmmodel_database.selectQuery("select count(ct.teamid) as teamcount, teamid,teamname from clm_team ct"); while(rsteams.next()){ int teamcount = rsteams.getInt("teamcount"); int n = teamcount - 1; int numofmatches = n*(n+1)/2; %> <h1>Team Count = <%out.print(teamcount);%></h1> <h1>Number of Matches = <%out.print(numofmatches);%></h1> <table> <%for(int i =0;i<n;i++){%> <tr> //Here I need to display the matches row by row </tr> <%}%> </table> <%}%> Which retrieves the team count and the number of matches to be played. Please help me on this.
-33614301 0Try
Sub HelloWord() Dim wordApp As Object Set wordApp = GetObject(, "Word.Application") MsgBox wordApp.Activedocument.FullName End Sub Once you've got a handle on the the wordApp, you can access all the objects in the model as normal.
The downvote might be because this doesn't sound like a very efficient solution - might it be better to get the Excel data into a Word document or format the Excel document in an acceptable way. You're invoking two pretty chunky apps here to do one thing.
-26066966 0try this
try { $pdo = new PDO('mysql:host=localhost;dbname=yourdbname', 'dbuser' , 'password'); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXECPTION); $pdo->exec('SET NAME "utf8"'); } catch (PDOException $e) { $error= 'error text'; include 'errorpage.php'; exit(); } $success = 'success'; include 'page.php';
-37315341 0 To use a closure in this situation try something like
func getCityDetail (completion:()->()){ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { //background thread, do ws related stuff, the ws should block until finished here dispatch_async(dispatch_get_main_queue()) { completion() //main thread, handle completion } } } then you can use it like
objWebService.getCityDetail { //do something when the ws is complete }
-28999831 0 First of all, Thomas Jungblut's answer is great and I gave me upvote. The only thing I want to add is that the Combiner will always be run at least once per Mapper if defined, unless the mapper output is empty or is a single pair. So having the combiner not being executed in the mapper is possible but highly unlikely.
-30478039 1 entering data and displaying entered data using pythonI am newbie to python , I am trying to write a program in which i can print the entered data .
here is the program which I tried.
#!"C:\python34\python.exe" import sys print("Content-Type: text/html;charset=utf-8") print() firststring = "bill" secondstring = "cows" thridstring = "abcdef" name = input('Enter your name : ') print ("Hi %s, Let us be friends!" % name) The output of this program is only : "Enter your name : " I cannot enter anything from my keyboard. I am running this program using apache in localhost like http://localhost:804/cgi-bin/ex7.py Can anyone plz help me to print the user entered data. Thank you.
-21392529 0 Cascading multi-value parameter issue in SSRS 2008Basically I have built a report using SSRS 2008, the report has cascading parameters, the independent one is a multi-value parameter (work units) populated with values from a database query, the dependent parameter (job positions contained in respective work units) also gets values from a query with a where clause as follows:
WHERE position.unitId IN (@units) @units being the multi-value parameter. The default value for units is the query itself - all of which the user has access to. So upon opening the report, all available units are selected and all respective job positions are retrieved - works fine. But a aser can also have no access to any units, which makes the dependent query fail, cause no units were retrieved hence @units contains no values. I would have thought the query would not fire until @units has a value present.. anyways I have tried to check the contents of @units before querying for job positions in various ways:
*replacing @units parameter with the following expression: =IIF(Parameters!units.Count = 0, "00000000-0000-0000-0000-000000000000", Parameters!units.Value)
*having another parameter containing a comma seperated string of the @units values and checking if the lenght of that is greater than 0 before executing the dependent dataset, etc.
But now, when I open up the report, the drop down list of job position is empty, disabled and remains so until the values of units are changed or the report is run. After that they refresh alright it seems. So my question is, what may be the cause of the control being disabled (units are retrieved, so why does an expression as a parameter value for job positions messes it up?) and how to deal with this the right way, can`t seem to find something really of the same nature online.
Any help will be greatly appreciated.
-2151770 0Maybe you can install PHPMailer as a Vendor and create a Component called "Mail"...
And don't forget to authenticate with your SMTP server! :)
-16254122 0You could create another list in the correct order, by something like:
// Given that 'Person' for the sake of this example is: public class Person { public string FirstName; public string LastName; } // And you have a dictionary sorted by Person.FirstName: var dict = new SortedDictionary<string, Person>(); // ...initialise dict... // Make list reference a List<Person> ordered by the person's LastName var list = (from entry in dict orderby entry.Value.LastName select entry.Value).ToList(); // Use list to populate the listbox This has the advantage of leaving the original collection unmodified (if that's important to you).
The overhead of keeping references to the objects in two different collections is not very high, because it's only one reference per object (plus some fixed overhead for the List<> implementation itself).
But remember that the objects will be kept alive as long as either of the collections are alive (unless you explicitly clear the collections).
Compilable sample:
using System; using System.Collections.Generic; using System.Linq; namespace Demo { public static class Program { private static void Main() { dict = new SortedDictionary<string, Person>(); addPerson("iain", "banks"); addPerson("peter", "hamilton"); addPerson("douglas", "adams"); addPerson("arthur", "clark"); addPerson("isaac", "asimov"); Console.WriteLine("--------------"); foreach (var person in dict) Console.WriteLine(person.Value); var list = (from entry in dict orderby entry.Value.LastName select entry.Value).ToList(); Console.WriteLine("--------------"); foreach (var person in list) Console.WriteLine(person); } private static void addPerson(string firstname, string lastname) { dict.Add(firstname, new Person{FirstName = firstname, LastName = lastname}); } private static SortedDictionary<string, Person> dict; } public class Person { public string FirstName; public string LastName; public override string ToString(){return FirstName + " " + LastName;} } }
-40049973 0 htaccess add index.php to the route with more paths after it I am building a REST using framework. Normally I can call my web services by going to this route
https://www.domainname.com/webservices/index.php/something/else/here
Now I want to be able to hide index.php but still call the same route like this
Currently I am able to get 200-OK from only going up to webservices/
using the following htaccess rewrite:
RewriteRule ^webservices/(.*)/$ webservices/index.php/$1 [R,L]
however, everything after the webservices/ will give me a 404 not found
here is an example.
I guess the biggest question is how do I add the paths after I add the index.php (the level of paths should be dynamic)
P.S. I don't want to display index.php in the URL at all
-36316094 0 Encode/Decode (Encrypt/Decrypt) datetime var in vb6I want to encode a datetime var into a 8-byte alphanumeric string that can be decoded later. I don't need too much security.
201603301639 -> X5AHY6J9 and viceversa.
-20979364 0Try to change:
$stmt->bindParam(':username', $username, ':password', $password); to:
$sth->bindParam(':username', $username, PDO::PARAM_STR); $sth->bindParam(':password', $password, PDO::PARAM_STR); I have tried again to edit your code, you don't need to use global variable, because you instantiate the PDO class directly and use it on the fly.
try { $pdo = new PDO('mysql:host=localhost;dbname=redgrace_staxapp', 'root', ''); $pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); } catch (PDOException $e) { die('MySQL connection fail! ' . $e->getMessage()); } function delete_user($username, $password) { if (username_exists($username)) return TRUE; $query = "DELETE FROM users WHERE username = :username and password = :password"; $stmt = $pdo->prepare($query); $stmt->bindParam(':username', $username, PDO::PARAM_STR); $stmt->bindParam(':password', $password, PDO::PARAM_STR); $stmt->execute(); }
-7772431 0 How about
(!!!) :: [a] -> Int -> Maybe a xs !!! n = Maybe.listToMaybe $ drop n xs
-36466602 0 when button click to activated mouse scroll in android After button click to mouse scroll to be activted,then scroll up to value increment and scroll down to value decrement.Button inside code here not working, my sample code here,please analysis code to help me.
enter code here public class MainActivity extends Activity { Button button; int x,f; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button=(Button)findViewById(R.id.button1); button.setOnTouchListener(new OnTouchListener() { @SuppressLint("NewApi") @Override public boolean onTouch(View arg0, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_SCROLL: if (event.getAxisValue(MotionEvent.AXIS_VSCROLL) < 0.0f) //selectNext(); { x=Integer.parseInt(button.getText().toString()); f=x+5; button.setText(""+f); } else { x=Integer.parseInt(button.getText().toString()); f=x-5; button.setText(""+f); return true; } } return false; } }); }
-24325114 0Was going to suggest you use some sort of conditional validations, as follows (then I read the comments):
#app/models/consumer.rb class Consumer < ActiveRecord::Base ... validates :password_confirmation, presence: {message: "Retype password!"}, if: Proc.new {|a| a.password.present? } end This is the best I can provide for your particular situation - I've not created a password signup / authentication procedure myself (always relied on other classes), so if you wanted to use has_secure_password etc - I'll have to update my answer to help
First one is an example of a nested state which fulfills your requirement for inheriting the scope object. e.g state/sub-state-a, state/sub-state-b The comment above the first snippet you took from the doc reads:
Shows prepended url, inserted template, paired controller, and inherited $scope object.
The second example is a nested view where you can define multiple views per state and use each depending on your use-case. From the docs:
-17428887 0 Set multiple alarms using sqlite database but only one alarm remainingThen each view in views can set up its own templates (template, templateUrl, templateProvider), controllers (controller, controllerProvider).
I set multiple alarms using SQLite, but when I set the clock, there is just one alarm that is the last one I set. How can I fix this?
public class alert extends Activity{ DatePicker pickerDate; TimePicker pickerTime; Button buttonSetAlarm; Button insertButton;`enter code here` TextView info; Context mContext; AlarmManager mAlarmManager; dalAlarm dbAlarm ; SQLiteOpenHelper dbHelper; SQLiteDatabase database; final static int RQS_1 = 0; dalAlarm dalAl = new dalAlarm(this); public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.alertscreen); info = (TextView)findViewById(R.id.info); pickerDate = (DatePicker)findViewById(R.id.pickerdate); pickerTime = (TimePicker)findViewById(R.id.pickertime); Calendar now = Calendar.getInstance(); pickerDate.init( now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH), null); pickerTime.setCurrentHour(now.get(Calendar.HOUR_OF_DAY)); pickerTime.setCurrentMinute(now.get(Calendar.MINUTE)); buttonSetAlarm = (Button)findViewById(R.id.setalarm); buttonSetAlarm.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { Calendar current = Calendar.getInstance(); Calendar cal = Calendar.getInstance(); cal.set(pickerDate.getYear(), pickerDate.getMonth(), pickerDate.getDayOfMonth(), pickerTime.getCurrentHour(), pickerTime.getCurrentMinute(), 00); //dbAlarm.addNewAlarm(new dalHelper_alarm(pickerTime.getCurrentHour(),pickerTime.getCurrentMinute(),cal.getTime().toString())); if(cal.compareTo(current) <= 0){ Toast.makeText(getApplicationContext(), "Invalid Date/Time", Toast.LENGTH_LONG).show(); }else{ // dbAlarm.addNewAlarm(new dalHelper_alarm(pickerTime.getCurrentHour(),pickerTime.getCurrentMinute(),cal.getTime().toString())); setAlarm(cal); database(); } } }); } public void setAlarm(Calendar targetCal) { info.setText("\n\n***\n" + "Alarm is set@ " + targetCal.getTime() + "\n" + "***\n"); dalAlarm db = new dalAlarm(alert.this); dalHelper_alarm test = new dalHelper_alarm(pickerTime.getCurrentHour(),pickerTime.getCurrentMinute(),targetCal.getTime().toString()); db.addNewAlarm(test); } public void newAlarm(Calendar newCal){ Intent intent = new Intent(getBaseContext(), popUp.class); PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT); AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, newCal.getTimeInMillis(), pendingIntent); } public void database(){ ArrayList<dalHelper_alarm> alarm = dalAl.getAllAlarm(); Calendar newCal = Calendar.getInstance(); newCal.set(pickerDate.getYear(), pickerDate.getMonth(), pickerDate.getDayOfMonth(), alarm.get(0).getHour(), alarm.get(0).getMin(), 00); info.setText("\n\n*** \n" + "Alarm is set@ " + newCal.getTime() + "\n" + "***\n"); newAlarm(newCal); } }
-14067583 0 That's not as simple as you might think.
The canvas doesn't actually "store" the text, it's just a grid of pixels. It's not aware of elements drawn on the canvas or anything. As such, the canvas can't "hyperlink" a text element.
One of the options would be to add a click event listener to the canvas, get the x/y of the event, and if you hit the text, redirect to the url. To do this you would need to keep track of the text's position (rotation?) and size, manually.
Another, possibly easier option, would be to simply add a element on top of the image that contains the text. Then, you can simply add a hyperlink.
Working example of a link overlaying the canvas
-3317881 0 How to blur 3d object? (Papervision 3d)How to blur 3d object? (Papervision 3d) And save created new object as new 3d model? (can help in sky/clouds generation)
Like in 2d picture I've turn rectangel intu some blury structure

We are writing a system that has a booking feature, and we are planning to have it send *.ics files via email to attendees so they can easily add appointments to their calendars. The types of events are things like training courses (e.g. 3pm in the boardroom).
We've got this working to the point that the system sends the *.ics, and using Gmail and Outlook, the user can accept the appointment which, is then added to their calendar.
Sometimes an event changes (e.g. a course is cancelled or delayed until the following day). Our software can send out a new *.ics file, and Gmail/Outlook correctly recognize that this is an update to the original appointment and gives the option to accept/decline again.
The trouble is, we don't have a mechanism to receive via email the accept/decline responses that standard email clients automatically send when the user accepts/declines an appointment. Therefore, clicking the "decline" option could give them the false sense that they have cancelled the appointment when in fact our system has no idea what they've done within their calendar.
We always want the bookings to be instigated by the user directly on the website, and the *.ics via email is merely a convenience to help them remember to attend. Similar to a flight booking, if the passenger really intends to cancel, something a little more definitive is required than clicking "decline" in Outlook. With a few flight bookings I've made, the carrier sent me a *.vcs file which contains "METHOD:PUBLISH" instead of "METHOD:REQUEST" which sounds closer to what we want, although in testing, this *.vcs file was not recognized by GMail as an appointment.
So the question is, can we email appointments, with subsequent updates, that will be automatically be recognized by Outlook, GMail & Lotus Notes, but prevent the user from thinking they can cancel/decline the entire booking from within their own calendar tool? If so, how?
UPDATE 1
I think I found the issue with the METHOD:PUBLISH airline booking example I was experimenting with - it was for a past date. Using a future date, We can now use METHOD:PUBLISH to allow people to add events to their calendar without requiring accept/decline. Problem now is that if the event is cancelled or changed, we cannot get a new *.ics to be recognized as overriding the original. We are allocating a unique UID and incrementing the SEQUENCE field to the event, but I don't know whether the spec allows a "PUBLISH"-ed event to elegantly handle updates (date, time, location, description etc.)
UPDATE 2
Okay, well I've just been experimenting with the sample *.ics files from the spec. Using the examples from 4.1.1 "A Minimal Published Event" and 4.1.2 "Changing a Published Event" I am sending what I believe is a spec-compliant published event, and subsequent update. Both Outlook 2010 and GMail see the update as a NEW EVENT. So at this point I'm going to assume Outlook and GMail have only partial support for *.ics files, give up on elegant updates and simply instruct the user to delete their old calendar appointment if I send them a new one.
-2420358 0 Why does using a structure in C program cause Link errorI am writing a C program for a 8051 architecture chip and the SDCC compiler.
I have a structure called FilterStructure;
my code looks like this...
#define NAME_SIZE 8 typedef struct { char Name[NAME_SIZE]; } FilterStructure; void ReadFilterName(U8 WheelID, U8 Filter, FilterStructure* NameStructure); int main (void) { FilterStructure testStruct; ReadFilterName('A', 3, &testFilter); ... ... return 0; } void ReadFilterName(U8 WheelID, U8 Filter, FilterStructure* NameStructure) { int StartOfName = 0; int i = 0; ///... do some stuff... for(i = 0; i < 8; i++) { NameStructure->Name[i] = FLASH_ByteRead(StartOfName + i); } return; } For some reason I get a link error "?ASlink-Error-Could not get 29 consecutive bytes in internal RAM for area DSEG"
If I comment out the line that says FilterStructure testStruct; the error goes away.
What does this error mean? Do I need to discard the structure when I am done with it?
-28470877 0This should work for you:
(Here i just simply go trough each innerArray with foreach. Then i get the id from the innerArray and check if it is already in the tmp array and if not i add it to the tmp array. At the end i just simply use array_values(), so that the indexes are clean and starts with 0. The array_reverse() is to get the entire arrray in the right order)
<?php $a = array( array('id'=>1, 'value'=>2), array('id'=>2, 'value'=>3), array('id'=>3, 'value'=>4), array('id'=>1, 'value'=>5), array('id'=>5, 'value'=>10), array('id'=>2, 'value'=>6), ); $tmp = array(); foreach(array_reverse($a) as $v) { $id = $v['id']; isset($tmp[$id]) or $tmp[$id] = $v; } $a = array_reverse(array_values($tmp)); print_r($a); ?> Output:
Array ( [0] => Array ( [id] => 3 [value] => 4 ) [1] => Array ( [id] => 1 [value] => 5 ) [2] => Array ( [id] => 5 [value] => 10 ) [3] => Array ( [id] => 2 [value] => 6 ) )
-10052374 0 Take the substring from the place where DS occurs using the function substr, and get the data out of it. To get the data, just parse the substring keeping a count of opening brackets. When the closing brackets start, keep a count of them. When this count and previous count become equal, you have got your data.
-33929587 0If you had the some problem as I, it's very simple. When you to go save the preferences, save like:
SharedPreferences sp = getSharedPrefenreces("Preference",MODE_PRIVATE); And no:
SharedPreferences sp = getSharedPrefenreces("Preference's name",Context.MODE_PRIVATE); I know how so much is important the SharedPrefenrences in some cases.
-35522875 0So based on what I understand from your question, it looks like the padding around the input is being shrunken.
Try this:
input:active { padding: 5px; } Mess around with the padding and see if it effects the size when active.
-33349822 0 Problems implementing an editable TableViewSo I've been trying to implement a TableView where you can edit a column just by clicking on it, and then save the edit by pressing the enter key. I've taken at lot of the code from the answer in this thread. This is the result:
import com.sun.javafx.collections.ObservableListWrapper; import javafx.application.Application; import javafx.application.Platform; import javafx.beans.property.SimpleStringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.Scene; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import javafx.stage.Stage; public class TestEditableTable extends Application { public void start(Stage stage) { TableView<ObservableList<String>> tableView = new TableView<ObservableList<String>>(); tableView.setEditable(true); // Some dummy data. ObservableList<ObservableList<String>> dummyData = FXCollections.observableArrayList(); ObservableList<String> firstRow = FXCollections.observableArrayList("Jack", "Smith"); dummyData.add(firstRow); ObservableList<String> secondRow = FXCollections.observableArrayList("Peter", "Smith"); dummyData.add(secondRow); TableColumn<ObservableList<String>, String> firstCol = new TableColumn<ObservableList<String>, String>( "First name"); firstCol.setCellValueFactory( (TableColumn.CellDataFeatures<ObservableList<String>, String> param) -> new SimpleStringProperty( param.getValue().get(0))); TableColumn<ObservableList<String>, String> secondCol = new TableColumn<ObservableList<String>, String>( "Last name"); secondCol.setCellValueFactory( (TableColumn.CellDataFeatures<ObservableList<String>, String> param) -> new SimpleStringProperty( param.getValue().get(1))); secondCol.setCellFactory(cell -> new EditableCell()); tableView.getColumns().addAll(firstCol, secondCol); tableView.getItems().addAll(dummyData); Scene scene = new Scene(tableView); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(); } class EditableCell extends TableCell<ObservableList<String>, String> { private TextField textfield = new TextField(); // When the user presses the enter button the edit is saved. public EditableCell() { setOnKeyPressed(e -> { if (e.getCode().equals(KeyCode.ENTER)) { commitEdit(textfield.getText()); } }); } @Override public void updateItem(String item, boolean empty) { super.updateItem(item, empty); if (isEmpty()) { setText(null); setGraphic(null); } else { if (isEditing()) { textfield.setText(item); setGraphic(textfield); setText(null); } else { setText(item); setGraphic(null); } } } @Override public void startEdit() { super.startEdit(); textfield.setText(getItem()); setGraphic(textfield); setText(null); } @Override public void cancelEdit() { super.cancelEdit(); setGraphic(null); setText(getItem()); } @Override public void commitEdit(String value) { super.commitEdit(value); // This works. But gives me a "Discouraged access: The type 'ObservableListWrapper<String>' is not API (restriction on required library 'C:\Program Files\Java\jre1.8.0_60\lib\ext\jfxrt.jar')". ObservableListWrapper<String> ob = ((ObservableListWrapper<String>) this.getTableRow().getItem()); ob.set(1, value); // I had to put this in a Platform.runLater(), otherwise the textfield remained open. Platform.runLater(() -> { setText(value); setGraphic(null); }); } } } And this program works OK. The cell is edited when you press the enter button. But there are two main issues with this:
Once I've pressed enter and a cell has been edited. I can't edit it again by clicking on it. I need to press another row to be able to edit it again. Setting to focus on the parent of the row didn't do the trick.
The code inside commitEdit() works. But it is ugly and using a ObservableListWrapper gives me the warning "Discouraged access: The type 'ObservableListWrapper' is not API (restriction on required library 'C:\Program Files\Java\jre1.8.0_60\lib\ext\jfxrt.jar')". Also the cell index is hard coded, which wont work if I use this in many different columns.
None of the issues mentioned above is acceptable.
The final implementation must support restriction of the input in the textfield. As far as I understand it this means that I need to have access to the TextField object displayed in the cell, as in my current implementation.
If you run gem list -d rails you'll get an output similar to this.
*** LOCAL GEMS *** rails (3.2.3) Author: David Heinemeier Hansson Homepage: http://www.rubyonrails.org Installed at: /Users/bjedrocha/.rvm/gems/ruby-1.9.3-p194@jwb Full-stack web application framework. Note the installed at directive. The part after the @ indicates the gemset. So if you've installed Rails without first creating and switching to a named gemset, chances are that it is installed under the @global gemset (a default for RVM). If this is your case, I would switch into the global gemset and uninstall Rails. Once its uninstalled, you can switch back to your named gemset and it will use the Rails version installed in this gemset
rvm use 1.9.3@global gem uninstall rails rvm use 1.9.3@mygemset Hope this helps
-28840717 0I only see two options here. Unfortunately, one of them isnt feasible and the other one doesnt exactly fit your criterions. Let's see:
EDIT: Why do you want to avoid writing a file? If you draw the big picture, we might be able to figure a way arround your problem.
-41059077 0The correct path to use is the platform/google_appengine/ directory, within the google-cloud-sdk installation directory,
I have found a JSFiddle that has some great code to animate a ball - it rotates it through 360 deg. What I would like to do is have the ball constantly rotate through 360 deg - it needs to turn continuously. I have tried to achieve this but have had no success. I would be grateful for any help in adjusting this javascript.
$(document).ready(function(){ var s=$('.ball').position(); var g=s.left; var r=$('.ball').css('margin-left'); $('.ball').css({'margin-left':'0px'}); $('.ball').css({'margin-left':''+r+''}); if(r=="0px") { $('.ball').css({'position':'absolute'}); $('.ball').animate({'left':''+g+'px'}); } $('.ball').css({'transform': 'rotate(360deg)','-webkit-transform': 'rotate(360deg)','-moz-transform': 'rotate(360deg)'}); }); This is the JSFiddle I found http://jsfiddle.net/996PJ/5/
-37341768 0 Java + Hibernate: Using a Formula on an embedded classCan I use the @Formula annotation on an embedded class which maps the resultset of the query in the formula?
Entity
@Entity(name = "TABLE") public class SpecialEntity { ... @Embedded @Formula("SELECT PATH, SIZE FROM TABLE WHERE ID = ID') private List<EmbedProperties> properties; } Embeddable
@Embeddable public class EmbedProperties { @Column("PATH") private String id; @Column("SIZE) private Long size; } If not, what are the alternatives?
-7053631 0You can try to use a different library to load this assembly, like Mono.Cecil.
new/new[]/malloc and not freeing itp = new int; p = new int[1];new int[100]; or cout<<(*new string("hello"))<<endl;I am designing a new chrome extension and when I package it then I get 2 file: a .crx file and a .pem file.
I want to distribuite my extension on my server ( shared ) and on Chrome webstore.
Could you tell me what is a pem file and how to use it ?
I can't find documentation about it.
-26981858 0using row number windowed function along with a CTE will do this pretty well. For example:
;With preResult AS ( SELECT TOP(100) [ID] = c.[ID], [Name] = c.[Name], [Keyword] = [colKeyword].[StringVal], [DateAdded] = [colDateAdded].[DateVal], ROW_NUMBER()OVER(PARTITION BY c.ID ORDER BY [colDateAdded].[DateVal]) rn FROM @cards AS c LEFT JOIN @cardindexes AS [colKeyword] ON [colKeyword].[CardID] = c.ID AND [colKeyword].[IndexType] = 1 LEFT JOIN @cardindexes AS [colDateAdded] ON [colDateAdded].[CardID] = c.ID AND [colDateAdded].[IndexType] = 2 WHERE [colKeyword].[StringVal] LIKE 'p%' AND c.[CardTypeID] = 1 ORDER BY [DateAdded] ) SELECT * from preResult WHERE rn = 1
-15879798 0 When you allocate memory with malloc (or similar functions) it returns a pointer. You can't assign this pointer to an array. In other words, you can't make an array point to something else once created.
What you should do is declare the array as a pointer instead.
-32085756 0Try MZFormSheetPresentationController by m1entus.
He provides a number of examples on GitHub and CocoaPods and they're ready to use.
-4803259 0 Embedded Jetty handles each message twiceI'm trying to use Jetty in the simplest way possible. I have started by running the walkthrough from the Jetty@Eclipse documentation, which basically looks like that:
public class Main { public class HelloHandler extends AbstractHandler { public void handle(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); response.getWriter().println("<h1>Hello World</h1>"); } } private void run() throws Exception { Server server = new Server(8080); server.setHandler(new HelloHandler()); server.start(); server.join(); } public static void main(String[] args) throws Exception { Main m = new Main(); m.run(); } } The problem is that the handler gets called twice on every request. I'm using Chrome with http://localhost:8080 to simulate, if that makes any difference. Jetty is embedded as two jars:
What am I doing wrong/missing here?
-17418208 0 update UI in Task using TaskScheduler.FromCurrentSynchronizationContextI want to add some text to list box using Task and I simply use a button and place in click event this code:
TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext(); Task.Factory.StartNew(() => { for (int i = 0; i < 10; i++) { listBox1.Items.Add("Number cities in problem = " + i.ToString()); System.Threading.Thread.Sleep(1000); } }, CancellationToken.None, TaskCreationOptions.None, uiScheduler); but it does not work and UI locked until the end of the for loop.
Where is the problem ?
thanks :)
-4723203 0yourString.replaceAll("&b=52","");
-9411266 0You don't need if else block, just math :
$Start = ($CurrentPage-1)*5+1;
-22752345 0 I'm assuming you left some out, is this the complete code?
public class House { private final House house; public static void main(String[] args) { house = new House("Robinsons"); house.setColor("Red"); } public House(String houseName) { // do something } public void setColor(String color) { // do something } } If so, there are a number of problems with this.
main method, either make house a static variable, which I wouldn't recommend. Or declare an instance inside the main method before using it.I built a similar system several years ago using MongoDB on Amazon AWS. This year, tired of doing DevOps on AWS (nod to @AndreiVolgin), I've moved it to Google BigQuery.
Datastore for my use case was overkill and frankly, limiting. I would have wanted to turn off indexes for most attributes anyways to save on storage cost. Limiting because it's harder to hook up datastore-based data with a visualization tool such as Tableau.
Regarding
I know there's a solution called BigQuery by Google, which I believe does what I want and allows me to serve the data I want to customers with high flexibility and efficiency, but as I understood it works only on datastore "backups", I need to serve data in real time.
When my system receives a datum, page visitor data in your example, it streams it directly to BQ. So no, it doesn't only work on backups. Whether you can use it to report "real time" depends on what real time means to you. My system computes aggregate statistics once every couple hours for presentation to users.
-38098717 0 Running praat on remote ubuntu serverI am working for a web application using praat features. I have written a script for that and it is working fine in ubuntu. But now i want to run these .praat scripts in a remote ubuntu server and I have already installed praat but when I run praat it gives me the following error:
(praat:1364): GLib-GObject-WARNING **: invalid (NULL) pointer instance
(praat:1364): GLib-GObject-CRITICAL **: g_signal_connect_data: assertion 'G_TYPE_CHECK_INSTANCE (instance)' failed
(praat:1364): Gtk-WARNING **: Screen for GtkWindow not set; you must always set a screen for a GtkWindow before using the window
(praat:1364): Gdk-CRITICAL **: IA__gdk_screen_get_default_colormap: assertion 'GDK_IS_SCREEN (screen)' failed
(praat:1364): Gdk-CRITICAL **: IA__gdk_colormap_get_visual: assertion 'GDK_IS_COLORMAP (colormap)' failed
(praat:1364): Gdk-CRITICAL **: IA__gdk_screen_get_default_colormap: assertion 'GDK_IS_SCREEN (screen)' failed
(praat:1364): Gdk-CRITICAL **: IA__gdk_screen_get_root_window: assertion 'GDK_IS_SCREEN (screen)' failed
(praat:1364): Gdk-CRITICAL **: IA__gdk_screen_get_root_window: assertion 'GDK_IS_SCREEN (screen)' failed
(praat:1364): Gdk-CRITICAL **: IA__gdk_window_new: assertion 'GDK_IS_WINDOW (parent)' failed Segmentation fault (core dumped)
Please tell me way a that I can run a praat script in remote ubuntu server.
-35568033 0 How to end if statement in phpThe question is pretty much self-explanatory, I am having trouble how to end if statement in php.
For example,
<?php if (argument) { // end if statement } else if (different argument) { // end if statement } else if (another different argument) { // end if statement } else { // do something } ?>
-39902288 0 Opening a form, closing it, then opening it again in the same location I have a pop up selector for my main form that comes up when I click a button. After I make my selection the box is closed and I continue my work in the main form. However if I go to click that button again, the pop up will appear slightly under where it had opened up previously. Is there a way to fix this so that every time that form is opened it opens in the same spot?
-6494079 0 How can i create django models , views , forms with different namesCurrently i have my models, views, forms in default file. But i want to have directory structure like
articles ---------models ---------views ---------forms Books ---------models ---------views ---------forms Icecreams ---------models ---------views ---------forms so that i keep separately but i don't want different app
-22000259 0 iOS xcdatamodel newly added attribute has quotation markI just migrated my new data model and added a new attribute called "author_mail".However I discover at when I output my records:
attachments = "<relationship fault: 0xd2459c0 'attachments'>"; author = nil; "author_mail" = nil; <-- ABNORMAL category1 = World; I set the author_mail to string type but I don't think the author_mail should wrap with quotation mark. I don't know if it related to my migration but it does not output any error. Any clue where should I start look on? I found nothing on the internet.
Result I want:
attachments = "<relationship fault: 0xd2459c0 'attachments'>"; author = nil; author_mail = nil; category1 = World; Thanks everyone.
-27177550 0 Show combobox drop down while editing textWhen I first load my form the combobox functions as desired:

Then when I select one of the drop down menu items (via cursor or arrow keys & enter):

Now if I try to edit the text in the combo box again (via cursor or arrow keys), the drop down menu no longer appears:

Currently my load form method:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 'connect to RFDB Dim connectionString = My.Settings.RFDBConnectionString Dim connection As New SqlConnection(connectionString) connection.Open() 'Get Versions Table from RFDB Dim versions As DataTable Dim query = "select LocationID, VersionsNum, Description, PlanetExport from Versions inner join VersionsBuild on VersionsBuildID=IDVersionsBuild" versions = QueryRFDB(query, connectionString) 'Fill ComboBox with possible site versions Dim source As New AutoCompleteStringCollection() Dim i As Integer For i = 0 To versions.Rows.Count - 1 Dim siteVersion As String siteVersion = versions.Rows(i)(0) & " V" & versions.Rows(i)(1) & " " & versions.Rows(i)(2) source.Add(siteVersion) Next i Me.ComboBox1.AutoCompleteCustomSource = source Me.ComboBox1.AutoCompleteMode = AutoCompleteMode.Suggest Me.ComboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource 'Fill ListBox with currently flagged site versions For i = 0 To versions.Rows.Count - 1 Dim siteVersion As String siteVersion = versions.Rows(i)(0) & " V" & versions.Rows(i)(1) & " " & versions.Rows(i)(2) If versions.Rows(i)(3) = True Then Me.ListBox1.Items.Add(siteVersion) Next i End Sub 'Returns a data table as the result of the sql query on RFDB Private Function QueryRFDB(ByVal query As String, ByVal connectionString As String) Dim adapter As New SqlDataAdapter(query, connectionString) Dim table As New DataTable adapter.Fill(table) Return table End Function I am thinking it is maybe a settings issue with my combobox? Any help is appreciated.
-23897168 0 Adjusting z-index of angularjs typeahead directiveI am using Angularjs typeahead directive in combination with jquery layout plugin. Here is the link to the app I am working on. When I type an address into the input box, the list of autocomplete results get hidden behind the resizer. I have tried changing the z-index property of both the autocomplete list as well as the pane resizer, but nothing seems to be working. What is the best way to solve this?
.ui-layout-resizer-open { z-index: 1; } .dropdown-menu { z-index: 2; }
-22113160 0 It possible you're not making those calls early enough, and the classes that use them have already been loaded and initialized themselves.
A good test/quick fix would be to make a separate Main class that only makes those calls, then calls the class you are currently using to start your app.
You might even have to call those in a static initializer (not in main), because once you execute main, all the classes it references will be loaded first.
You could also use reflection to load and execute your class from Main, that's kind of messy and probably not required.
-22503882 0 What does the read call return on earth if there are already both FIN and RST in the TCP buffer?Assuming that the client and server send packets according to the order of sequence as shown in the figure, the client does not know FIN has arrived.
It sends “hello again” to the server, the server responds to the client with an RST and the RST has arrived. Then if the client is blocking on a read, why it return 0 due to the FIN instead of -1 because the RST? In the 《Effective TCP/IP programming》, it tells us that the core will return ECONNRESET error.
My operating system is Ubuntu 12.10. Is it related with the operating system? Please tell me some TCP’s details on this implementation. Thanks in advance.

I have a batch file which is asking for some user input text in the middle of that process. I need to run this batch file through c# code. I cannot change the bat file. So the option having command line arguments also is not working for me. Is there any way that i can provide the input when it prompts?
-12585443 0Use mysql_fetch_row()to get the $amount_data.Mysql_query() returns only the resouce id
$amount_data = mysql_query ("SELECT * FROM subscriber WHERE payment_amount = '$payment_amount' AND id = '$id' "); $row = mysql_fetch_row($amount_data); echo $row[0]; Check the link http://php.net/manual/en/function.mysql-fetch-row.php
-13242813 0 can't get stdout to a variableit seems silly... I don't know what I am doing wrong....
I need to change the .txt files encoding to utf-8. here the script:
#!/bin/bash for NOME_ARQ in *.txt do ##1 - verify file encoding and store in CODIFICACAO CODIFICACAO=$(file --mime-encoding "$NOME_ARQ" | cut -d" " -f2) ##2 - convert to utf-8 iconv -f "$CODIFICACAO" -t utf-8 "$NOME_ARQ" -o temp01.txt done Have tried several ways for the ##1, but always get the following error:
sc-sini2csv: line 5: sintax error near `token' unexpected `CODIFICACAO=$(file --mime-encoding "$NOME_ARQ" | cut -d" " -f2)' sc-sini2csv: line 5: `CODIFICACAO=$(file --mime-encoding "$NOME_ARQ" | cut -d" " -f2)' We see from the error, that the problem occur when assigning the variable $CODIFICACAO
As far as I've looked around there are 2 ways of assigning the STDOUT to a variable:
1- using backtick:
CODIFICACAO=`file --mime-encoding "$NOME_ARQ" | cut -d" " -f2` or
2- using $():
CODIFICACAO=$(file --mime-encoding "$NOME_ARQ" | cut -d" " -f2) Both of them will give the same error.
As I wrote, it seems silly, but I'm stucked on this error..... any hel will be much appreciated !!!
PS: using $() or backticks directly from terminal (outside a bash script) will work.... but i need it into a shell script.
In time: I'm using ubuntu with bash shell
Thanks in advance !!! Silvio
-2791931 1 Speed vs security vs compatibility over methods to do string concatenation in PythonSimilar questions have been brought (good speed comparison there) on this same subject. Hopefully this question is different and updated to Python 2.6 and 3.0.
So far I believe the faster and most compatible method (among different Python versions) is the plain simple + sign:
text = "whatever" + " you " + SAY But I keep hearing and reading it's not secure and / or advisable.
I'm not even sure how many methods are there to manipulate strings! I could count only about 4: There's interpolation and all its sub-options such as % and format and then there's the simple ones, join and +.
Finally, the new approach to string formatting, which is with format, is certainly not good for backwards compatibility at same time making % not good for forward compatibility. But should it be used for every string manipulation, including every concatenation, whenever we restrict ourselves to 3.x only?
Well, maybe this is more of a wiki than a question, but I do wish to have an answer on which is the proper usage of each string manipulation method. And which one could be generally used with each focus in mind (best all around for compatibility, for speed and for security).
Thanks.
edit: I'm not sure I should accept an answer if I don't feel it really answers the question... But my point is that all them 3 together do a proper job.
Daniel's most voted answer is actually the one I'd prefer for accepting, if not for the "note". I highly disagree with "concatenation is strictly using the + operator to concatenate strings" because, for one, join does string concatenation as well, and we can build any arbitrary library for that.
All current 3 answers are valuable and I'd rather having some answer mixing them all. While nobody volunteer to do that, I guess by choosing the one less voted (but fairly broader than THC4k's, which is more like a large and very welcomed comment) I can draw attention to the others as well.
-13564819 0Placemarker tokens are defined in the preceding paragraph (6.10.3.2):
If, in the replacement list of a function-like macro, a parameter is immediately preceded or followed by a
##preprocessing token, the parameter is replaced by the corresponding argument’s preprocessing token sequence; however, if an argument consists of no preprocessing tokens, the parameter is replaced by a placemarker preprocessing token instead.145)
And the footnote:
145) Placemarker preprocessing tokens do not appear in the syntax because they are temporary entities that exist only within translation phase 4.
And the last line you quoted doesn't say "undefined behaviour", it says "the behavior is undefined". I'm not sure what kind of answer you're looking for here. It says so because the authors of the standard decided so.
-39831789 0not sure url is str or other types
you can do like this:
"https" in str(df.url[len(df)-1]) or
str(df.ix[len(df)-1].url).__contains__("https")
-14607934 0 Use .ToString():
Year = int.Parse(bindingContext.ValueProvider.GetValue("Year").AttemptedValue ?? now.Year.ToString()); Both variables need to be of the same type.
-30398320 0If you see (lldb) in the console you've most likely hit a breakpoint. If you haven't added a breakpoint there yourself there might be an exception breakpoint in your project, catching all uncaught exceptions.
Try clicking on the "play" looking button above the console, that should continue the execution (or at least help you with what the crash was).
-28739363 0I'm not sure where you quoted that from, it doesn't appear in the documentation at all. To actually quote from the documentation:
The
HashSet<T>class is based on the model of mathematical sets and provides high-performance set operations similar to accessing the keys of theDictionary<TKey, TValue>orHashtablecollections. In simple terms, theHashSet<T>class can be thought of as aDictionary<TKey, TValue>collection without values.
So it is a collection, containing actual values. The sentence you quoted there is false.
That being said, you could create an ISet<T> implementation that works that way, e.g. representing numbers in a set as ranges. But trying to do that with a vanilla HashSet<T> will quickly break down.
The following code is for an AngularJS code to read data from a .txt file and echo out on the webpage. It works just fine for the entered records in the .txt file, but upon increasing the number of records above 4, the code fails to work. What could be wrong?
Index.html
<html> <head> <title>Angular JS Includes</title> <style> table, th , td { border: 1px solid grey; border-collapse: collapse; padding: 5px; } table tr:nth-child(odd) { background-color: #f2f2f2; } table tr:nth-child(even) { background-color: #ffffff; } </style> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app="" ng-controller="studentController"> <table> <tr> <th>Name</th> <th>Roll No</th> <th>Percentage</th> </tr> <tr ng-repeat="student in students"> <td>{{ student.Name }}</td> <td>{{ student.RollNo }}</td> <td>{{ student.Percentage }}</td> </tr> </table> </div> <script> function studentController($scope,$http) { var url="data.txt"; $http.get(url).success( function(response) { $scope.students = response; }); } </script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> </body> Data.txt
[ { "Name" : "Collin James", "RollNo" : 101, "Percentage" : "81.5%" }, { "Name" : "Michael Ross", "RollNo" : 201, "Percentage" : "70%" }, { "Name" : "Robert Flare", "RollNo" : 191, "Percentage" : "75%" }, { "Name" : "Julian Joe", "RollNo" : 111, "Percentage" : "77%" } ]
-37002717 0 From your android device you should not put localhost/###.#.#.#:##, but instead just your server address and port like ###.#.#.#:##, for example 192.168.1.12:80. Because you are not running any server on your android app.
Instead of messing about with errorformat, just set cscopequickfix and use the normal :cscope commands. eg. (from vim help)
:set cscopequickfix=s-,c-,d-,i-,t-,e- Edit
You could also use a filter like the following to reorder the fields
sed -e 's/^\([^ ]\+\) \([^ ]\+\) \([^ ]\+\) \(.*\)$/\1 \3 \4 inside \2/' set it to filter your message, then use the efm
errorformat=%f\ %l\ %m
-5475979 0 Dynamically generating a function name based on a variable What I want is to create a function whose name will come from the content of one of my variables.
Example :
var myFunctionName = "tryAgain";` [tryAgain] | | | function myFunctionName() { alert('Try Again !'); };
-15447316 0 Validation doesn't work with knockout bindings....
You have to duplicate the validation in client side. The faster way is using knockout validation plugin, but it is slow when you have a lot of data..
https://github.com/ericmbarnard/Knockout-Validation
Or you can just use jquery validation.
-37118922 0 Translating cURL into Swift NSURLSessionI am working with the Twilio API to perform a lookup with a phone number. I have an SID & API token, and the example call gives me this cURL command:
curl -XGET "https://lookups.twilio.com/v1/PhoneNumbers/4192240117?Type=carrier&Type=caller-name" -u "{AccountSid}:{AuthToken}" However, I'm not sure how to translate that into a valid URL when creating my NSURLSession.
Does the AccountSID & AuthToken token go into the header of the request, or are they parameters to the request?
I have tried adding them as both, using the awesome Paw app, to see if I could get it working, but I have not been able to.
I have tried searching Google for what the -u command is in cURL, so I added the username & password fields in the request header with the appropriate key, but no luck.
Can anyone explain where I need to put AccountSID & AuthToken in the URL to successfully make the request?
Go to your module or extension folder then /Block/Adminhtml/Blog/Grid.php. Open this Grid.php file and search the function protected function _prepareCollection() and add the following code under this function before return parent::_prepareColumns();.
$this->addExportType('*/*/exportCsv', Mage::helper('blog')->__('CSV')); $this->addExportType('*/*/exportXml', Mage::helper('blog')->__('XML')); After add this code it may be looks like that: Next, in this extension or module folder go to /controllers/Adminhtml/ and open the controller file and add the following code under the class (add the code bottom of the page before last '}')
public function exportCsvAction() { $fileName = 'blog.csv'; $content = $this->getLayout()->createBlock('[your-module-name]/adminhtml_[your-module-name]_grid') ->getCsv(); $this->_sendUploadResponse($fileName, $content); } public function exportXmlAction() { $fileName = 'blog.xml'; $content = $this->getLayout()->createBlock('[your-module-name]/adminhtml_[your-module-name]_grid') ->getXml(); $this->_sendUploadResponse($fileName, $content); } protected function _sendUploadResponse($fileName, $content, $contentType='application/octet-stream') { $response = $this->getResponse(); $response->setHeader('HTTP/1.1 200 OK',''); $response->setHeader('Pragma', 'public', true); $response->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true); $response->setHeader('Content-Disposition', 'attachment; filename='.$fileName); $response->setHeader('Last-Modified', date('r')); $response->setHeader('Accept-Ranges', 'bytes'); $response->setHeader('Content-Length', strlen($content)); $response->setHeader('Content-type', $contentType); $response->setBody($content); $response->sendResponse(); die; } Now replace the [your-module-name] text with your extension or module name and save then check.
* Please like if this post help you!*
-3043018 0Since CMIS was approved as a standard last month, the new best way to achieve this is probably via CMIS, as explained here.
-27330748 0WebClient.resCode is a non-nullable Int so it is 0 by default hence the problem would be either the request not being sent or the response not being read.
As you are obviously writing the request, the problem should the latter. Try calling WebClient.readRes() before resStr.
This readRes()
Read the response status line and response headers. This method may be called after the request has been written via writeReq and reqOut. Once this method completes the response status and headers are available. If there is a response body, it is available for reading via resIn. Throw IOErr if there is a network or protocol error. Return this.
Try this:
echo(spreadsheet_inputer.readRes.resStr) I suspect the following line will also cause you problems:
spreadsheet_inputer.reqOut.writeXml(xml_test.writeToStr).close becasue writeXml() escapes the string to be XML safe, whereas you'll want to just print the string. Try this:
spreadsheet_inputer.reqOut.writeChars(xml_test.writeToStr).close
-32152775 0 import scala.collection._ import scala.collection.JavaConversions._ val myMap: mutable.Map[K,V] = ??? val unmodifiable: mutable.Map[K,V] = java.util.Collections.unmodifiableMap[K,V](myMap) val newMap = unmodifiable.asInstanceOf[scala.collection.Map[K,V]] You can cast newMap to a mutable.Map, but modifications will throw UnsupportedOperationException.
In my case, the maps may be small enough that toMap may be faster and use less memory.
I have a GUI with a Menu named file
how do I Add a file open and close function to the program. If the program is in the encrypting mode, it should load/save the cleartext text area. If the program is in decrypting mode, it should load/save the ciphertext area.
-34391650 0you should do
public List<DataLstViewEmail> GetRows() { instead of
public IEnumerable<object> GetRows() {
-14474895 0 How to encode method parameters using HadoopRpcRequestProto request field in Hadoop The Hadoop RPC engine uses Protocol Buffer to encode/decodes the bytes from the wire.
I am trying to invoke a method on a Hadoop Server using the HadoopRpcRequestProto
HadoopRpcRequestProto rpcReHadoopRpcRequestProtoquest; HadoopRpcRequestProto.Builder builder = HadoopRpcRequestProto.newBuilder(); builder.setMethodName("foo"); So if my "foo" method takes two parameters, foo(String name, int num);
How do I encode the parameters and set them to the HadoopRpcRequestProto's request field?
TIA
-26092740 0System.out.println((int)(5.4%((int)5.4)*10));
Basically 5.4 mod 5 gets you .4 * 10 gets you 4.
I'm writing a unit test and the piece of code its testing requires that a file be in Request.Files.
In my controller I'm calling something called AddDocument(file) and the file is taken from Request.Files.
How do you achieve unit testing this? Isn't the Request only available in the controller?
-22242913 0Write only one function & call it on both event.
$( "#target" ).keypress(function() { funABC(); });
$( "#target" ).click(function() { funABC(); });
function funABC(){alert("DONE");} One more shortcut :
$( "#target" ).click(function() { $( "#target" ).keypress(); }); $( "#target" ).keypress(function() { funABC(); });
-15730635 0 Jquery Ajax requests not working on IE 10 (due to cache) I would like to begin with this. I am fed up with IE. I have the code below:
$(function () { $("#cal").on('click', "#forward", function () { $.ajax({ url: "Home/Calendar?target=forward", type: "GET", success: function (result) { $("#cal").html(result); } }); }); }); $(function () { $("#cal").on('click', "#backwards", function () { $.ajax({ url: "Home/Calendar?target=backwards", type: "GET", success: function (result) { $("#cal").html(result); } }); }); }); It is an ajax call to a controller action in an C# MVC application. It just goes back and forth a calendar's months replacing the html. Now I know that you need to reattach the event due to the html() call and that is why I use on() with JQuery 1.7. I have used delegate() as well. In FF, Chrome it works as intended. In IE 10 it does not. I am at a loss. I knew that IE had issues with delegate in IE8 and with JQuery < 1.5 but this is not the case.
Does anyone know how to solve this?
-21359209 0 How to pass the asp.Identity object to a second register pageI am building a much more advanced registration process which consists of 3 pages, the first page is a form that grabs a username(email form) and a password with confirmation. The button click on this page creates the user in an unverified state in the db and redirects to the page where the profile is created. Once the create profile button is clicked and the profile is created in the db the redirect takes you to the Credit Card info page where the form is filled out, the credit card is verified and then that info is written to a table in the database.
I have disabled the loggedin user display in the header so that I can use the registrants First and Last name which arent entered until the Credit Card page. Since the identityUser is required for the sign on and thus to populate the loggedin user control, how can I pass this object from page to page?
Code where original template was logging in the user: (Note:I commented out the sign in code)
Protected Sub CreateUser_Click(sender As Object, e As EventArgs) Dim userName As String = UserNameCtrl.Text Dim manager = New UserManager() Dim newuser = New IdentityUser() With {.UserName = userName} manager.UserValidator = New UserValidator(Of IdentityUser)(manager) With {.AllowOnlyAlphanumericUserNames = False} Dim result = manager.Create(newuser, Password.Text) If result.Succeeded Then Session("email") = newuser.UserName Session("userid") = newuser.Id.ToString() 'uncomment the code below if you want the auto sign in to occur 'IdentityHelper.SignIn(manager, newuser, isPersistent:=False) IdentityHelper.RedirectToReturnUrl(Page.ResolveUrl("~/Account/CreateProfile.aspx?Guid=" & newuser.Id.ToString()), Response) Else ErrorMessage.Text = Encoder.HtmlEncode(result.Errors.FirstOrDefault()) End If End Sub I now call this routine to sign in the user once the third page of the registration process is completed. (Session("userid") is the new registrants generated userid)
Private Sub SignInUserOnFormCompletion() Dim manager = New UserManager() manager.UserValidator = New UserValidator(Of IdentityUser)(manager) With {.AllowOnlyAlphanumericUserNames = False} Dim newuser = New IdentityUser() With {.Id = Session("userid").ToString()} IdentityHelper.SignIn(manager, newuser, isPersistent:=False) End Sub The problem is the above doesnt work as the newuser somehow has different credentials. How can I pass the original newuser from the first page to the third page where I can use it in the SignInUserOnFormCompletion subroutine? Do I create a cookie and pass it around that way? This is a new topic for me so I'm not familiar with the proper methods to accomplish this.
-30154654 0 Eclipse does not recognize static web content under src/main/resources/staticI am working on a Spring boot web project. I have an index.html file under src/main/webapp, and a .js file under src/main/resources/static/js.
Eclipse is complaining on the <script></script> inclusion inside the index.html file: Undefined Javascript file. The above is also the case for css files under src/main/resources/static/css.
In addition, I'm using wro to generate unified angularjs-bootstrap js and css files, which are generated under target\generated-resources\static and Eclipse cannot find them either.
Is there any way to configure Eclipse to include the above directories?
-21608440 0Can't you do:
Set typeAMems = errorSet.findAll { it.type == 'A' }.lineNumber Set typeBMems = errorSet.findAll { it.type == 'B' }.lineNumber
-36864836 0 How to register a post type and taxonomy in WordPress and display in a page/single post I have a question about WordPress register post type:
How can I register a post type like portfolio?
For example: In the WordPress dashboard, I can register a post type and taxonomy. After this I want to create a page to display all the portfolio and taxonomies like (portfolio.php) and display a single portfolio in a (single-portfolio.php).
Can someone explain this for me please?
-26187227 0 Is this myFile = SD.open("test.txt", FILE_WRITE); class object usage good/possible in cppI have created a class object named myFile for a class File which is present in one of my cpp files (FILE.cpp) which I am calling in another file(SDtrail.cpp) where I am working on.
In SDtrail.cpp file I have defined a statement as shown below myFile = SD.open("test.txt", FILE_WRITE);
So, my doubt is can I declare like above statement or not as I think that this is the root cause of the following errors
error: no match for 'operator=' in 'myFile = SDClass::open(const char*, uint8_t)(((const char*)"test.txt"), 19u)'
error: could not convert 'myFile' to 'bool'
I know that SD.open("test.txt", FILE_WRITE); will provide 1(success) or 0(fail) as output and myFile is an object of my File class ( I have declared it as File myFile). I don't know whether a class object consists of a type declaration. (FYI: myFile = SD.open("test.txt", FILE_WRITE); worked perfectly when I ran that in my Arduino software and when I have printed the myFile variable I got 1 as an output.)
Thanks in advance.
-24361668 0Your script filter is slow on big data and doesn't use benefits of "indexing". Did you think about parent/child instead of nested? If you use parent/child - you could use aggregations natively and use calculate sum.
-34832022 0Use another variable:
int dist=fillUps[index].calcDistance(); //or double, depands on the method's returning value fillUps[index].calcMPG(dist);
-16383856 0 You should try a later dtrace release. I believe this was fixed - the stack walk code had to keep on being rewritten due to erraticness of compilers, distros and 32 vs 64 bit kernels.
-37562195 0For logical reasons, tables are filled row by row in iText:
If you want to change the order, you need to do this yourself by creating a data matrix first. One way to do this, is by creating a two-dimensional array (there are other ways, but I'm using an array for the sake of simplicity).
The RowColumnOrder example shows how it's done.
This is the normal behavior:
document.add(new Paragraph("By design tables are filled row by row:")); PdfPTable table = new PdfPTable(5); table.setSpacingBefore(10); table.setSpacingAfter(10); for (int i = 1; i <= 15; i++) { table.addCell("cell " + i); } document.add(table); You want to change this behavior, which means that you have to create a matrix in which you change the order rows and columns are filled:
String[][] array = new String[3][]; int column = 0; int row = 0; for (int i = 1; i <= 15; i++) { if (column == 0) { array[row] = new String[5]; } array[row++][column] = "cell " + i; if (row == 3) { column++; row = 0; } } As you can see, there is no iText code involved. I have 15 cells to add in a table with 5 columns and 3 rows. To achieve this, I create a String[3][5] array of which I fill every row of a column, then switch to the next column when the current column is full. Once I have the two-dimensional matrix, I can use it to fill a PdfPTable:
table = new PdfPTable(5); table.setSpacingBefore(10); for (String[] r : array) { for (String c : r) { table.addCell(c); } } document.add(table); As you can see, the second table in row_column_order.pdf gives you the result you want.
-26320408 0You can use that, im not using the prettiest way, but you can write a new accessor that injects that methods.
Classes:
class Container def property=(arg) arg.called_from = self.class @arg = arg end def property @arg end end class SomeClass def container_class @klass end def called_from=(klass) @klass = klass end end Spec:
require_relative 'container' describe Container do let(:container) { Container.new } it 'passes message' do container.property = SomeClass.new expect(container.property.container_class).to eq Container end end
-14327896 0 A singleton would be fine if you're not going to store any of the information in between sessions.
For example, if you wanted to save a user's email address so they don't have to fill it out every time to log in, you'll need to use
[[NSUserDefaults standardUserDefaults] valueForKey:@"someKeyName"]; Just like in your question.
-25167304 0char isn’t special in this regard (besides its implementation-defined signedness), all conversions to signed types usually exhibit this “cyclic nature”. However, there are undefined and implementation-defined aspects of signed overflow, so be careful when doing such things.
What happens here:
In the expression
c=c+10 the operands of + are subject to the usual arithmetic conversions. They include integer promotion, which converts all values to int if all values of their type can be represented as an int. This means, the left operand of + (c) is converted to an int (an int can hold every char value1)). The result of the addition has type int. The assignment implicitly converts this value to a char, which happens to be signed on your platform. An (8-bit) signed char cannot hold the value 135 so it is converted in an implementation-defined way 2). For gcc:
For conversion to a type of width N, the value is reduced modulo 2N to be within range of the type; no signal is raised.
Your char has a width of 8, 28 is 256, and 135 ☰ -121 mod 256 (cf. e.g. 2’s complement on Wikipedia).
You didn’t say which compiler you use, but the behaviour should be the same for all compilers (there aren’t really any non-2’s-complement machines anymore and with 2’s complement, that’s the only reasonable signed conversion definition I can think of).
Note, that this implementation-defined behaviour only applies to conversions, not to overflows in arbitrary expressions, so e.g.
int n = INT_MAX; n += 1; is undefined behaviour and used for optimizations by some compilers (e.g. by optimizing such statements out), so such things should definitely be avoided.
A third case (unrelated here, but for sake of completeness) are unsigned integer types: No overflow occurs (there are exceptions, however, e.g. bit-shifting by more than the width of the type), the result is always reduced modulo 2N for a type with precision N.
Related:
1 At least for 8-bit chars, signed chars, or ints with higher precision than char, so virtually always.
2 The C standard says (C99 and C11 (n1570) 6.3.1.3 p.3) “[…] either the result is implementation-defined or an implementation-defined signal is raised.” I don’t know of any implementation raising a signal in this case. But it’s probably better not to rely on that conversion without reading the compiler documentation.
-11325145 0 Team City nightly build fails to startI have a Team City instance running on my PC.
I've set up a nightly build to run at midnight each night, even if there are no checkins to build.
I leave the PC locked at night so assume the build should trigger.
However I keep getting "Unable to collect changes", "Failed to start build", "Failed to collect changes, error: org.tmatesoft.svn.core.SVNException: svn: E210003: Unknown host MySVNServer".
If I set the build to run during the day, it triggers fine, even when the PC is locked.
I have a checkin triggered build, and a couple of others for 1 off ad-hoc builds to the same environment, they all run fine.
Will Team City build fail if I am not "logged in", is the fact the PC is locked causing the issue?
-19003558 0 Inner query in LinqHow to write a linq query to retreive questions from questions table which is not attempt by user before.
question table
create table questions ( questionID int, question varchar, primary key(questionID) ); create table result { id int, answered_by varchar, questionid int, answer varchar, primary key (id), foreign key ( questionid) references question(questionID) );
-14341290 0 You can have distinct patterns only for positive and negative values.You should do something like:
public class DecimalScientificFormat extends DecimalFormat { private static DecimalFormat df = new DecimalFormat("#0.00##"); private static DecimalFormat sf = new DecimalFormat("0.###E0"); @Override public StringBuffer format(double number, StringBuffer result, FieldPosition fieldPosition) { String decimalFormat = df.format(number); return (0.0001 != number && df.format(0.0001).equals(decimalFormat)) ? sf.format(number, result, fieldPosition) : result.append(decimalFormat); } }
-12424460 0 You can create a ModelValidatorProvider for Enterprise Library validation. Brad Wilson has a blog post describing how to do this.
However, it looks like this will only perform server side validation. If the attributes you are using are very similar to DataAnnotations, I would recommend using them instead.
-29749900 0 Extract details that are in both using awk or sedI'm trying to write a script which needs to extract details that exist on both versions.
ABC-A1 1.0 tomcat BBC-A1 2.0 tomcat CAD-A1 1.0 tomcat ABC-A1 2.0 tomcat BBC-A1 2.0 tomcat In the above data , I would like to extract the names that exist in both 1.0 and 2.0 ( that will be ABC-A1 and BBC-A1 )
How can I do this using awk or sed or any other?
-30306385 0 Not getting values from grid table when checkbox is checked?I want to get value of row where checkbox is checked. I am new to C# windows forms and so far unsuccessful. I want to eventually use these row values, so if user selects multiple row and then I should get value for those checked. Also, I have set the selection mode to 'fullrowselect'
Please suggest changes to my code
private void button1_Click(object sender, EventArgs e) { StringBuilder ln = new StringBuilder(); dataGridView1.ClearSelection(); foreach (DataGridViewRow row in dataGridView1.Rows) { if (dataGridView1.SelectedRows.Count>0 ) { ln.Append(row.Cells[1].Value.ToString()); } else { MessageBox.Show("No row is selected!"); break; } } MessageBox.Show("Row Content -" + ln); }
-36376059 0 This is an aggregation query, but you don't seem to want the column being aggregated. That is ok (although you cannot distinguish the rk that defines each row):
select count(*) as CountOfId, max(dateof) as maxdateof from t group by fk; In other words, your subquery is pretty much all you need.
If you have a reasonable amount of data, you can use a MySQL trick:
select substring_index(group_concat(id order by dateof desc), ',', 1) as id count(*) as CountOfId, max(dateof) as maxdateof from t group by fk; Note: this is limited by the maximum intermediate size for group_concat(). This parameter can be changed and it is typically large enough for this type of query on a moderately sized table.
see this Fiddle
you just need to set hours to midnight 12. You can do it like this d.setHours(0,0,0,0);
var today = true; var d = new Date(), till = new Date(), t, h, m; d.setHours(0, 0, 0, 0); if (today) { till.setDate(d.getDate() + 1); till.setHours(0, 0, 0, 0); while (d <= till) { h = d.getHours(); m = d.getMinutes(); t = h % 12; t = t == 0 ? 12 : t; $('#time').append('<li>' + (t < 10 ? '0' : '') + t + ':' + (m < 10 ? '0' : '') + m + ' ' + (h < 12 || h == 24 ? 'AM' : 'PM') + '</li>'); d.setMinutes(m + 15); } } else { // print full list of time } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div id="time"></div> I have a file like below
<AUDIT_RECORD TIMESTAMP="2013-07-30T17:52:29" NAME="Query" CONNECTION_ID="10" STATUS="0" SQLTEXT="show databases"/> <AUDIT_RECORD TIMESTAMP="2013-07-29T17:27:53" NAME="Quit" CONNECTION_ID="12" STATUS="0"/> <AUDIT_RECORD TIMESTAMP="2013-07-30T17:52:29" NAME="Query" CONNECTION_ID="10" STATUS="0" SQLTEXT="show grants for root@localhost"/> <AUDIT_RECORD TIMESTAMP="2013-07-30T17:52:29" NAME="Query" CONNECTION_ID="10" STATUS="0" SQLTEXT="create table stamp like paper"/> Here each record begin with <AUDIT_RECORD and end with "/> and the record might spread across multiple lines.
My requirement is to display result like below
<AUDIT_RECORD TIMESTAMP="2013-07-30T17:52:29" NAME="Query" CONNECTION_ID="10" STATUS="0" SQLTEXT="show databases"/> <AUDIT_RECORD TIMESTAMP="2013-07-30T17:52:29" NAME="Query" CONNECTION_ID="10" STATUS="0" SQLTEXT="show grants for root@localhost"/> <AUDIT_RECORD TIMESTAMP="2013-07-30T17:52:29" NAME="Query" CONNECTION_ID="10" STATUS="0" SQLTEXT="create table stamp like paper"/> for that purpose I have used
sed -n "/Query/,/\/>/p" file.txt but it is displaying the entire file including the record with the string "Quit".
Can anyone help me regarding this? Also please let me know if it is possible to match exactly string named "Query" ( like grep -w "Query" ).
Suppose we have fixed row sums for a matrix (say, MAT) of dimension 3 x N which (i.e the row sums) are = (RS,LS,NCS)'. The N column vectors are unknown. There are 3 possible choices for each of the N column vectors - (1,0,0)', (0,1,0)', (0,0,1)'.
So the first question is -
How can we get all possible choices of this matrix MAT by keeping the row sums fixed as (RS,LS,NCS)' using R software ?
For example - Take N=7, RS=sum of first row=2, LS=sum of second row=2 and NCS=sum of third row=3. So (1,0,0)' will appear twice, (0,1,0)' will also appear twice and (0,0,1)' will appear thrice in the set of N columns of that matrix MAT. One possible choice of MAT is -
1 0 0 0 0 1 0
0 1 0 0 0 0 1
0 0 1 1 1 0 0
I think there will be 7!/(2!x2!x3!)=210 possible choices of MAT by keeping the row sum fixed as (2,2,3)'.
But how to get those possible choices of MAT using R software ? It should be an array of dimension 3xNxn, where n is the number of possible choices of MAT.
The second question is-
How the solution mechanism changes in the above problem if the possible choices of each of the N column vectors of that matrix MAT becomes - (1,1,0)', (1,0,0)', (0,1,0)', (0,0,1)' ?
-20446616 0Got it working, when I renamed the id, I forgot to rename the digarm element with the new id. I corrected it.
-21390196 0 Detect linux version 5 or 6I am new to shell script as I do to detect the version of linux? with shell script would detect if the version is 5 or 6 Linux with IF if possible to execute a block of installation.
-24301734 0If you specify context configuration location on your test class, and use spring test runner the context will be cached not reloaded each time.
Something like :
@RunWith (SpringJUnit4ClassRunner.class) @ContextConfiguration (locations = "classpath:/config/applicationContext-test.xml") @WebAppConfiguration public class MyTest {}
-5349875 0 matlab "arrayfun" function Consider the following function, which takes a gray image (2D matrix) as input:
function r = fun1(img) r = sum(sum(img)); I'm thinking of using arrayfun to process a series of images(3d matrix), thus eliminating the need for a for loop:
arrayfun(@fun1, imgStack); But arrayfun tries to treat every element of imgStack as an input to fun1, the result of the previous operation also being a 3D matrix. How can I let arrayfun know that I want to repeat fun1 only on the 3rd dimension of imgStack?
Another question, does arrayfun invoke fun1 in parallel?
Try the following command:
function s:WipeBuffersWithoutFiles() let bufs=filter(range(1, bufnr('$')), 'bufexists(v:val) && '. \'empty(getbufvar(v:val, "&buftype")) && '. \'!filereadable(bufname(v:val))') if !empty(bufs) execute 'bwipeout' join(bufs) endif endfunction command BWnex call s:WipeBuffersWithoutFiles() Usage:
:BWnex<CR> Note some tricks:
filter(range(1, bufnr('$')), 'bufexists(v:val)') will present you a list of all buffers (buffer numbers) that vim currently has.empty(getbufvar(v:val, '&buftype')) checks whether buffer actually should have a file. There are some plugins opening buffers that are never supposed to be represented in filesystem: for example, buffer with a list of currently opened buffers emitted by plugins such as minibufexplorer. These buffers always have &buftype set to something like nofile, normal buffers have empty buftype.Is it wrong to do it like this?
<div class="row"> <div class="medium-6 columns">some content</div> <div class="medium-6 columns">some content</div> <div class="medium-6 columns">some content</div> <div class="medium-6 columns">some content</div> <div class="medium-6 columns">some content</div> <div class="medium-6 columns">some content</div> </div> Instead of:
<div class="row"> <div class="medium-6 columns">some content</div> <div class="medium-6 columns">some content</div> </div> <div class="row"> <div class="medium-6 columns">some content</div> <div class="medium-6 columns">some content</div> </div> <div class="row"> <div class="medium-6 columns">some content</div> <div class="medium-6 columns">some content</div> </div> From what I can see the result is the same but with less divs.
I have several pages made from the a template that has a navigation made with idTabs, in javascript.
This is what I have in <head>:
<script type="text/javascript" src="jquery.idTabs.min.js"></script> <script src="scripts/jquery.js" type="text/javascript"></script> <script src="scripts/lightbox.js" type="text/javascript"></script> <link href="css/lightbox.css" rel="stylesheet" type="text/css" /> <link href="css/sample_lightbox_layout.css" rel="stylesheet" type="text/css" /> Then in <body>:
<div id="poze"> <div id="gallery" class="lbGallery"> <ul> <li> <a href="images/lightboxdemo2.jpg" title=""><img src="images/lightboxdemo_thumb2.jpg" width="72" height="72" alt="Flower" /></a> </li> <li> <a href="images/lightboxdemo5.jpg" title=""><img src="images/lightboxdemo_thumb5.jpg" width="72" height="72" alt="Tree" /></a> </li> </ul> </div> <script type="text/javascript"> // BeginOAWidget_Instance_2127022: #gallery $(function(){ $('#gallery a').lightBox({ imageLoading: '/images/lightbox/lightbox-ico-loading.gif', // (string) Path and the name of the loading icon imageBtnPrev: '/images/lightbox/lightbox-btn-prev.gif', // (string) Path and the name of the prev button image imageBtnNext: '/images/lightbox/lightbox-btn-next.gif', // (string) Path and the name of the next button image imageBtnClose: '/images/lightbox/lightbox-btn-close.gif', // (string) Path and the name of the close btn imageBlank: '/images/lightbox/lightbox-blank.gif', // (string) Path and the name of a blank image (one pixel) fixedNavigation: false, // (boolean) Boolean that informs if the navigation (next and prev button) will be fixed or not in the interface. containerResizeSpeed: 400, // Specify the resize duration of container image. These number are miliseconds. 400 is default. overlayBgColor: "#999999", // (string) Background color to overlay; inform a hexadecimal value like: #RRGGBB. Where RR, GG, and BB are the hexadecimal values for the red, green, and blue values of the color. overlayOpacity: .6, // (integer) Opacity value to overlay; inform: 0.X. Where X are number from 0 to 9 txtImage: 'Image', //Default text of image txtOf: 'of' }); }); // EndOAWidget_Instance_2127022 </script> </div> The navigation has two links: a <div> with text, and a <div> with lightbox gallery. The lightbox is a widget from Dreamweaver.
<div id="navidtabs"> <ul class="idTabs"> <li><a href="#info">informatii</a></li> <li><a href="#pictures">poze</a></li> </ul> </div> Something unbelievable happens: I apply the template to a new page, make the modifications, save it, load it into the wamp server, switch between the navigation links, test the lightbox, it works! But when I switch for example, to a different page, and return, the lightbox crashes. I can see the pictures, but when I click it opens another page just for the picture.
I forgot to say that I have a third <div> conected into the navigation, a select command to retrieve data from database. The entire file is PHP.
What can I do to mantain the lightbox effect?
-25891688 0Try re-writing your query to:
$name = trim($form_state['values']['name']); $formwem = $form_state['values']['settings']['active']; $result = db_query("INSERT INTO twittername (name, Blogurt, Twitter_name) VALUES (':name',':blogurt',':twitter_name')", array(':name' => $name, ':blogurt' => $formwem, ':twitter_name' => $formwem)); Though I'm not sure which form field populates the two columns Blogurt and Twitter_name. Can you please explain?
Don't rely on order by when using mutlirows variable assignment.
try this for instance:
DECLARE @c INT = 0 SELECT @c = @c + x FROM (VALUES(1),(2),(3)) AS src(x) WHERE x BETWEEN 1 AND 3 ORDER BY 1 - x DESC SELECT @c SET @c = 0 SELECT @c = @c + x FROM (VALUES(1),(2),(3)) AS src(x) WHERE x BETWEEN 1 AND 3 ORDER BY x DESC SELECT @c http://sqlmag.com/sql-server/multi-row-variable-assignment-and-order
-37359579 0 append value to textbox on changing dynamic selectboxI have created a dynamic bootstrap form. Input field is being created by clicking 'add field' button. now am trying to get value of select box into respective textbox in same parent div. but i failed to do so. my code is below:
<div class="input_fields_wrap_credit "> <div class="form-group"> <h3>Credit / Deposit <a href="#add_credit_control" class="add-btn pull-right add_credit_field_button"><i class="fa fa-plus-circle"></i> add credit field</a></h3> </div> <!-- /form-group --> <div class="form-group"> <div class="form-input col-md-2"> <input id="cr_ac_no" name="cr_ac_no[]" type="text" placeholder="Account no." class="form-control input-sm" required="" value=""> </div> <div class="form-input col-md-6 col-xs-12 "> <select name="cr_gl_head[]" class="form-control cr_gl_head"><?=$accounts->GET_CHART_OF_AC()?></select> </div> <!-- /controls --> <div class="form-input col-md-3 col-xs-12 "> <input type="text" name="cr_amount[]" class="form-control cr_amt" maxlength="10" placeholder="Amount"> </div> <!-- /controls --> <a href="#" class="remove_field"><i class="fa fa-remove"></i></a> </div><!--form-group --> </div> JQUERY:
<!--credit --> <script type="text/javascript"> $(document).ready(function() { var max_fields = 10; //maximum input boxes allowed var wrapper = $(".input_fields_wrap_credit"); //Fields wrapper var add_button = $(".add_credit_field_button"); //Add button ID var y = 1; //initlal text box count $(wrapper).on('click','.add_credit_field_button',function(e){ //on add input button click e.preventDefault(); if(y < max_fields){ //max input box allowed y++; //text box increment $(wrapper).append('<div class="form-group"><div class="form-input col-md-2"><input id="cr_ac_no" name="cr_ac_no[]" type="text" placeholder="Account no." class="form-control input-sm" required="" value=""></div><div class="form-input col-md-6 col-xs-12 "><select name="cr_gl_head[]" class="form-control cr_gl_head"><?=$accounts->GET_CHART_OF_AC()?></select></div> <!-- /controls --> <div class="form-input col-md-3 col-xs-12 "><input type="text" name="cr_amount[]" class="form-control cr_amt" maxlength="10" placeholder="Amount"></div> <!-- /controls --><a href="#" class="remove_field"><i class="fa fa-remove"></i></a></div><!--form-group -->'); //add input box $('#num_cr').val(y); //number of credit field }else{ alert('Maximum allowed 10 fields.'); } }); $(wrapper).on("click",".remove_field", function(e){ //user click on remove text e.preventDefault(); $(this).parent('div').remove(); y--; }) }); </script> //append ac no. to text box <script type="text/javascript"> $(document).ready(function() { var wrapper = $(".input_fields_wrap_credit"); //Fields wrapper $(wrapper).on("change",".cr_gl_head", function(e){ //user click on remove text e.preventDefault(); var ac_no = $(this).val(); var txt = $(this).parent('div').find('#cr_ac_no').val(ac_no); }); }); </script> Any help please?
-27260020 0 Why are Spock Speck tests so wordy?Coming from JUnit background I don't really understand the point of all the text in spockD tests, since they don't show on the output from the test.
So for example, if I have a constraint on a field Double foo with constraints foo max:5, nullable:false
And I write tests like this:
void "test constraints" { when: "foo set to > max" foo=6D then: "max validation fails" !foo.validate() when: "foo is null foo=null then: "null validation fails" !foo.validate() } The test is well documented in its source, but if the validation fails, the error output doesn't take advantage of all this extra typing I've done to make my tests clear.
All I get is
Failure: | test constraints(com.grapevine.FooSpec) | Condition not satisfied: f.validate() | | | false But I can't tell form this report whether it failed the null constraint or the max constraint validation and I then need to check the line number of the failure in the test source.
At least with JUnit I could do
foo=60D; assertFalse("contraints failed to block foo>max", f.validate()); foo=null; assertFalse("contraints failed to block foo=null", f.validate()); And then I'd get useful info back from in the failure report. Which seems to both more concise and gives a more informative test failure report.
Is there some way get more robust error reporting out of Spec that take advantage of all this typing of when and then clauses so they show up on failure reports so you know what actually fails? Are these "when" and "then" text descriptors only serving as internal source documentation or are they used somewhere?
-34492246 0 Methods for Linear system solution with matlabI have a linear system Ax = b , which is created by natural splines and looks like this:
The code in matlab which is supposed to solve the system is the following:
clear; clc; x = [...] ; a = [...]; x0 = ...; n = length(x) - 1 ; for i = 0 : (n-1) h(i+1) = x(i+2) - x(i+1) ; end b= zeros( n+1 , 1 ) ; for i =2: n b(i,1) = 3 *(a(i+1)-a(i))/h(i) - 3/h(i-1)*(a(i) - a(i-1) ) ; end %linear system solution. l(1) =0 ; m(1) = 0 ; z(1) = 0 ; for i =1:(n-1) l(i+1) = 2*( x(i+2) - x(i) ) - h(i)* m(i) ; m(i+1) = h(i+1)/l(i+1); z(i+1) = ( b(i+1) - h(i)*z(i) ) / l ( i+1) ; end l(n+1) =1; z(n+1) = 0 ; c(n+1) = 0 ; for j = ( n-1) : (-1) : 0 c(j+1) = z(j+1) - m(j+1)*c(j+2) ; end but I can't understand which method is being used for solving the linear system. If I had to guess I would say that the LU method is used, adjusted for tridiagonal matrices, but I still can't find the connection with the code...
Any help would be appreciated!!!
-27716571 0Is your page rendered inside of a frame? A frame by default supports Navigation. If this is the case you have to set the navigation visibility property of the frame control to hidden.
<Frame Name="Frame1" NavigationUIVisibility="Hidden" >
-17995653 0 Build your query like this:
string query = string.empty query += "select "; if (CheckBoxList1[0].Selected) { query += "first_column, "; }//and so on query += " from tblProject";
-39568911 0 Laravel simple relation between models return null In my database I have users and tickets table. Now I want to create simple relation between theme, in phpmyadmin relation created between tickets.userId and users.id, now I wrote some functions on models:
User model:
public function tickets() { return $this->hasMany('App\Tickets'); } Tickets model:
public function user() { return $this->belongsTo('App\User'); } This code as dd(\App\Tickets::with('user')->get()); return null on relation result, for example:
0 => Tickets {#209 ▼ #table: "tickets" #connection: null #primaryKey: "id" #keyType: "int" #perPage: 15 +incrementing: true +timestamps: true #attributes: array:9 [▶] #original: array:9 [▶] #relations: array:1 [▼ "user" => null ]
-15707923 0 Get twitter entity value from json with PHP I am looping through each tweet in json feed from twitter. The first part of the code works perfectly...
$screen_name = "BandQ"; $count = 10; $urlone = json_decode(file_get_contents("http://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=false&screen_name=BandQ&count=".$count."&page=1"),true); $urltwo = json_decode(file_get_contents("http://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=false&screen_name=BandQ&count=".$count."&page=2"),true); $data = array_merge_recursive( $urlone, $urltwo); // Output tweets //$json = file_get_contents("http://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=false&screen_name=".$screen_name."&count=".$count."", true); //$decode = json_decode($json, true); $count = count($data); //counting the number of status $arr = array(); for($i=0;$i<$count;$i++){ $text = $data[$i]["text"]." "; $retweets = $data[$i]["text"]."<br>Retweet Count: ".$data[$i]["retweet_count"]. "<br>Favourited Count: ".$data[$i]["favorite_count"]."<br>".$data[$i]["entities"]["user_mentions"][0]["screen_name"]."<br>"; // $arr[] = $text; $arr[] = $retweets; } // Convert array to string $arr = implode(" ",$arr); print_r($arr); but when I try to get entities->user_mentions->screen_name the PHP throws errors...
Notice: Array to string conversion in C:\xampp\htdocs\tweets.php on line 29 Notice: Use of undefined constant user_mentions - assumed 'user_mentions' in C:\xampp\htdocs\tweets.php on line 29 Notice: Use of undefined constant screen_name - assumed 'screen_name' in C:\xampp\htdocs\tweets.php on line 29 How do I get that screen_name value?
Many thanks
-31754823 0You need to use the bodyparser middleware:
var bodyParser = require('body-parser'); and then
app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true }));
-40158302 0 With flat product enabled, you'd better use
$collection = Mage::getResourceModel('catalog/product_collection') You will be able to retrieve disabled and enabled products.
See this answer for a better explanation: http://magento.stackexchange.com/a/40001/32179
-6156611 0You're building a dynamic search condition. By forcing one single statement to cover both cases you are cutting the optimizer options. The generated plan has to work in both cases when @seconds is null and when is not null. You'll be much better using two separate statement:
IF @SECOND IS NULL THEN SELECT * FROM BANK_DETAIL WHERE X = @FIRST ORDER BY X ELSE SELECT * FROM BANK_DETAIL WHERE X >= @FIRST AND X <= @SECOND ORDER BY X You intuition to 'simplify' into one single statement is leading you down the wrong path. The result is less text, but much more execution time due to suboptimal plans. The article linked at the beginning of my response goes into great detail on this topic.
-37373524 0 nsupdate in basic CSH script for BIND in unix
I have never used C and I'm not writing this for security reasons, i am just writing this script to test an update via nsupdate to my BIND for a specific zone being "zoneA.unix". But i am receiving "option: undefined variable"
And I'm not to sure if this is the correct way to do nsupdate via a user's inputs.
echo "First of all we need to grab your username:" set uname = $< if ($uname == "zoneA")then echo "password: " set passwd = $< if ($passwd == "Azone")then echo "you are in" echo "now to do the nsupdate" echo "do you wish to (A)dd or (D)elete a record" set numeric = $< if ($numeric == "A")then $option = "add" $testinga = "add" else if($numeric == "D")then $option = "delete" $testinga = "delete" endif echo "what to $testinga to the zone zoneA.unix?" set innerzonename = $< nsupdate -k /usr/local/etc/namedb/Keys/Kzonea.+157+57916.key -v debug yes zone zonea.unix update $testinga $innerzonename 86400 A 127.0.0.1 show echo "is this correct (Y)es (n)" set sendoff = $< if($sendoff == "Y")then send else if ($sendoff == "N")then quit endif So the code works fine til the $option part and I'm not to sure if it will work after the input needed during the nsupdate because it won't pause it, well i don't know how i can pause it.
What it seems to be doing is running nsupdate and waiting until nsupdate is finished. anyway i can pass them into it?
I would also propose Solution 4: write a code generation tool.
Pros:
Cons:
Have you ever look servicestack ? It's awesome ,totally DTO based and very easy to create API for .net
Please look out my blog post about that
Check this thread for authentication options in ServiceStack.
https://groups.google.com/d/topic/servicestack/U3XH9h7T4K0/discussion
Look at example here
-2372641 0Use the SqlDataReader.Read method:
while (sqlDREmailAddr.Read()) { ... // Assumes only one column is returned with the email address strEmailAddress = sqlDREmailAddr.GetString(0); }
-39145786 0 Create a row with subtotals above data to be added with a Loop through an array in VBA I need to programmatically format an excel table creating two different subtotals base on changes of values in two specified column (the first and second of the spreadsheet).
I managed to code the routine for the first subtotals but I’m now stuck trying to figure out the second part of the code.
In the second routine I need to create the subtotal row above the data that will be added. I couldn’t manage to insert the calculation in the right row and there is something wrong when I do the loop through the columns included in the array.
Anyone that can see what I’m doing wrong?
Thank you
Public Sub SubtotalTable() Dim RowNumber As Long Dim RangePointer As Range Dim RangeTopRow As Range 'Pointing the column to check Set RangePointer = ActiveSheet.Range("B1") 'Assigning the first row to a range Set RangeTopRow = Rows(2) 'Assigning to long a variable the number of row from which begin checking RowNumber = 3 Do If RangePointer.Offset(RowNumber).Value <> RangePointer.Offset(RowNumber - 1).Value Then Set RangeTopRow = Rows(RowNumber) 'Call the function to insert the row Call InsertRowTotalsAbove(RangePointer.Offset(RowNumber), RangeTopRow, RowNumber) Else RowNumber = RowNumber + 1 End If RowNumber = RowNumber + 1 Loop End Sub Public Function InsertRowTotalsAbove(RangePointer As Range, lastRow As Range, RowNumber As Long) Dim ArrayColumns() As Variant Dim ArrayElement As Variant Dim newRange As Range 'Assigning number of columns to an array ArrayColumns = Array("D", "E", "F", "G") Do If RangePointer.Offset(RowNumber).Value = RangePointer.Offset(RowNumber - 1).Value Then RowNumber = RowNumber - 1 Else ActiveSheet.Cells(RowNumber + 1, 2).Select Set newRange = Range(ActiveCell, ActiveCell.Offset(0, 0)) Rows(newRange.Offset(RowNumber + 1).Row).Insert shift:=xlDown newRange.Offset(RowNumber + 1, 0).Value = "Totale" & " " & newRange.Offset(RowNumber + 2, 0) For Each ArrayElement In ArrayColumns newRange.Cells(RowNumber, ArrayElement).Value = Application.WorksheetFunction.Sum(Range(lastRow.Cells(-1, ArrayElement).Address & ":" & RangePointer.Cells(0, ArrayElement).Address)) Next ArrayElement End If Loop End Function
-3969464 0 Audiogram is a constructor and seriesColors are not used apart from this method
Assuming that your statement is accurate, and assuming that you posted the entire constructor, the seriesColors attribute (static or not) serves no useful purpose whatsoever.
If this is the case, the then fix for the memory leak is to simply remove the seriesColors declaration from your code, as follows:
// static private ArrayList seriesColors = new ArrayList(); <<<=== remove this line public Audiogram(int widthParm, int heightParm) throws Exception { super(widthParm, heightParm); // seriesColors.add(new Color(0, 0, 255)); <<<=== remove this line // Set the default settings to an industrial audiogram setType(INDUSTRIAL_AUDIOGRAM); } However, I suspect that this is not the whole story ...
EDIT
Comment out those two lines as indicated. If the code compiles with those two lines commented out, then they are definitely redundant.
However, it strikes me that your knowledge of Java must be close to zero. If this is the case, you should NOT be trying to clean up memory leaks and the like in other peoples' code. Learn some Java first.
-29954001 0 JPQL for a Unidirectional OneToManyI need a jpql query for my Spring repository interface method, to retrieve all Posts for a given Semester.
@LazyCollection(LazyCollectionOption.FALSE) @OneToMany(cascade = CascadeType.MERGE) @JoinTable ( name = "semester_post", joinColumns = {@JoinColumn(name = "semester_id", referencedColumnName = "id")}, inverseJoinColumns = {@JoinColumn(name = "post_id", referencedColumnName = "id", unique = true)} ) private List<PostEntity<?>> posts = new ArrayList<>(); PostEntity doesn't have a reference to Semester, and I do not want to add one, because I plan to use this PostEntity for other things than Semester. Maybe I'll have another class (let's say Group) which will also have a OneToMany of PostEntity (like the one in Semester)
So, how do I write this SQL query as a JPQL one ?
select * from posts join semester_post on semester_post.post_id = posts.id where semester_post.semester_id = 1; My repository
public interface PostRepository extends JpaRepository<PostEntity, Long> { String QUERY = "SELECT p FROM PostEntity p ... where semester = :semesterId"; @Query(MY_QUERY) public List<PostEntity> findBySemesterOrderByModifiedDateDesc(@Param("semesterId") Long semesterId);
-37382425 0 If I understand your question correctly, then maybe try something like this:
First create a "dummy" config file in a directory that you will map as a volume
mkdir mapdir touch mapdir/myconfig.cfg In your Dockerfile you'll do what you need to do with that config file. Maybe as part of a CMD clause
FROM ... RUN ... CMD ["sed", "<editstuff>, "mapdir/myconfig.cfg" ] Then build and run your container
docker build . docker run --name mycontainer -v mapdir:mapdir ... It's still a strange approach, but if you absolute can only change the config file from within your container, give this a go.
-35811149 0 Codeigniter 3x Query Builder class seems to be generating extra segments to my queryI am using the latest version of the Codeigniter framework for PHP. Here is my code.
public function get_user_by_username( $username ) { $this->db->where( 'username', strtolower( $username ) ); $q = $this->db->get( 'users', 1 ); foreach( $q->result() as $row ) { return $row; } return NULL } I called the last_query() method to get the query that was generating the problem and this pops up messing up the entire query. I didn't code this. Codeigniter is generating this on its own.
SELECT * FROM `users` WHERE `serial` IS NULL AND `password` IS NULL AND `username` = '[username]' LIMIT 1 I need Codeigniter to generate this instead as I expected.
SELECT * FROM `users` WHERE `username` = '[username]' LIMIT 1 I'm just now starting to code with Codeigniter 3x after using version 2x for the last couple of years. Thanks in advance.
-6697575 0It makes no sense to clear the buffer.
If it were an output buffer e.g. BufferedWriter, then you could flush the buffer to make sure that all buffered content has been written before closing the buffer.
In this case you can just close the buffer, after br.readLine() returns null, which means that there is no more input to be read.
Based on what I found out here: Sending correct JSON content type for CakePHP
The correct way to return JSON in CakePHP is like so:
$this->response->type('json'); $this->response->body(json_encode(array('message'=>'Hello world!'))); This is because the headers can be overridden and therefore the CORS doesn't work unless you do it the 'proper' way using the response object in Cake.
-727269 0 Web service response is null, but SOAP message response is validI am writing a web service starting with writing the WSDL. I have been generating server-side skeleton code using wsimport and then writing my own implementing class. I'm running the web service on an Axis2 server. When using soapUI, the SOAP messages coming to and from the service look fine, but when using a web service client, I'm getting null in the client-side stubs. I've heard that this could be a namespace issue, but I see anything wrong. Here is my copy of the WSDL. Any help would be appreciated.
<?xml version="1.0" encoding="UTF-8"?> <wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:ns1="http://org.apache.axis2/xsd" xmlns:ns="http://test.sa.lmco.com" xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" targetNamespace="http://test.sa.lmco.com"> <!-- **************** --> <!-- ** Types ** --> <!-- **************** --> <wsdl:types> <xs:schema attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://test.sa.lmco.com"> <xs:element name="sayHello"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="s" nillable="true" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="sayHelloResponse"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="return" nillable="true" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="getTaxonomyNode"> <xs:complexType> <xs:sequence> <xs:element name="taxonomyId" minOccurs="1" maxOccurs="1" type="xs:int" /> <xs:element name="nodeId" type="xs:int" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="getTaxonomyNodeResponse"> <xs:complexType> <xs:sequence> <xs:element name="resultNode" type="ns:TaxonomyNode" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="getChildren"> <xs:complexType> <xs:sequence> <xs:element name="taxonomyId" minOccurs="1" maxOccurs="1" type="xs:int" /> <xs:element name="parentNodeId" minOccurs="1" maxOccurs="1" type="xs:int" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="getChildrenResponse"> <xs:complexType> <xs:sequence> <xs:element name="childNodes" minOccurs="0" maxOccurs="unbounded" type="ns:TaxonomyNode" /> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name="TaxonomyNode"> <xs:sequence> <xs:element name="taxonomyId" type="xs:int" /> <xs:element name="nodeId" type="xs:int" /> </xs:sequence> </xs:complexType> <xs:complexType name="LCD"> <xs:sequence> <xs:element name="language" type="xs:string" /> <xs:element name="content" type="xs:string" /> <xs:element name="description" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:schema> </wsdl:types> <!-- ***************** --> <!-- ** Messages ** --> <!-- ***************** --> <wsdl:message name="sayHelloRequest"> <wsdl:part name="parameters" element="ns:sayHello"/> </wsdl:message> <wsdl:message name="sayHelloResponse"> <wsdl:part name="parameters" element="ns:sayHelloResponse"/> </wsdl:message> <wsdl:message name="getTaxonomyNodeRequest"> <wsdl:part name="parameters" element="ns:getTaxonomyNode" /> </wsdl:message> <wsdl:message name="getTaxonomyNodeResponse"> <wsdl:part name="parameters" element="ns:getTaxonomyNodeResponse" /> </wsdl:message> <wsdl:message name="getChildrenRequest"> <wsdl:part name="parameters" element="ns:getChildren" /> </wsdl:message> <wsdl:message name="getChildrenResponse"> <wsdl:part name="parameters" element="ns:getChildrenResponse" /> </wsdl:message> <!-- ******************* --> <!-- ** PortTypes ** --> <!-- ******************* --> <wsdl:portType name="HelloWSPortType"> <wsdl:operation name="sayHello"> <wsdl:input message="ns:sayHelloRequest" wsaw:Action="urn:sayHello"/> <wsdl:output message="ns:sayHelloResponse" wsaw:Action="urn:sayHelloResponse"/> </wsdl:operation> <wsdl:operation name="getTaxonomyNode"> <wsdl:input message="ns:getTaxonomyNodeRequest" wsaw:Action="urn:getTaxonomyNode" /> <wsdl:output message="ns:getTaxonomyNodeResponse" wsaw:Action="urn:getTaxonomyNodeResponse" /> </wsdl:operation> <wsdl:operation name="getChildren"> <wsdl:input message="ns:getChildrenRequest" wsaw:Action="urn:getChildren" /> <wsdl:output message="ns:getChildrenResponse" wsaw:Action="urn:getChildrenResponse" /> </wsdl:operation> </wsdl:portType> <!-- ****************** --> <!-- ** Bindings ** --> <!-- ****************** --> <wsdl:binding name="HelloWSServiceSoap11Binding" type="ns:HelloWSPortType"> <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/> <wsdl:operation name="sayHello"> <soap:operation soapAction="urn:sayHello" style="document"/> <wsdl:input> <soap:body use="literal"/> </wsdl:input> <wsdl:output> <soap:body use="literal"/> </wsdl:output> </wsdl:operation> <wsdl:operation name="getTaxonomyNode"> <soap:operation soapAction="urn:getTaxonomyNode" style="document" /> <wsdl:input> <soap:body use="literal" /> </wsdl:input> <wsdl:output> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> <wsdl:operation name="getChildren"> <soap:operation soapAction="urn:getChildren" style="document" /> <wsdl:input> <soap:body use="literal" /> </wsdl:input> <wsdl:output> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> </wsdl:binding> <!-- **************** --> <!-- ** Service ** --> <!-- **************** --> <wsdl:service name="HelloWS"> <wsdl:port name="HelloWSServiceHttpSoap11Endpoint" binding="ns:HelloWSServiceSoap11Binding"> <soap:address location="http://162.16.129.25:9090/axis2/services/HelloWS"/> </wsdl:port> </wsdl:service>
-29386599 0 As of April 3, 2015, the BabelJS team has released v5.0 3 days ago which includes support for the said shorthand as stated in their blog post.
Lee Byron's stage 1 additional export-from statements proposal completes the symmetry between import and export statement, allowing you to easily export namespaces and defaults from external modules without modifying the local scope.
Exporting a default
export foo from "bar";equivalent to:
import _foo from "bar"; export { _foo as foo };
Old Answer:
This export notation
export v from "mod"; does not supported in ES6 (look at supported examples in the specification), but it can be supported in ES7 (look at this proposal).
To achieve exactly the same result you must use import for now:
import Outer from './Outer'; export {Outer};
-28505332 0 I have it working now. I have decided to change things around so the default css page loaded has the styles necessary for the newer model phones which support overflow:scroll. So therefore I have set the heights of the body, container_wrappper and side menu to 100% to begin with instead of changing that after receiving a positive response to checking if overflow: scroll is supported... Instead I check if overflow scroll is not supported and then if not supported i dynamically add a new stylesheet which has the heights of the body and container_wrapper as height: auto; instead of height:100%. it seems that this way around ie changing from height:100% to height: auto displays it correctly as opposed to the way i was doing it starting with no height and adding in height 100% if overflow scroll is* supported.. it was to do with the speed of things loading but when i do it this way even though there is a delay in loading the second stylesheet it still displays correctly after loading. so i add the following code to my head:
<link rel="stylesheet" type="text/css" href="css/main_style_new_phones.css"/> <script> if(!canOverflowScroll()){ var lnk=document.createElement('link'); lnk.href='css/main_style_old_phones.css'; lnk.rel='stylesheet'; lnk.type='text/css'; (document.head||document.documentElement).appendChild(lnk); } and this is the css in main_style_new_phones.css
body{ margin-top: 0px; /*moves #container right up to top of page so no gap*/ font-family:Arial,Helvetica,sans-serif; width: 100%; overflow: auto; z-index: 1; height: 100%; } #container_wrapper{ position: absolute; left: 0px; top: 0px; display: block; margin: 0 auto; width: 100%; background: #120F3A; overflow: auto; max-width: 100%; /*same width as full logo image width so that when on full screen the background color of the container doesn't spread across*/ z-index: 4; -webkit-transition: .3s; /* Android 2.1+, Chrome 1-25, iOS 3.2-6.1, Safari 3.2-6 */ -moz-transition: .3s; -o-transition: .3s; transition: .3s; /* Chrome 26, Firefox 16+, iOS 7+, IE 10+, Opera, Safari 6.1+ */ height: 100%; } #headernav { width: 100%; position:fixed; top: 0px; left: 0px; z-index: 10; background: #000; padding-bottom: 2px; -webkit-transition: .3s; /* Safari */ transition: .3s; } and in the css for phones that do not support overflow scroll in main_style_old_phones.css:
body{ height: auto; } #container_wrapper{ height: auto; } #headernav { position:absolute; } #swipe_menu_right{ height: auto; }
-40098668 0 I have tried two ways for this that works:
$str = "RestaurantSmith Family Restaurant"; echo preg_replace("/Restaurant(\w+)/", "$1", $str); and:
echo preg_replace("/Restaurant\B/", "", $str);
-17187362 0 How to parse below JSON How to parse below JSON code in javascript where iterators are not identical?
var js= { '7413_7765': { availableColorIds: [ '100', '200' ], listPrice: '$69.00', marketingMessage: '', prdId: '7413_7765', prdName: 'DV by Dolce Vita Archer Sandal', rating: 0, salePrice: '$59.99', styleId: '7765' }, '0417_2898': { availableColorIds: [ '249', '203' ], listPrice: '$24.95', marketingMessage: '', prdId: '0417_2898', prdName: 'AEO Embossed Flip-Flop', rating: 4.5, salePrice: '$19.99', styleId: '2898' }, prod6169041: { availableColorIds: [ '001', '013', '800' ], listPrice: '$89.95', marketingMessage: '', prdId: 'prod6169041', prdName: 'Birkenstock Gizeh Sandal', rating: 5, salePrice: '$79.99', styleId: '7730' } } How can i parse this JSON in jvascript? I want the values of 'prdName', 'listprice', 'salePrice' in javascript?
-22346803 0the thing about the max being assigned as -999, max is meant to check the maximum values, and min is checking the minimum values, so its suppose to ask at each position if the column indices if even then if it is, its asking if the greatest value (which are usually positive) bigger than -999, and if they would be less than 1000, and so on.. until i get maximums and minimums, because -2000 is actually smaller than -999 so if i entered that, its suppose to be kept in minimum not max ^_^
-9717516 0Have a look at the String.Split() function, it tokenises a string based on an array of characters supplied.
e.g.
string[] lines = text.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries); now loop through that array and split each one again
foreach(string line in lines) { string[] pair = line.Split(new[] {':'}); string key = pair[0].Trim(); string val = pair[1].Trim(); .... } Obviously check for empty lines, and use .Trim() where needed...
[EDIT] Or alternatively as a nice Linq statement...
var result = from line in text.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries) let tokens = line.Split(new[] {':'}) select tokens; Dictionary<string, string> = result.ToDictionary (key => key[0].Trim(), value => value[1].Trim());
-24952566 0 If you are using GUIDE for developing, every time you add a button to your GUI a chunk of code is generated:
% --- Executes on button press in pushbutton1. function pushbutton1_Callback(hObject, eventdata, handles) % hObject handle to pushbutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) This function is called every time you push the said button. So, if you need something to be executed when you click the button you just need to add the lines of code you want to execute below that generated chunk of code. For example, imagine you have an edit text variable called edit1 with value
edit1 = 'hello'; If you want to interact with it you need to call handles, but first you need to create a global variable:
%set the current figure handle to main application data setappdata(0,'figureHandle',gcf); %set the handles to figure's application data setappdata(gcf,'EDIT1',handles.edit1); Then, in the callback function of your button you need write the following:
% --- Executes on button press in pushbutton1. function pushbutton1_Callback(hObject, eventdata, handles) % hObject handle to pushbutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) figureHandle = getappdata(0,'figureHandle'); EDIT1 = getappdata(figureHandle,'EDIT1 '); new_string = 'updated string'; set(EDIT1, 'String', new_string); Hope this helps
-13378466 0function check(mail) { return !mail.match(/^\.|\.$/); } check('amshaegar@example.org'); // true check('amshaegar@example.org.'); // false check('.amshaegar@example.org'); // false The function check expects a mail address as a String and checks if there is no dot(.) at the beginning or end.
For detecting multiple dots(...) as well your function would look like this:
function check(mail) { return !mail.match(/^\.|\.{2,}|\.$/); }
-6529843 0 Financial Company Logos API Is there a way to dynamically pull company logos for banks and brokerages into a webpage without individually downloading each logo or building a list of URL's to link to them directly? I'm looking for any site that has an API to get company logos given a ticker symbol, company name, or website URL.
-15214852 1 depth of a tree pythoni am new to programming and am trying to calculate the depth of a python tree. I believe that my error is because depth is a method of the Node class and not a regular function. I am trying to learn oop and was hoping to use a method. This might be a new bee error... Here is my code:
class Node: def __init__(self, item, left=None, right=None): """(Node, object, Node, Node) -> NoneType Initialize this node to store item and have children left and right. """ self.item = item self.left = left self.right = right def depth(self): if self.left == None and self.right == None: return 1 return max(depth(self.left), depth(self.right)) + 1 i receive this error: >>>b = Node(100) >>>b.depth() 1 >>>a = Node(1, Node(2), Node(3)) >>>a.depth() Traceback (most recent call last): File "C:\Program Files\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 1, in <module> # Used internally for debug sandbox under external interpreter File "C:\Program Files\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 15, in depth builtins.NameError: global name 'depth' is not defined
-15198592 0 To vertically align a text in a container, multiple techniques can be used. However, most of them have additional script calculation at runtime (if the height of the text container is changing) which can mess with the business logic.
A hack can be used in your particular situation. You can add an image container with empty src inside your text container with 100% height and 0 width set by css.
<label id="uppgift" class="uppgifter" style="display:inline-block;"><img scr=""/>Abc</label> <label id="uppgift2" class="uppgifter" style="display:inline-block;"><img scr=""/>123</label> //and css .uppgifter img{ height:100%; width:0; } This way you would not have to write logic for additional added layers.
-4270843 0 Informix: How to get the rowid of the last insert statementThis is an extension of a question I asked before: C#: How do I get the ID number of the last row inserted using Informix
I am writing some code in C# to insert records into the informix db using the .NET Informix driver. I was able to get the id of the last insert, but in some of my tables the 'serial' attribute is not used. I was looking for a command similar to the following, but to get rowid instead of id.
SELECT DBINFO ('sqlca.sqlerrd1') FROM systables WHERE tabid = 1;
And yes, I do realize working with the rowid is dangerous because it is not constant. However, I plan to make my application force the client apps to reset the data if the table is altered in a way that the rowids got rearranged or the such.
-7006605 0Cout works right to left in your compiler so first rightmost is evaluated then left one. :) So the value of referenced variable isn't changed.
-8601300 0The problem is that the SOUNDEX algorithm is disabled by default and you have to use the compiler flag -DSQLITE_SOUNDEX=1 when building sqlite.
So you have to build the sqlite driver with this flag on, and then build the plugin by linking it to your sqlite build.
I want to analyze a piece of document and build an ontology from it. There could be many characteristics of this document, and it could be a hierarchy.
What is the best programming method to build this hierarchy with unlimited height? A tree?
I am looking for a broad "way" of programming, not necessary code.
-23240829 0Regular Threads can prevent the VM from terminating normally (i.e. by reaching the end of the main method - you are not using System#exit() in your example, which will terminate the VM as per documentation).
For a thread to not prevent a regular VM termination, it must be declared a daemon thread via Thread#setDaemon(boolean) before starting the thread.
In your example - the main thread dies when it reaches the end of it code (after t1.start();), and the VM - including t1- dies when t1 reaches the end of its code (after the while(true) aka never or when abnormally terminating.)
Compare this question, this answer to another similar question and the documentation.
-23165042 0 Tracking Executing ThreadsI am trying to figure out how I can track all the threads that my application is spawning. Initially, I thought I had it figured out using a CyclicBarrier, however I am seeing threads executing after my await call.
Below is the working pseudo code:
public class ThreadTesterRunner { public static void main(String[] args) throws InterruptedException { final CyclicBarrier cb = new CyclicBarrier(1); ThreadRunner tr = new ThreadRunner(cb); Thread t = new Thread(tr, "Thread Runner"); t.start(); boolean process = true; // wait until all threads process, then print reports while (process){ if(tr.getIsFinished()){ System.out.println("Print metrics"); process = false; } Thread.sleep(1000); } } } class ThreadRunner implements Runnable { static int timeOutTime = 2; private ExecutorService executorService = Executors.newFixedThreadPool(10); private final CyclicBarrier barrier; private boolean isFinished=false; public ThreadRunner(CyclicBarrier cb) { this.barrier = cb; } public void run(){ try { boolean stillLoop = true; int i = 0; while (stillLoop){ int size; Future<Integer> future = null; try { future = executorService.submit(new Reader()); // sleeps size = future.get(); } catch (InterruptedException | ExecutionException ex) { // handle Errs } if(i == 3){ stillLoop = false; this.barrier.await(); this.isFinished=true; } //System.out.println("i = "+i+" Size is: "+size+"\r"); i++; } } catch (InterruptedException | BrokenBarrierException e1) { e1.printStackTrace(); } } public boolean getIsFinished(){ return this.isFinished; } } class Reader implements Callable { private ExecutorService executorService = Executors.newFixedThreadPool(1); @Override public Object call() throws Exception { System.out.println("Reading..."); Thread.sleep(2000); executorService.submit(new Writer()); return 1000; } } class Writer implements Callable { @Override public Void call() throws Exception { Thread.sleep(4000); System.out.println("Wrote"); return null; } } Can anyone suggest a way to ONLY print "print metrics" after all threads have run?
-14067271 0Well it depends on your app and the connect, first your app must support background running. Then if the internet connection is GRPS, CDMA or EDGE your connection is dropped and NSURLConnection will receive an error if the connection is not reestablished with the time out period. On 3G and WiFi you can have data and voice at the same time. On LTE all data connection are dropped and the witches back to UMTS(3G) see comment by Codo
I want to hide my textbox-X in classic asp according to the date entered textbox-Y. textbox-X is in different asp page and textbox-Y in different page but both are contained in one base page default.asp i used the following condition and code to hide my textbox-Y, but in vein.
if (document.getElementById('txtAmount')) { alert("Inside first alert"); $("#txtPRAmount1").hide(); alert("Inside second alert"); } here first alert fires and but second alert doesnt. please help me
-14943596 0 Strange / unstable behaviour on CreatePivotTable()I am writing VBA code to automate some processes in Excel and I am encountering a very strange behavior for which I have not been able to find documentation / help.
I have a procedure MAJ_GF that first executes function GF.Update, checks the result, and then launches procedure GF.Build (which basically takes the data obtained by GF.Update from different worksheets and does a bunch of stuff with it).
At some point, this "bunch of stuff" requires using a pivot table, so GF.Build contains the following line:
Set pvt = ThisWorkbook.PivotCaches.Create(xlDatabase, _ "'source_GF'!R1C1:R" & j & "C" & k).CreatePivotTable("'TCD_GF'!R4C1", "GFTCD1") The strange behavior is this:
MAJ_GF, VBA properly executes GF.Update, then launches GF.Build, and stops at the line described above complaining "Bad argument or procedure call"GF.Update, then manually run GF.Build, everything goes smoothly and GF.Build does what it has to do from beginning to end with no errorsMAJ_GF then VBA pauses on the line as expected, and when I say "Continue"... it just continues smoothly and with no errors !I turned this around and around and around, double-checked the value of every variable, and this just makes no sense.
Ideas anybody?
-22552361 0 How to understand the `Net pruing` via complexity penaltyIn Chapter6.10.3 'Net pruning', page53 of An introduction to neural networks __ Kevin Gurney. It introduce the complexity penalty into the back-propagation training algorithm. The complexity penalty is like as follow:
$$ E_c=\sum_{i}w_i $$
$$ E = E_t + \lambda E_c $$
Et is error used so far based on input-output differences.
Then performing gradient descent on this total risk E.
My question : After doing derivation. The complexity penalty will dissapear. How can it affect the training
1) Option one reduce li font size if client is ok with it font-size: 0.75em;
This worked for me and you the search bar was fixed.
2) Second option is to trim the text length. There is only so much u can fit in those tight cells.
abt the news widget I don't see anything wrong.
-10308265 0You can create multiple encryption keys (millions) and use separate keys for separate columns. Adding multiple keys is critical for any scenario that requires periodic key rotation. To encrypt data you use ENCRYPTBYKEY and pass in the key name of the desired encryption key, see How to: Encrypt a Column of Data. You decrypt data using DECRYPTBYKEY. Note that you do not specify what decryption key to use, the engine knows. But you have to properly open the decryption key first, see OPEN SYMMETRIC KEY.
Your response is likely being treated as HTML by the browser, which collapses line breaks (among plenty of other things). If you want your file to be displayed as-is, set the parameter mimetype='text/plain' on your flask Response object before returning it:
return Response(content, mimetype='text/plain')
-34182439 0 It may help to note that comboPanel is a JPanel having the default FlowLayout, which centers components based on the preferred sizes of the comboboxes. As a result, they "clump" together in the middle. Some alternatives:
Specify a GridLayout having an extra column and use an empty component for the check column. The initial tableau will be aligned, although subsequent changes to the column widths will change that.
JPanel comboPanel = new JPanel(new GridLayout(0, annots.length + 1)); Add a combobox to each relevant header using the approach shown here, being mindful of the caveats adduced here.
I've been stuck on this for a while, I'm trying to figure out how to make a boolean have a 50% chance to be set to true after clicking a button and a 50% chance to keep it false.
Any help would be appreciated.
-22387777 0If you want all results where the Quantity is 20, then all you need to do is specify that in the WHERE clause:
SELECT * FROM Product WHERE Quantity = 20; There's no need to include the ORDER BY if you expect the value to be the same throughout. There's also no need to LIMIT unless you want the first number of results where Quantity is 20.
-23994234 0 How to terminate a server socket thread on timeout?I'm using Spring Integration on the server side to offer a socket. The socket as a defined soTimeout, so that exceeding that timeout will close the current open socket connection to the client.
TcpConnectionFactoryFactoryBean fact = new TcpConnectionFactoryFactoryBean(); fact.setSoTimeout(timeout); But the thread on the server side will continue. How can I force cancelation/termination of the server socket as well (maybe with an additional thread timeout, so that no thread can hang in the background by any issues)?
-14325496 0Just tried it here, and I can't duplicate your experience. I'm guessing you have an unexpected or inconsistent view/controller hierarchy? Look at the controller of the table and scroll views' common superview. Anything fishy there? Remember: view controllers manage sets of views. Container view controllers manage other view controllers and have special rules (see: The View Controller Programming Guide, esp. -addChildViewController:, etc.).
I'd suggest opening a blank project and trying to recreate the problem in its simplest possible form. If it's magically fixed, what's different? If it's still giving you trouble, send us a link so we can see the details of how you have things wired.
-26132836 0This is an issue with the simulator. On a device it'll work as expected.
-34087329 0 Categorical and ordinal feature data representation in regression analysis?I am trying to fully understand difference between categorical and ordinal data when doing regression analysis. For now, what is clear:
Categorical feature and data example:
Color: red, white, black
Why categorical: red < white < black is logically incorrect
Ordinal feature and data example:
Condition: old, renovated, new
Why ordinal: old < renovated < new is logically correct
Categorical-to-numeric and ordinal-to-numeric encoding methods:
One-Hot encoding for categorical data
Arbitrary numbers for ordinal data
Categorical data to numeric:
data = {'color': ['blue', 'green', 'green', 'red']} Numeric format after One-Hot encoding:
color_blue color_green color_red 0 1 0 0 1 0 1 0 2 0 1 0 3 0 0 1 Ordinal data to numeric:
data = {'con': ['old', 'new', 'new', 'renovated']} Numeric format after using mapping: Old < renovated < new → 0, 1, 2
0 0 1 2 2 2 3 1 In my data I have 'color' feature. As color changes from white to black price increases. From above mentioned rules I probably have to use one-hot encoding for categorical 'color' data. But why I cannot use ordinal representation. Below I provided my observations from where my question arised.
Let me start with introducing formula for linear regression:
Let have a look at data representations for color:
Let's predict price for 1-st and 2-nd item using formula for both data representations:
One-hot encoding: In this case different thetas for different colors will exist. I assume that thetas already derived from regression (20, 50 and 100). Prediction will be:
Price (1 item) = 0 + 20*1 + 50*0 + 100*0 = 20$ (thetas are assumed for example) Price (2 item) = 0 + 20*0 + 50*1 + 100*0 = 50$ Ordinal encoding for color: In this case all colors will have 1 common theta but my assigned multipliers (10, 20, 30) differ:
Price (1 item) = 0 + 20*10 = 200$ (theta assumed for example) Price (2 item) = 0 + 20*20 = 400$ (theta assumed for example) In my model White < Red < Black in prices. Seem to be that correlation works correctly and it is logical predictions in both cases. For ordinal and categorical representations. So I can use any encoding for my regression regardless of the data type (categorical or ordinal)? This division in data representations is just a matter of conventions and software-oriented representations rather than a matter of regression logic itself?
-14482392 0wrap your two commands in function so you will have just one call ?
function add-log{ (param $txt) $DateTime = get-date | select -expand datetime Add-Content $LogFile -Value "$DateTime: $txt" }
-31256206 0 C++ memory alignment So I read that when variables are declared in c++ if you want to get the optimum cache reads the memory should stick to its natural alignment. Example:
int a; // memory address should end in 0x0,0x4,0x8,0xC int b[2]; // 8 bytes 0x0,0x8 int b[4]; // 16 bytes 0x0 But in practice these variables do not follow the "natural alignment" rules, a 16 byte variable was residing at a memory address that ended in 0xC. Why is this ?
-38704327 0var questionID = $(this)[0].id
This worked for me!
-33082472 0 My timer increases speed after a single play through of my game why?I continue to get the error TypeError: Error #1009: Cannot access a property or method of a null object reference. at ChazS1127_win_loose_screen_fla::MainTimeline/updateTime() at flash.utils::Timer/_timerDispatch() at flash.utils::Timer/tick() and here is my code for my main game
stop(); import flash.events.MouseEvent; import flash.ui.Mouse; import flash.events.TimerEvent; import flash.utils.Timer; var timer:Timer = new Timer(1000, 9999); timer.addEventListener(TimerEvent.TIMER, updateTime); var timeRemaining = 30; timerBox.text = timeRemaining; function updateTime(evt:TimerEvent) { timeRemaining--; timerBox.text = timeRemaining; if(timeRemaining <= 0) { gotoAndStop(1, "Loose Screen"); } } addEventListener(MouseEvent.CLICK, onMouseClick); var score = 0 ; function onMouseClick(evt:MouseEvent) { if(evt.target.name == "playBtn") { texts.visible = false; playBtn.visible = false; backpackss.visible = false; backgrounds.visible = false; timer.start(); } if(evt.target.name == "Backpack") { Backpack.visible = false; message.text = "A backpack is a necessity for carrying all your items."; score = score + 1; scoredisplay.text = "score:" + score; 0 } if(evt.target.name == "Bandage") { Bandage.visible = false; message.text = "Bandages for cuts and scraps and to keep from bleeding out."; score = score + 1; scoredisplay.text = "score:" + score; } if(evt.target.name == "Brace") { Brace.visible = false; message.text = "A brace is good for a sprain or even a break in a bone allow you to keep going."; score = score + 1; scoredisplay.text = "score:" + score; } if(evt.target.name == "canned") { canned.visible = false; message.text = "Canned foods are a good resource as food will be scarce in situations."; score = score + 1; scoredisplay.text = "score:" + score; } if(evt.target.name == "Compass") { Compass.visible = false; message.text = "Going the wrong direction in a survival situation can be your downfall."; score = score + 1; scoredisplay.text = "score:" + score; } if(evt.target.name == "Flashlight") { Flashlight.visible = false; message.text = "A flashlight can help you see at night and help you stay sane."; score = score + 1; scoredisplay.text = "score:" + score; } if(evt.target.name == "Iodine") { Iodine.visible = false; message.text = "An ioddine purfication kit can assist in keeping water clean for drinking."; score = score + 1; scoredisplay.text = "score:" + score; } if(evt.target.name == "Lighter") { Lighter.visible = false; message.text = "A windproof lighter for even the windest of days to light fires."; score = score + 1; scoredisplay.text = "score:" + score; } if(evt.target.name == "Radio") { Radio.visible = false; message.text = "A radio to help keep up to date on news around if it's still brodcasting."; score = score + 1; scoredisplay.text = "score:" + score; } if(evt.target.name == "Sewing") { Sewing.visible = false; message.text = "A sewing kit for salvaging clothes and for patching up wounds."; score = score + 1; scoredisplay.text = "score:" + score; } if(evt.target.name == "Tent") { Tent.visible = false; message.text = "A tent can be a home for the night and a home for life."; score = score + 1; scoredisplay.text = "score:" + score; } if(score >= 11) { gotoAndStop(1, "Victory Screen"); } } function removeAllEvents() { removeEventListener(MouseEvent.CLICK, onMouseClick); timer.removeEventListener(TimerEvent.TIMER, updateTime); timer.stop(); } and my Victory Screen
stop(); import flash.events.MouseEvent; addEventListener(MouseEvent.CLICK, onMouseClick2); play(); function onMouseClick2(evt:MouseEvent) { if(evt.target.name == "restartButton") { gotoAndStop(1, "Main Game"); removeAllEvents2(); } } function removeAllEvents2() { removeEventListener(MouseEvent.CLICK, onMouseClick2); } and my loose screen
stop(); import flash.events.MouseEvent; play(); addEventListener(MouseEvent.CLICK, onMouseClick2); function onMouseClick3(evt:MouseEvent) { if(evt.target.name == "restartButton") { gotoAndStop(1, "Main Game"); removeAllEvents3(); } } function removeAllEvents3() { removeEventListener(MouseEvent.CLICK, onMouseClick3); } so why does my game when through one play the timer will speed up and go fast for no reason. After one play through it'll go 2 seconds for every 1 second and so on.
-23340283 0Are you meaning that you want the text values of all checked checkboxes, or the text value of every checkbox, or...?
Either way, you want to iterate through the Page's Controls collection to find all controls that have a type of Checkbox and then use that to get their text values (and you can limit whether you want to include checked boxes or not in that iteration). And, yes, using a List might be easier than starting with an array, because you can easily add to a List<> and then transform it into an array with little pain.
-12721334 0 How to set all pages of a subdomain to redirect to a single page?Let's say my domain name is website123.com and I have a subdomain of my.website123.com
I've deleted the "my" subdomain from the site and want to make sure that anyone that goes to any page with a my.website123.com URL is redirected to the main www.website123.com URL. The "my" subdomain has a ton of pages of it, so I need to make sure that regardless of which page a user goes to on the "my" subdomain, that they're redirected to the site's main index page.
I was thinking to get this accomplished through .htaccess - is that the best way? If yes how?
-21862704 0It sounds like you want to use something like VVDocumenter.
From their Github page:
-19250774 0Writing document is so important for developing, but it is really painful with Xcode. Think about how much time you are wasting in pressing '*' or '/', and typing the parameters again and again. Now, you can find the method (or any code) you want to document to, and type in ///, the document will be generated for you and all params and return will be extracted into a Javadoc style, which is compatible with appledoc, Doxygen and HeaderDoc. You can just fill the inline placeholder tokens to finish your document.
Have you considered using the Server.Transfer to redirect the query to the required url?
Simply use
Server.Transfer("Page2.aspx", true);
-33469734 0 The format file is describing the source data not the destination. When you use -c or datafiletype='char' your input datatypes must be SQLCHAR. Native datatypes are only valid when using -n or datafiletype='native'. A source file in native format is always binary so bcp needs to know the data type of each field in order to read the correct amount of bytes and interpret them correctly.
Be careful about assuming that int operations are always faster than float operations. In isolation they may be, but moving data between a float register and an int register is shockingly slow on modern processors. So once your data is on a float, you should keep it on a float for further computation.
-36602474 0 LINQ to JSON - Query for object or an arrayI'm trying to get a list of SEDOL's & ADP values. Below is my json text:
{ "DataFeed" : { "@FeedName" : "AdminData", "Issuer" : [{ "id" : "1528", "name" : "ZYZ.A a Test Company", "clientCode" : "ZYZ.A", "securities" : { "Security" : { "id" : "1537", "sedol" : "SEDOL111", "coverage" : { "Coverage" : [{ "analyst" : { "@id" : "164", "@clientCode" : "SJ", "@firstName" : "Steve", "@lastName" : "Jobs", "@rank" : "1" } }, { "analyst" : { "@id" : "261", "@clientCode" : "BG", "@firstName" : "Bill", "@lastName" : "Gates", "@rank" : "2" } } ] }, "customFields" : { "customField" : [{ "@name" : "ADP Security Code", "@type" : "Textbox", "values" : { "value" : "ADPSC1111" } }, { "@name" : "Top 10 - Select one or many", "@type" : "Dropdown, multiple choice", "values" : { "value" : ["Large Cap", "Cdn Small Cap", "Income"] } } ] } } } }, { "id" : "1519", "name" : "ZVV Test", "clientCode" : "ZVV=US", "securities" : { "Security" : [{ "id" : "1522", "sedol" : "SEDOL112", "coverage" : { "Coverage" : { "analyst" : { "@id" : "79", "@clientCode" : "MJ", "@firstName" : "Michael", "@lastName" : "Jordan", "@rank" : "1" } } }, "customFields" : { "customField" : [{ "@name" : "ADP Security Code", "@type" : "Textbox", "values" : { "value" : "ADPS1133" } }, { "@name" : "Top 10 - Select one or many", "@type" : "Dropdown, multiple choice", "values" : { "value" : ["Large Cap", "Cdn Small Cap", "Income"] } } ] } }, { "id" : "1542", "sedol" : "SEDOL112", "customFields" : { "customField" : [{ "@name" : "ADP Security Code", "@type" : "Textbox", "values" : { "value" : "ADPS1133" } }, { "@name" : "Top 10 - Select one or many", "@type" : "Dropdown, multiple choice", "values" : { "value" : ["Large Cap", "Cdn Small Cap", "Income"] } } ] } } ] } } ] } } Here's the code that I have so far:
var compInfo = feed["DataFeed"]["Issuer"] .Select(p => new { Id = p["id"], CompName = p["name"], SEDOL = p["securities"]["Security"].OfType<JArray>() ? p["securities"]["Security"][0]["sedol"] : p["securities"]["Security"]["sedol"] ADP = p["securities"]["Security"].OfType<JArray>() ? p["securities"]["Security"][0]["customFields"]["customField"][0]["values"]["value"] : p["securities"]["Security"]["customFields"]["customField"][0]["values"]["value"] }); The error I get is:
Accessed JArray values with invalid key value: "sedol". Int32 array index expected
I think I'm really close to figuring this out. What should I do to fix the code? If there is an alternative to get the SEDOL and ADP value, please do let me know?
[UPDATE1] I've started working with dynamic ExpandoObject. Here's the code that I've used so far:
dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(json, new ExpandoObjectConverter()); foreach (dynamic element in obj) { Console.WriteLine(element.DataFeed.Issuer[0].id); Console.WriteLine(element.DataFeed.Issuer[0].securities.Security.sedol); Console.ReadLine(); } But I'm now getting the error 'ExpandoObject' does not contain a definition for 'DataFeed' and no extension method 'DataFeed' accepting a first argument of type 'ExpandoObject' could be found. NOTE: I understand that this json text is malformed. One instance has an array & the other is an object. I want the code to be agile enough to handle both instances.
[UPDATE2] Thanks to @dbc for helping me with my code so far. I've updated the json text above to closely match my current environment. I'm now able to get the SEDOLs & ADP codes. However, when I'm trying to get the 1st analyst, my code only works on objects and produces nulls for the analysts that are part of an array. Here's my current code:
var compInfo = from issuer in feed.SelectTokens("DataFeed.Issuer").SelectMany(i => i.ObjectsOrSelf()) let security = issuer.SelectTokens("securities.Security").SelectMany(s => s.ObjectsOrSelf()).FirstOrDefault() where security != null select new { Id = (string)issuer["id"], // Change to (string)issuer["id"] if id is not necessarily numeric. CompName = (string)issuer["name"], SEDOL = (string)security["sedol"], ADP = security["customFields"] .DescendantsAndSelf() .OfType<JObject>() .Where(o => (string)o["@name"] == "ADP Security Code") .Select(o => (string)o.SelectToken("values.value")) .FirstOrDefault(), Analyst = security["coverage"] .DescendantsAndSelf() .OfType<JObject>() .Select(jo => (string)jo.SelectToken("Coverage.analyst.@lastName")) .FirstOrDefault(), }; What do I need to change to always select the 1st analyst?
-8656409 0 mongodb map-reduce output doublesmy source database have documents like..
{date:14, month:1, year:2011, name:"abc", item:"A"} {date:14, month:1, year:2011, name:"abc", item:"B"} {date:14, month:1, year:2011, name:"def", item:"A"} {date:14, month:1, year:2011, name:"def", item:"B"} {date:15, month:1, year:2011, name:"abc", item:"A"} {date:16, month:1, year:2011, name:"abc", item:"A"} {date:15, month:1, year:2011, name:"def", item:"A"} {date:16, month:1, year:2011, name:"def", item:"A"} and my map reduce is like...
var m = function(){ emit({name:this.name, date:this.date, month:this.month, year:this.year}, {count:1}) } var r = function(key, values) { var total_count = 0; values.forEach(function(doc) { total_count += doc.count; }); return {count:total_count}; }; var res = db.source.mapReduce(m, r, { out : { "merge" : "bb_import_trend" } } ); so "myoutput" collection will have counts like this....
{ "_id" : { date : 14, month : 1, year : 2011, name : "abc" }, "_value" : { "count" : 2 } }, { "_id" : { date : 14, month : 1, year : 2011, name : "def" }, "_value" : { "count" : 2 } }, { "_id" : { date : 15, month : 1, year : 2011, name : "abc" }, "_value" : { "count" : 1 } }, { "_id" : { date : 15, month : 1, year : 2011, name : "def" }, "_value" : { "count" : 1 } }, { "_id" : { date : 16, month : 1, year : 2011, name : "abc" }, "_value" : { "count" : 1 } }, { "_id" : { date : 16, month : 1, year : 2011, name : "def" }, "_value" : { "count" : 1 } } so total 6 documents
so when aother three documents of date 17 like...
{date:17, month:1, year:2011, name:"abc", item:"A"} {date:17, month:1, year:2011, name:"abc", item:"B"} {date:17, month:1, year:2011, name:"def", item:"A"} has been added to my source collection...and again i am running map-reduce it should be jus addition of two documents like...
previous 6 plus
... { "_id" : { date : 17, month : 1, year : 2011, name : "abc" }, "_value" : { "count" : 2 } }, { "_id" : { date : 17, month : 1, year : 2011, name : "def" }, "_value" : { "count" : 1 } } but instead of this it duplicates all the previous 6 documents and adds another 2 new ones..so total of 14 documents in my output collection(though i 've used merge in output).
Note > : when i am using another database having same source collection and doing the same procedure it gives me desired output(of only 8 collection).but my database using by my gui is still duplicating the old ones.
-40975592 0If you are going to use PHP (*nix/Windows) then you are looking for the PHP dio (Direct I/O) extension: http://php.net/manual/en/book.dio.php
From PHP manual:
-770179 0 PHP / Curl: HEAD Request takes a long time on some sitesPHP supports the direct io functions as described in the Posix Standard (Section 6) for performing I/O functions at a lower level than the C-Language stream I/O functions (fopen(), fread(),..). The use of the DIO functions should be considered only when direct control of a device is needed. In all other cases, the standard filesystem functions are more than adequate.
I have simple code that does a head request for a URL and then prints the response headers. I've noticed that on some sites, this can take a long time to complete.
For example, requesting http://www.arstechnica.com takes about two minutes. I've tried the same request using another web site that does the same basic task, and it comes back immediately. So there must be something I have set incorrectly that's causing this delay.
Here's the code I have:
$ch = curl_init(); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 20); curl_setopt ($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // Only calling the head curl_setopt($ch, CURLOPT_HEADER, true); // header will be at output curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // HTTP request is 'HEAD' $content = curl_exec ($ch); curl_close ($ch); Here's a link to the web site that does the same function: http://www.seoconsultants.com/tools/headers.asp
The code above, at least on my server, takes two minutes to retrieve www.arstechnica.com, but the service at the link above returns it right away.
What am I missing?
-16599422 0 Cannot create new project - There must not already be a project at this locationI am trying to start using the just released Android Studio, I have already established the location for the Android SDK, and the Studio opens correctly.
Now, I want to create a new application project, but I cannot figure out what to select as project location.
Steps followed:
I read a similar question, and I am making sure, as you can tell by the steps I followed, that I am entering the path at the very end, and it still won't work for me.
I really think there must be a silly thing I am missing here, not sure what it may be though.
Any ideas?
-15528355 0initialize the jlabels and textareas before adding them
I have a webgrid
@{ var gdAdminGroup = new WebGrid(source: Model, rowsPerPage: 20, ajaxUpdateContainerId: "tdUserAdminGroup"); } @gdAdminGroup.GetHtml( htmlAttributes: new { id = "tdUserAdminGroup" }, tableStyle: "gd", headerStyle: "gdhead", rowStyle: "gdrow", alternatingRowStyle: "gdalt", columns: gdAdminGroup.Columns( gdAdminGroup.Column(columnName: "Description", header: "Admin Group"), gdAdminGroup.Column(header: "", format: @<text><input name="chkUserAdminGroup" type="checkbox" value="@item.AdminGroupID" @(item.HasAdminGroup == 0? null : "checked") /></text>) ) ) If I check some checkboxs and goes to the second page, the selection on the first page will be lost. Can anyone help me with this? Thank you
-25670049 0 Changing checkbox attributes for multiple rows with single checkboxGood Morning,
Im working on a larger project but i tried to do a simple page in order to check my work. php/mysql newb here. Sorry! :)
What im trying to accomplish is ultimately having a single user page shown with rows of tasks from a table and a single check mark in order to say if the user has completed the task or not by checking or unchecking the box.
For testing purposes, I have set up a table with rows labled testid, testdata and testcheck. The testid a INT(2)AutoIncrement and Primary and Unique, testdata is a VARCHAR(30) and testcheck is a TINYINT(1). The auto increment isnt really important because I manually populated all the rows. I have 5 rows (for the array sake) consisting of 1-5 testid, "testdata1-5" for testdata and either a 0 or a 1 for testcheck. The table is functioning fine and the database can be queried.
Here is the code for the php start page:
<html> <?php include_once('init.php'); $query = mysql_query("SELECT testid, testdata, testcheck FROM testtable"); ?> <h1>Test form for checkmarks</h1> <form method="POST" action="testover.php"> <table border="1"> <tr> <td> Test ID </td> <td> Test Data </td> <td> Checked </td> <td> Test Check </td> </tr> <?php while ( $row = mysql_fetch_assoc($query)) { ?> <tr> <td> <?php echo $row['testid']; ?> </td> <td> <?php echo $row['testdata']; ?> </td> <td> <center><input type="checkbox" name="<?php $row['testid'] ?>" value="<?php $row['testcheck']; ?>" <?php if($row['testcheck']=='1'){echo 'checked';} ?>></center> </td> <td> <center><?php echo $row['testcheck']; ?></center> </td> </tr> <?php } ?> </table> <input type="submit" name="confirm" value="Confirm Details"> <a href="testcheck.php"><input type="button" value="Home"></a> </form> </html> Ive been going back and forth trying to use an array for the inputs name (name="something[]") or the "isset" parameter but that is where my knowledge is failing. Ive read countless articles both here and on other websites and I cant seem to find the right code to use. Most sites have rows with multiple check boxes or a different layout of their table.
I posted here to hopefully be pointed in some direction as to how to update the DB with these values of the check marks.
-5355071 0It looks like the EWMH properties _NET_CURRENT_DESKTOP and _NET_DESKTOP_NAMES are what you're looking for. With Xlib, you'd use the XGetWindowProperty function.
Are there any negative impacts when a single user application uses only one IB transaction, which is active as long the program runs? By using only CommitRetaining and RollbackRetaining.
Background: I want to use IBQuery(s) and connect them to a DB Grid(s) (DevExpress), which loads all records into memory at once. So I want to avoid re-fetching all data after every SQL insert command. IBTransaction.Commit would close the dataset.
-7457885 0All of the answers you've gotten so far are overly complicated and/or slightly misleading.
In the first construction/initialization:
T a(10); The very obvious thing happens. The second construction/initialization is more interesting:
T aa = 10; This is equivalent to:
T aa(T(10)); Meaning that you create a temporary object of type T, and then construct aa as a copy of this temporary. This means that the copy constructor is called.
C++ has a default copy constructor that it creates for a class when you have none explicitly declared. So even though the first version of class T has no copy constructor declared, there still is one. The one the compiler declares has this signature T(const T &).
Now in your second case where you declare something that looks like a copy constructor, you make the argument a T &, not a const T &. This means that the compiler, when trying to compile the second expression, tries to use your copy constructor, and it can't. It's complaining that the copy constructor you declared requires a non-const argument, and the argument it's being given is const. So it fails.
The other rule is that after the compiler has converted your initialization to T aa(T(10)); it is then allowed to transform it to T aa(10);. This is called 'copy elision'. The compiler is allowed, in certain circumstances, to skip calls to the copy constructor. But it may only do this after it verifies that the expression is correctly formed and doesn't generate any compiler errors when the copy constructor call is still there. So this is an optimization step that may affect exactly which parts of a program run, but cannot affect which programs are valid and which ones are in error (at least from the standpoint of whether or not they compile).
Check out Array#map.
ids = [ 123, 456 ] connections = ids.map do |id| @graph.get_connections("#{ id }","?fields=posts") end
-11035849 0 You can use the Insert transformation:
<resizer> <plugins> <add name="AzureReader" connectionString="DataConnectionString" xdt:Transform="Insert" /> </plugins> </resizer> Web.config Transformation Syntax for Web Application Project Deployment
-12832239 0 MS Identity and Access Tool MVC 4This VS 2012 extension is meant to allow me to add a local Development STS to my MVC application http://visualstudiogallery.msdn.microsoft.com/e21bf653-dfe1-4d81-b3d3-795cb104066e
I follow the very simple instructions e.g. Right Click the project name and select Identity and Access in the menu. Select your Identity Provider and the OK to apply the settings to your web.config.
I run my MVC 4 application and it redirects immediately to login.aspx
I'm guessing there are special instructions for MVC 4.
What are they?
Where do I find them?
EDIT
To be clear I have created a ASP.MVC 4 Internet application in visual studio 2012. Then I am using the Identity & Access Tool to add a local development STS to Test my application.
I am running the site on a local IIS Express
When I debug the application I am redirected to
localhost:11378/login.aspx?ReturnUrl=%2f
This occurs even if I remove forms authentication as suggested in advice already given.
-33843526 0Sure! My existdb version is 2.2.
xquery version "3.0"; declare boundary-space preserve; declare namespace exist = "http://exist.sourceforge.net/NS/exist"; declare namespace request="http://exist-db.org/xquery/request"; declare namespace xmldb="http://exist-db.org/xquery/xmldb"; declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization"; declare option output:method "text"; declare option output:indent "yes"; import module namespace file="http://exist-db.org/xquery/file"; let $log-in := xmldb:login("/db", "admin", "admin") for $k in (35,36,37) let $AppletName := fn:doc(fn:concat('/db/project/AppletA_',$k,'.xml'))//APPLET/@NAME/string() let $collection := fn:concat('xmldb:exist:/db/project/Scripts_',$k) let $node :=(<APPLET_SCRIPTS>{ for $i in fn:doc(fn:concat('/db/project/AppletA_',$k,'.xml'))//APPLET_SERVER_SCRIPT let $MethodName := $i/@NAME let $MethodScript := string($i/@SCRIPT) let $file-name := fn:concat($MethodName,'.js') let $store := xmldb:store($collection,$file-name, $MethodScript) return <div>{$MethodScript}</div> }</APPLET_SCRIPTS>) return $node A fragment of xml is:
The content of file created is this one line string:
function Prova() { try { var sVal = TheApplication().InvokeMethod("LookupValue","FS_ACTIVITY_CLASS","CIM_FAC18"); var recordFound = searchRecord(sVal); if(!recordFound) { this.InvokeMethod("NewRecordCustom"); this.BusComp().SetFieldValue("Class",sVal); this.BusComp().WriteRecord(); } } catch(e) { throw(e); } finally { sVal = null; } }
-4704472 0 How to set alarm in qt mobility applicationIs it possible to set an alarm for a specific time in Qt?
-5597109 0I have an app that does something similar - we use Open ID and OAuth exclusively for logins, and while we store the user's email address (Google Account or Facebook sends it back during authentication) they never login using it and so don't have/need a password.
This is a callback for what happens when a user signs up via Facebook:
User.create!( :facebook_id => access_token['uid'], :email => data["email"], :name => data["name"], :password => Devise.friendly_token[0,20]) The Devise.friendly_token[...] just generates a random 20 character password for the user, and we are using our default User model with devise just fine. Just setting the password in a similar way on your users would be my approach, since you are never going to use their password. Also, if you ever change your mind and want them to be able to login, you can just change a user's password in the database and build a login form, and devise will take care of the rest.
you'll probably find it easier to query sizes if you work with the gtable,
--- title: "Untitled" header-includes: - \usepackage{lipsum} output: pdf_document: fig_caption: yes fig_crop: no keep_tex: yes geometry: width=5in --- ```{r setup, include=FALSE} library(ggplot2) library(dplyr) library(grid) library(knitr) general_fig_width <- 5 ``` ```{r plot, fig.show=FALSE} p <- diamonds %>% sample_frac(0.3) %>% ggplot(aes(x = carat, y = price, color = price)) + geom_point() + theme_dark() + theme(plot.margin = unit(c(0,0,0,0), "pt")) g <- ggplotGrob(p) if(getRversion() < "3.3.0"){ g$widths <- grid:::unit.list(g$widths) g$widths[4] <- list(unit(general_fig_width, "in")) } else { g$widths[4] <- unit(general_fig_width, "in") } fig_width <- convertWidth(sum(g$widths), "in", valueOnly = TRUE) left_width <- convertWidth(sum(g$widths[1:3]), "in", valueOnly = TRUE) ggsave('plot-tmp.pdf', width=fig_width, height=2) ``` \begin{figure}[!hb] \hspace{`r -left_width`in}\includegraphics[width=`r fig_width`in]{plot-tmp} \end{figure} \lipsum[2]
-16016720 0 It depends for what you want to do with the Acess Token.
If you want an acess token to access an user data. You can use the "setExtendedAccessToken" method, how the luschn said in his answer.
But, if you want an acess token to access some public information, like an a feed from a public group, or a page. So you can uses an App Access Token. Which you gets here https://developers.facebook.com/tools/access_token/
-3465330 0Another answer assuming IEEE float:
int get_bit_index(uint64_t val) { union { float f; uint32_t i; } u = { val }; return (u.i>>23)-127; } It works as specified for the input values you asked for (exactly 1 bit set) and also has useful behavior for other values (try to figure out exactly what that behavior is). No idea if it's fast or slow; that probably depends on your machine and compiler.
-33876999 0 Click doesn't work on this Google Translate button?I am creating an Tampermonkey userscript that would automatically click the "star" button on Google Translate website and save my searches so that I can later view them and rehearse.
This is the button that I am targeting: 
This is what I've got so far:
// @match https://translate.google.com/#en/de/appetit/ var el = document.getElementById("gt-pb-star"); setTimeout(function(){ el.click(); },4000); I encountered 2 problems.
@match should be every translate.google.com search and not just appetit. How do I specify the whole domain?Can you please help me finish this userscript?
Edit: it seems that setting match to https://translate.google.com/ handles the first question. Still don't know why click() doesn't work.
This is a design principle question for classes dealing with mathematical/physical equations where the user is allowed to set any parameter upon which the remaining are being calculated. In this example I would like to be able to let the frequency be set as well while avoiding circular dependencies.
For example:
from traits.api import HasTraits, Float, Property from scipy.constants import c, h class Photon(HasTraits): wavelength = Float # would like to do Property, but that would be circular? frequency = Property(depends_on = 'wavelength') energy = Property(depends_on = ['wavelength, frequency']) def _get_frequency(self): return c/self.wavelength def _get_energy(self): return h*self.frequency I'm also aware of an update trigger timing problem here, because I don't know the sequence the updates will be triggered:
(The answer to be accepted should also address this potential timing problem.)
So, what' the best design pattern to get around these inter-dependent problems? At the end I want the user to be able to update either wavelength or frequency and frequency/wavelength and energy shall be updated accordingly.
This kind of problems of course do arise in basically all classes that try to deal with equations.
Let the competition begin! ;)
-11233777 0I've got a functional solution using option #1, but it's such a hack I can't bear to post it publicly. Basically, in serializeData I'm reaching into the model and modifying _relations before and after a call to toJSON. Not thread safe and ugly as heck. Hoping to come back soon and find a proper solution.
-6239807 0It sounds like you want to compare a short term (5-day) moving average to a longer-term moving average (e.g., something like 90 days).
As a refinement, you might want to do a least-squares linear regression over the longer term, and then compare the shorter term average to the projection you get from that.
-40104926 0 Javascript - Does not save into database when i change value in javascript sideMy code looks like this:
document.getElementById("medewerkers").value = mdwString; document.getElementById("medewerkersomschr").value = mdwNaam; $("#medewerkers").val(mdwString); $("#medewerkersomschr").val(mdwNaam); document.getElementById("machines").value = mchString; document.getElementById("machinesomschr").value = mchNaam; $("#machines").val(mchString); $("#machinesomschr").val(mchNaam); As u can see i tried two ways to get a value into fields.
This does work for me, but next up when i try to save the values into the database it goes wrong. It looks like the view got updated but not the value of the html itself. Does anyone have an idea what i am doing wrong or what i should change up?
-4368012 0Look into joins for selecting data from multiple tables:
SELECT * FROM Prices LEFT JOIN (Vendors, Products) ON (Products.product_id=Prices.product_id AND Vendors.vendor_id=Prices.vendor_id)
-13195822 0 You could take a dictionary but make sure that you prevent duplicate key insertion. Keys of dictionary would serve as the unique numbers you need
-34461270 0Don't bother with splicing the array, just create a new one:
var newArray = []; $('#clearChecked').click(function() { $('#keyWords > input').each( function (n, obj) { if ($(obj).is(':checked')) { newArray.push($(obj).val()); } } }); localArray = newArray;
-11900714 0 On the blog page you can use:
{% for post in site.posts %} … {% endfor %} To retrieve all posts and show them all. If you want to filter more (say, you have a third category you wouldn't want to show on this page:
{% for post in site.posts %} {% if post.categories contains 'post' or post.categories contains 'photos' %} ... {% endif %} {% endfor %}
-36595895 0 This should work (though not recommended)
^(55[0-5]|5[0-4][0-9]|[1-4][0-9][0-9]|[1-9][0-9]|[5-9])$
-1657811 0 Subscriptions in the iPhone SDK really are to get around the fact that you cannot sell virtual credits, therefore what you can do is sell a subscription and make the digital content free from within your application assuming the user has a subscription to your service, you are correct in that you have to handle the majority of the logic yourself
-23474010 0 Java: How to copy automatically a file each time one is generated in a folder?I am asking for a Java code.
An ERP generates XML files in a folder, and each one has a different name.
For data extraction, I need to:
If new file is generated:
Copy file from the main folder to a secondary folder
Rename this file under "temp"
Extract data with an ETL (Talend) from "temp"
Delete the file "temp"
My question is: How to capture automaticaly a file with Java in order to copy or rename it each time one is generated?
Thanks
-36922012 0Okay, I think my issue was forgetting how multinomial regression works. The prediction formula for multinomial regression is
So you need a set of coefficients for every class.
-8773966 0The readlines() method of a file object returns a list of the lines of the file including the newline characters. Your checks compare with strings not including newline characters, so they always fail.
One way of getting rid of the newline characters is
lines = (line.strip() for line in open("out2.txt")) (Note that you don't need readlines() -- you can directly iterate over the file object itself.)
Literal bytes, shorts, integers and longs starting with 0 are interpreted as being octal
The integral types (byte, short, int, and long) can be expressed using decimal, octal, or hexadecimal number systems. Decimal is the number system you already use every day; it's based on 10 digits, numbered 0 through 9. The octal number system is base 8, consisting of the digits 0 through 7. The hexadecimal system is base 16, whose digits are the numbers 0 through 9 and the letters A through F. For general-purpose programming, the decimal system is likely to be the only number system you'll ever use. However, if you need octal or hexadecimal, the following example shows the correct syntax. The prefix 0 indicates octal, whereas 0x indicates hexadecimal.
from Primitive Data Types
-36421576 0 In import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener; SimpleImageLoadingLIstneer is not foundI am learning android and new to android. I want to pick multiple images from gallery and then want to show them in gridview and for that i am using UniversalImageLoader library 1.9.5
To Use UniversalImageLoader Library i added the following dependency in build.gradle app module
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5' and then i copied and pasted the solution from some tutorial
In This my mainactivity is like following in which i used universal image loader library
package tainning.infotech.lovely.selectmultipleimagesfromgallery; import java.util.ArrayList; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.os.Bundle; import android.provider.MediaStore; import android.util.Log; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.Toast; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.GridView; import android.widget.ImageView; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener; /** * @author Paresh Mayani (@pareshmayani) */ public class MainActivity extends BaseActivity { private ArrayList<String> imageUrls; private DisplayImageOptions options; private ImageAdapter imageAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.content_main); final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID }; final String orderBy = MediaStore.Images.Media.DATE_TAKEN; Cursor imagecursor = managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy + " DESC"); this.imageUrls = new ArrayList<String>(); for (int i = 0; i < imagecursor.getCount(); i++) { imagecursor.moveToPosition(i); int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA); imageUrls.add(imagecursor.getString(dataColumnIndex)); System.out.println("=====> Array path => "+imageUrls.get(i)); } options = new DisplayImageOptions.Builder() .showStubImage(R.drawable.stub_image) .showImageForEmptyUri(R.drawable.image_for_empty_url) .cacheInMemory() .cacheOnDisc() .build(); imageAdapter = new ImageAdapter(this, imageUrls); GridView gridView = (GridView) findViewById(R.id.gridview); gridView.setAdapter(imageAdapter); /*gridView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { startImageGalleryActivity(position); } });*/ } @Override protected void onStop() { imageLoader.stop(); super.onStop(); } public void btnChoosePhotosClick(View v){ ArrayList<String> selectedItems = imageAdapter.getCheckedItems(); Toast.makeText(MainActivity.this, "Total photos selected: "+selectedItems.size(), Toast.LENGTH_SHORT).show(); Log.d(MainActivity.class.getSimpleName(), "Selected Items: " + selectedItems.toString()); } /*private void startImageGalleryActivity(int position) { Intent intent = new Intent(this, ImagePagerActivity.class); intent.putExtra(Extra.IMAGES, imageUrls); intent.putExtra(Extra.IMAGE_POSITION, position); startActivity(intent); }*/ public class ImageAdapter extends BaseAdapter { ArrayList<String> mList; LayoutInflater mInflater; Context mContext; SparseBooleanArray mSparseBooleanArray; public ImageAdapter(Context context, ArrayList<String> imageList) { // TODO Auto-generated constructor stub mContext = context; mInflater = LayoutInflater.from(mContext); mSparseBooleanArray = new SparseBooleanArray(); mList = new ArrayList<String>(); this.mList = imageList; } public ArrayList<String> getCheckedItems() { ArrayList<String> mTempArry = new ArrayList<String>(); for(int i=0;i<mList.size();i++) { if(mSparseBooleanArray.get(i)) { mTempArry.add(mList.get(i)); } } return mTempArry; } @Override public int getCount() { return imageUrls.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView == null) { convertView = mInflater.inflate(R.layout.row_multiphoto_item, null); } CheckBox mCheckBox = (CheckBox) convertView.findViewById(R.id.checkBox1); final ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView1); imageLoader.displayImage("file://"+imageUrls.get(position), imageView, options, new SimpleImageLoadingListener() { @Override public void onLoadingComplete(Bitmap loadedImage) { Animation anim = AnimationUtils.loadAnimation(MainActivity.this,Animation.START_ON_FIRST_FRAME); imageView.setAnimation(anim); anim.start(); } }); mCheckBox.setTag(position); mCheckBox.setChecked(mSparseBooleanArray.get(position)); mCheckBox.setOnCheckedChangeListener(mCheckedChangeListener); return convertView; } OnCheckedChangeListener mCheckedChangeListener = new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub mSparseBooleanArray.put((Integer) buttonView.getTag(), isChecked); } }; } } but when i try to build the project it shows me the error following error Error:(26, 53) error: cannot find symbol class SimpleImageLoadingListener and also in following import statement import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener; SimpleImageLoadingListener is underlined as red line. and it says cannot find symbol SimpleImageLoadingListener . The BaseActivity.java is following import android.app.Activity; import com.nostra13.universalimageloader.core.ImageLoader; /** * @author Paresh Mayani (@pareshmayani) */ public abstract class BaseActivity extends Activity { protected ImageLoader imageLoader = ImageLoader.getInstance(); } The UilApplication.java is like following package tainning.infotech.lovely.selectmultipleimagesfromgallery; /** * Created by student on 4/5/2016. */ import android.app.Application; import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; /** * @author Paresh Mayani (@pareshmayani) */ public class UILApplication extends Application { @Override public void onCreate() { super.onCreate(); // This configuration tuning is custom. You can tune every option, you may tune some of them, // or you can create default configuration by // ImageLoaderConfiguration.createDefault(this); // method. ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext()) .threadPoolSize(3) .threadPriority(Thread.NORM_PRIORITY - 2) .memoryCacheSize(1500000) // 1.5 Mb .denyCacheImageMultipleSizesInMemory() .discCacheFileNameGenerator(new Md5FileNameGenerator()) //.enableLogging() // Not necessary in common .build(); // Initialize ImageLoader with configuration. ImageLoader.getInstance().init(config); } } The manifest file is this <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="tainning.infotech.lovely.selectmultipleimagesfromgallery" > <!-- Include following permission if you load images from Internet --> <uses-permission android:name="android.permission.INTERNET" /> <!-- Include following permission if you want to cache images on SD card --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" android:theme="@style/AppTheme.NoActionBar" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Build.gradle(Module:app) is like this apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.2" defaultConfig { applicationId "tainning.infotech.lovely.selectmultipleimagesfromgallery" minSdkVersion 15 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.1.1' compile 'com.android.support:design:23.1.1' compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5' } Kindly help as soon as possible. I searched for the solution of above problem but was not able to find any. I searched as much i can but didn't get the solution.
Thanks in advance
-10060450 0 RedirectToAction returns to calling Action Inside my Index action I call my NotFound Action. I follow in debug and the if condition tests true, it goes to the "return RedirectToAction("NotFound");" statement, it then goes to Dispose and then returns to the Index Action not the NotFound Action. If I Redirect to the Details Action it works fine. These are all in the same controller. The NotFound View just contains text.
if (condition tests true) { return RedirectToAction("NotFound"); } public ActionResult NotFound() { return View(); } I've also tried the NotFound as a ViewResult. It still fails.
-21239182 0In MapReduce, have the first line of your mapper parse the line it is reading. You can do this with custom parsing logic, or you can leverage pre-built code (in this case, a CSV library).
protected void map(LongWritable key, Text value, Context context) throws IOException { String line = value.toString(); CSVParser parser = new au.com.bytecode.opencsv.CSVParser.CSVParser(); try { parser.parseLine(line); // do your other stuff } catch (Exception e) { // the line was not comma delimited, do nothing } }
-38747747 0 Try this code :
YourViewControllerClass *viewController = [[UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil] instantiateViewControllerWithIdentifier:@"ViewController"]; // instanciate your viewcontroller [(UINavigationController *)[self sideMenuController].rootViewController pushViewController:viewController animated:YES]; //push your viewcontroller [[self sideMenuController] hideRightViewAnimated:YES completionHandler:nil]; //hide the menu
-1316659 0 BLOB data to simple string in DataGridView? I am using C# & MYSQL to develop a desktop application.
In one of my form I have a DataGridView (dgvBookings) and in my database table I have a table tblBookings which contains a field specialization of type BLOB.
I am selecting data with following query,
SELECT * FROM tblBookings WHERE IsActive=1; and then binding the data with DataGridView as,
dgvBookings.DataSource = ds.Tables["allbookings"]; BUT after binding the data in gridview it shows Byte[] Array value for all rows of column specialization which is of BLOB type.
How yo solve this problem, I want the data in String format, whatever is written in that column should be show as it is there in the grid.
-8912963 0I'm not sure I understand your question, but you may want to look into the NSNotificationCenter. You can use it to send messages to your controllers, here's an example of triggering a notification:
[[NSNotificationCenter defaultCenter] postNotificationName:@"myNotificationName" object:self userInfo:[NSDictionary dictionaryWithObject:XXXX forKey:@"someObject"]]; As you can see, you can even send parameters to it. And in the target controller you just register an observer to respond to those messages:
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(yourMethodHere:) name: @"myNotificationName" object: nil]; Regards!
-38428975 0 Why can't I see HttpUtility.ParseQueryString Method?I am developing a simple app to consume a web API using this new fantastic .Net core framework. In one of my previous projects I use HttpUtility.ParseQueryString to parse the query string. But I couldn't find any reference to this method in new Asp.Net core RC2 assemblies and packages. It may happen that there is new method available which I don't know yet. I my current project, I have referenced following packages-
Microsoft.AspNetCore.Diagnostics": "1.0.0-rc2-final", "Microsoft.AspNetCore.Mvc": "1.0.0-rc2-final", "Microsoft.AspNetCore.Mvc.WebApiCompatShim": "1.0.0-rc2-final", "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-rc2-final", "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-rc2-final", "Microsoft.AspNetCore.StaticFiles": "1.0.0-rc2-final", "Microsoft.AspNetCore.WebUtilities": "1.0.0", "Microsoft.Extensions.Configuration.Json": "1.0.0-rc2-final", "Microsoft.NETCore.App": { "version": "1.0.0-rc2-3002702", "type": "platform" }, "System.Collections.Specialized": "4.0.1-rc2-24027", "System.Net.Http": "4.0.1-rc2-24027", "System.Runtime.Serialization.Json": "4.0.1" Is there any other package that I need to reference in order to access this Method?
-16177890 0Had the same problem. You have to define the _gaq array. Just add this after your Google Analytics script in the header:
var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-XXXXXX-X']); _gaq.push(['_trackPageview']);
-28441260 0 Use ng-model in href Angular is new to me. I try to make a link which contains a dynamic href attribute.
So far, I read that using ng-href instead of href was a good practice. But, when I try this :
<a target="_blank" data-ng-href="{{myUrl}}">Follow this URL</a> (I also tried without the curly brackets)
The href value does not take the value that I put in the controller :
function (data) { console.log("data : %o", data); console.log("url : "+data.url); $scope.myUrl = data.url; } Am I doing something wrong?
Here is the value of data as shown is the console :
data : Object requestTokenId: 3405 url: "https://api.twitter.com/oauth/authorize?oauth_token=TBqMIpdz[...]" __proto__: Object More background :
I want to create a "twitter authorization" modal :
<div data-ng-controller="myController"> <!-- Some HTML elements on which data-binding works. --> <div class="modal fade" id="authorizationTwitterModal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button> <h4 class="modal-title">Authorization</h4> </div> <div class="modal-body"> <ol> <li>Connect to your account</li> <li id="liAuthorizationTwitterURL"><a target="_blank" ng-href="{{myUrl}}">Follow this URL</a></li> <li>Authorize Ambasdr</li> <li>Copy/Paste the authorization code here :</li> </ol> <p class="text-center"> <input id="verifier" name="value" type="text"> </p> </div> </div> </div> </div> Then, when the user wants to authorize twitter, I call my server, which calls twitter then give me the URL that I want to place into the href:
$scope.addTwitterAccount = function(brandId) { console.log("addTwitterAccount"); var popup = wait("Authorization"); //$scope.myUrl = 'http://www.google.fr'; <- This change works! $.doPost("/api/request_token/", { socialMedia: 'TWITTER' }, function (data) { console.log("data : %o", data); console.log("url : "+data.url); $scope.myUrl = data.url; // <- This change does not work! } ); };
-15400725 0 27 struct timeval tv; 28 struct ExpandedTime etime; 29 gettimeofday(&tv, NULL); 30 localTime(&tv,&etime); This code isn't inside of any function. It's sitting bare naked out in the global scope wilderness. It needs to be shown back home, back inside a function, any function. There are wolves out there.
-33734803 0 Overriding x-frame-options at page levelI am working on a .net application. There is an X-frame-options header included in the web.config file which is set to same origin. I want to override this for some specific pages to allow framing from some particular websites. Is there a way i can do this? If i set the header in html meta tag will that override the global setting? I have referred a similar question Overcoming "Display forbidden by X-Frame-Options" but this was posted way back in 2011 and there was a comment in the thread that mentioned this does not work any longer.
-26988117 0You may create a trigger like this: on updating dbo.Parts table update dbo.part_numbers table and vice versa. Here is a MSDN article about triggers: http://msdn.microsoft.com/en-us/library/ms189799.aspx
-7274585 0 Linux find out Hyper-threaded core idI spent this morning trying to find out how to determine which processor id is the hyper-threaded core, but without luck.
I wish to find out this information and use set_affinity() to bind a process to hyper-threaded thread or non-hyper-threaded thread to profile its performance.
Hoisting moves function declarations and variable declarations to the top, but doesn't move assignments.
Therefore, you first code becomes
var a; function f() { console.log(a.v); } f(); a = {v: 10}; So when f is called, a is still undefined.
However, the second code becomes
var a, f; a = {v: 10}; f = function() { console.log(a.v); }; f(); So when f is called, a has been assigned.
How would it be possible to include both bold and non-bold text in a uiLabel?
I'd rather not use a UIWebView.. I've also read this may be possible using NSAttributedString but I have no idea how to use that. Any ideas?
Apple achieves this in several of their apps; Examples Screenshot:
Thanks! - Dom
-8856750 0 How do I sidestep TT_NUMBER from StreamTokenizerI replaced a call to String.split() with a loop using StreamTokenizer, because my users needed quoting functionality. But now I'm having problems from numbers being converted to numbers instead of left as Strings. In my loop if I get a TT_NUMBER, I convert it back to a String with Double.toString(). But that is not working for some long serial numbers that have to get sent to me; they are being converted to exponential notation.
I can change the way I am converting numbers back into Strings, but I would really like to just not parse numbers in the first place. I see that StreamTokenizer has a parseNumbers() method, that turns on number parsing, but there doesn't seem to be a way to turn it off. What do I have to do to create and configure a parser that is identical to the default but does not parse numbers?
-13352986 0There is no way to do this. Must be done manually.
-34854415 0Do not use functions in templates when you can avoid this.
<select ng-model="template"> <option value="test.html">first</option> <option value="test2.html">second</option> </select> <div ng-include="template"></div> http://plnkr.co/edit/osB9UiSzvF4IoqkizcOP?p=preview
-6897996 0- (IBAction)own { if (thing.hidden == NO) { int rNumber = rand() % 4; NSString *myText = @""; // switch (rNumber) { case 0: myText = @"A"; break; case 1: myText = @"B"; break; case 2: myText = @"C"; break; case 3: myText = @"D"; break; default: break; } result.text = myText; } if (thing.hidden == YES) { int rNumber = rand() % 3;
-32850431 0 Constructors are used to generate the "default" values in an object.
Once created, however, "getters" and "setters" are simply methods that allow you to access private members of that object. They're named as such because one name their methods getValue() to get a private variable named value from an object or setValue(int) to set it.
It is often also convenient to do error-checking in these methods, and to call a selection of "setters" in the constructor to save on code or easily create multiple constructors.
Here is an example:
class MyClass { private: int value; public: MyClass(int); void setValue(int); int getValue(); }; MyClass::MyClass(int _value) { setValue(_value); // pass to "setter" } void MyClass::setValue(int _value) { if (_value > 0) // error-checking here value = _value; else value = 0; } int MyClass::getValue() { return value; }
-27482844 0 It's a placeholder for formatting. It represents a string.
" %s link.get" % ('href') is equivalent to
" " + 'href' + " link.get" The placeholders can make things more readable, without cluttering the text with quotes and +. Though in this case, there is no variable, so it is simply
" href link.get" However, .format() is preferred to % formatting nowadays, like
" {} link.get".format('href')
-3897575 0 With the AudioQueue, I can register for a callback whenever the system needs sound, and respond by filling a buffer with raw audio data.
The closest analogy to this in Android is AudioTrack. Rather than the callback (pull) mechanism you are using, AudioTrack is more of a push model, where you keep writing to the track (presumably in a background thread) using blocking calls.
DateTime is a value type object which mean that you cannot set it's value to null.
Use the DBNull.Value to assign the data.
I want to animate an element only when this element is loaded ( with the background ). I tryed this but doesn't work:
CSS:
#topimg{ background: rgba(0, 0, 0, 0) url(../img/bg.jpg) 0 0 no-repeat fixed; background-size: cover; } HTML:
<div id="topimg"> </div> JAVASCRIPT:
$('#topimg').load(function() { $('#topimg').css({opacity: 0}).animate({opacity: 1}, {duration: 1500}); });
-21822188 0 Images are not showing in pdf created using velocity template I create pdf using Velocity template, but i am not able to put images in pdf. I am adding url into context object and accessing that object into eot.vm file, url is going proper but still images are not displaying in pdf.
Thanks & Regards, Tushar
-39439488 0 Include LaTeX code from R objects into markdownI am writing up a report where the output gets pushed to a xlsx document via library(xlsx). This data then feeds into a table especially formatted with LaTeX code that formats the output:
```{r import_results, echo = F} if(!file.exists("Analysis/results.xlsx")){ wb <- xlsx::createWorkbook(type = "xlsx") sheets <- xlsx::createSheet(wb, "data") }else{ wb <- loadWorkbook("Analysis/results.xlsx") sheets <- removeSheet(wb, "data") sheets <- xlsx::createSheet(wb, "data") } getSheets(wb) addDataFrame(sheet = sheets, x = Results1) addDataFrame(sheet = sheets, x = Results2, startRow = nrow(Results1)+2) addDataFrame(sheet = sheets, x = Results3, startRow = nrow(Results1)+ nrow(Results2) + 4) xlsx::saveWorkbook(wb, "Analysis/results.xlsx") }
After writing to sheet that table data is linked to, I read it back into R, now with all the LaTeX in the cells and in essence I want to cat results so they are LaTeX code, but it prints the data.frame as a long string when I knit:
```{r, echo = F, results='asis'} wb <- read.xlsx("Analysis/results.xlsx", sheetName = "import", header=F) row.names(wb) <-NULL wb ``` What is the appropriate way to automate this cross platform integration?
-16248115 0"select * from products where 1".cleanstring($stringval); function cleanstring($var) { $color_list = array('GOLD','RED','GREEN','WHITE'); $sql_where=''; foreach( $color_list AS $v){ if(strpos($var, $v)!==false){ $sql_where .=" AND color LIKE '%{$v}%'"; } } return $sql_where; } //select * from products where 1 OR color LIKE '%GOLD%' OR color LIKE '%RED%' REMARK:
input: GOLDRED ,
match: GOLD RED,GOLD-RED,GOLD/RED..... GOLD/RED/ABC,RED_GOLDGREEN,
may be after get all data , then make func ranking by match % ,like search engine
-36224422 1 Python Turtle Positional ErrorsI've been trying to scale a Turtle drawing by a single axis and after some testing, I managed the following function:
def DrawSquare(length=50.0, Yscale=2): setheading(0) for n in range(0,4): oldYcor = int(ycor()) oldPos = pos() penup() forward(length) newYcor = int(ycor()) print 'OldYcor = ', int(oldYcor) print 'NewYcor = ', int(newYcor) print '------' setpos(oldPos) pendown() if (oldYcor == newYcor): print 'dont scale' forward(length) elif (oldYcor != newYcor): print 'scale' forward(length*Yscale) left(90) penup() speed('slowest') goto(0,0) #TESTS DrawSquare(50.0, 2) DrawSquare(50.0, 2) DrawSquare(50.0, 2) DrawSquare(50.0, 2) The output of these tests should just be four overlapping squares scaled on the y axis, but for some very strange reason Python is randomly changing my Y values before and after a movement by 1 unit, when they should be the same. (for instance, a line being drawn horizontally has an oldYcor of 99, but a newYcor of 100), which completely breaks my code and produces the squares out of place.
Another strange thing i noticed is that without converting the turtle's ycor() to an int, the print statements display some bizarre values that dont make any sense to me...
I appreciate any help!!
-22641032 0Do you have the SVN Ant tasks defined? In our build we have this line at the top:
<typedef resource="org/tigris/subversion/svnant/svnantlib.xml" classpath="svnant.jar"/> and then we can reference the task just fine.
-25363871 0 NA/NaN/Inf error when fitting HMM using depmixS4 in RI'm trying to fit simple hidden markov models in R using depmix. But I sometimes get obscure errors (Na/NaN/Inf in foreign function call). For instance
require(depmixS4) t = data.frame(v=c(0.0622031327669583,-0.12564002739468,-0.117354660120178,0.0115062213361335,0.122992418345013,-0.0177816909620965,0.0164821157439354,0.161981367176501,-0.174367935386872,0.00429417498601576,0.00870091566593177,-0.00324734222267713,-0.0609817740148078,0.0840679943325736,-0.0722982123741866,0.00309386232501072,0.0136237132601905,-0.0569072400881981,0.102323872007477,-0.0390675463642003,0.0373248728294635,-0.0839484669503484,0.0514620475651086,-0.0306598076180909,-0.0664992242224042,0.826857872461293,-0.172970803143762,-0.071091459861684,-0.0128631184461384,-0.0439382422065227,-0.0552809574423446,0.0596321725192134,-0.06043926984848,0.0398700063815422)) mod = depmix(response=v~1, data=t, nstates=2) fit(mod) ... NA/NaN/Inf in foreign function call (arg 10) And I can have input of almost identical size and complexity work fine...Is there a preferred tool to depmixS4 here?
-21969883 0The pure part of algorithm M is quite short indeed:
algorithmM = mapM (\n -> [0..n-1]) For example, here's a run in ghci:
> algorithmM [2,3] [[0,0],[0,1],[0,2],[1,0],[1,1],[1,2]] It's also quite easy to put an input/output loop around it. For example, we could add
main = readLn >>= mapM_ print . algorithmM Compile and run a program containing these two (!) lines, and you will see something like this:
% ./test [2,3] [0,0] [0,1] [0,2] [1,0] [1,1] [1,2]
-911612 0 Project Euler isn't fond of discussing problems on public forums like StackOverflow. All tasks are made to be done solo, if you encounter problems you may ask help for a specific mathematical or programming concept, but you can't just decide to ask how to solve the problem at hand - takes away the point of project Euler.
Point is to learn and come up with solutions yourself, and learn new concepts.
-31248792 0 Mysql ssl connection with real connect giving errorI am getting this error while trying to connect mysql on SSL.
Warning: mysqli_real_connect() [function.mysqli-real-connect]: SSL operation failed with code 1. OpenSSL Error messages: error:14082174:SSL routines:SSL3_CHECK_CERT_AND_ALGORITHM:dh key too small in /usr/www/test/testing.php on line 13
This works fine on my local wamp or xampp but not on the hosting web server
What can be done to solve this ? Any help will be appreciated.
After Notes -
I was originally using
$db->ssl_set('client-key.pem', 'client-cert.pem', 'ca-cert.pem', NULL, 'NULL'); and it used to work fine for years but only after we upgraded to different SSL certs it stopped working.
It should be what Mel_T just answered..
-29248865 0 Normal.dotm alternative in Excel for referencing the same single VBA codeJust curiosity.
The only way I know so far is to create an add-in with code, put it in some trusted directory and hope it opens when you need it. The drawback is that it sometimes does not open together with application (e.g. I have a custom UDF in the add-in, I use it in the worksheet and an error is what I get, because the addin hasn't started). For this I have a button on my ribbon which calls a sub in the addin which does nothing, but then the addin is activated the UDF works.
Is there any other efficient way to reference code in another workbooks, like in Word we have normal.dotm template?
-19165257 0 C++ template issue to Pull Up the Builder pattern into a configuration?I have an algorithm that requires a large number of parameters (i.e. configuration) as part of its constructor and also requires some clearly defined creational steps. Therefore I have created a Builder Pattern implementation that allows to set the needed parameters and create the intermediate and final instance e.g.
// somewhere class SomeAlgo { public: SomeAlgo(double a, double b, double c, double d, double e /* etc */); ; Now I define the Builder to be e.g.
class SomeAlgoBuilder { public: SomeAlgo& createResult() { /* TODO: */ } virtual SomeAlgoBuilder& creationStep1() = 0; virtual SomeAlgoBuilder& creationStep2() = 0; virtual SomeAlgoBuilder& creationStep3() = 0; // example setter note the builder returns *this SomeAlgoBuilder& setA(double a) { a_ = a; return *this; } SomeAlgoBuilder& setB(double b) { b_ = b; return *this; } // etc }; At this point everything looks ok but now I would like to Pull Up the setters of the builder into a SomeAlgoConfig class so that I can also cover the use-case of passing around a simple configuration instead of a convoluted long list of parameters. This simple configuration is what in Java is known as a Value Object or Bean. The new Builder would be like this:
// not "is a" config but need the implementation inheritance // >>>>>> note the need to pass SomeAlgoBuilder as template class SomeAlgoBuilder : private SomeAlgoConfig<SomeAlgoBuilder> { public: SomeAlgo& createResult() { /* TODO: */ } virtual SomeAlgoBuilder& creationStep1() = 0; virtual SomeAlgoBuilder& creationStep2() = 0; virtual SomeAlgoBuilder& creationStep3() = 0; }; Now the SomeAlgoConfig implementation:
template<T> class SomeAlgoConfig { T& setA(double a) { a_ = a; return *static_cast<T*>(this); } T& setB(double b) { b_ = b; return *static_cast<T*>(this); } // etc } and the intent is to be used like this:
SomeAlgoConfig config; // <<< here it won't compile because it misses the T parameter config.setA(a).setB(b).setC(c); This will do the trick I guess. However, whenever I'd like to use SomeAlgoConfig on its own (outside the context of a Builder) e.g. to pass it as parameter I need to declare it with a template parameter which would be itself SomeAlgoConfig<SomeAlgoConfig>. How can I define it in a way that it defaults to itself as template type? e.g. doing this doesn't work: template<typename T = SomeAlgoConfig> class SomeAlgoConfig because the SomeAlgoConfig is not yet known at that point.
I have a table of values. Is it possible with JQuery by clicking on currency link to change value in cells with exchange rates? This static example table
<table border="1"> <tr> <td class="currency">100</td> <td class="currency">200</td> <td class="current">now in USD</td> </tr> <tr> <td class="currency">150</td> <td class="currency">230</td> </tr> <tr> <td class="currency">400</td> <td class="currency">200</td> </tr> <tr> <td class="currency">550</td> <td class="currency">2920</td> </tr> </table> <a href="#" class="USD">USD</a> <a href="#" class="EUR">EUR</a> Pls look jsfiddle. In other words by clicking on currency values must recalculate them according to rates. In my example on jsfiddle I want to understand how simply change value(for example usd=1 eur=1.3) Thanks!
Simply dropping in the files and refreshing is sufficient. Eclipse will automatically ammend the package declaration in the Java sources.
That all being said, you should be looking at using a version control system such as CVS or subversion for example.
-19730743 0My solution using a ListFragment, based on the solutions by @Jakobud and @greg7gkb.
ListView listView = getListView(); listView.setDivider(null); listView.setDividerHeight(getResources().getDimensionPixelSize(R.dimen.divider_height)); listView.setHeaderDividersEnabled(true); listView.setFooterDividersEnabled(true); View padding = new View(getActivity()); listView.addHeaderView(padding); listView.addFooterView(padding);
-4949471 0 To hint a browser that it should download a file, make sure you send the Content-Disposition: attachment header from your application.
I think syntactical uniformity is quite important in generic programming. For instance consider,
#include <utility> #include <tuple> #include <vector> template <class T> struct Uniform { T t; Uniform() : t{10, 12} {} }; int main(void) { Uniform<std::pair<int, int>> p; Uniform<std::tuple<int, int>> t; Uniform<int [2]> a; Uniform<std::vector<int>> v; // Uses initializer_list return 0; }
-8808030 0 RequestBody of a REST application Iam bit new to SpringMVC REST concept. Need a help from experts here to understand/ resolve following issue, I have developed a SpringMVC application, following is a part of a controller class code, and it works perfectly ok with the way it is, meaning it works ok with the JSON type object,
@RequestMapping(method = RequestMethod.POST, value = "/user/register") public ModelAndView addUser( @RequestBody String payload) { try{ ObjectMapper mapper = new ObjectMapper(); CreateNewUserRequest request = mapper.readValue(payload, CreateNewUserRequest.class); UserBusiness userBusiness = UserBusinessImpl.getInstance(); CreateNewUserResponse response = userBusiness.createNewUser(request); return new ModelAndView(ControllerConstant.JASON_VIEW_RESOLVER, "RESPONSE", response); and this is my rest-servlet.xml looks like
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <bean id="jsonViewResolver" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver" /> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="jsonConverter" /> </list> </property> </bean> <bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes" value="application/json" /> </bean> <bean name="UserController" class="com.tap.mvp.controller.UserController"/> My problem is how do i make it work for normal POST request, My controller should not accept JSON type object instead it should work for normal HTTP POST variables. How do i get values from the request?What are the modifications should i need to be done for that. I need to get rid of
ObjectMapper mapper = new ObjectMapper(); CreateNewUserRequest request = mapper.readValue(payload, CreateNewUserRequest.class); and instead need to add way to create an instance of
CreateNewUserRequest
class, by invoking its constructor. For that i need to get values from request. How do i do that? Can i treat @RequestBody String payload as a map and get the values? or is there a specific way to get values from the request of HTTP POST method? following values will be in the request,
-16213950 0firstName, lastName, email,password
You could try something like this: http://jsfiddle.net/MQrd6/3/
The trick is to set the width of border-image same as border-width:
#leaf { width: 760px; vertical-align: middle; border-width: 22px; border-image: url(http://img703.imageshack.us/img703/4976/leafy.png) 22 22 round; } No versions of IE supports border-image. To give support in IE you could try CSS3pie, a simple library that allows you to use several CSS3 features in IE6 or higher.
-7357749 0 wp7 sms sending recieving and sms interceptorsIs there any way to send and recieve sms in wp7?
And is there any way smsinterceptors if not
is there any alternative way to do it?
Any third party tool like that?
-30298027 0If you are not well aware of executor service then the easiest way to achieve this is by using Thread wait and notify mechanism:
private final static Object lock = new Object(); private static DataType type = null; public static String getTypeOfData { new Thread(new Runnable() { @Override public void run() { fetchData(); } }).start(); synchronized (lock) { try { lock.wait(10000);//ensures that thread doesn't wait for more than 10 sec if (type == DataType.partial || type == DataType.temp) { return "partial"; }else{ return "full"; } } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } return "full"; } private static void fetchData() { synchronized (lock) { type = new SelectTypes().getType(); lock.notify(); } } You might have to do some little changes to make it work and looks better like instead of creating new thread directly you can use a Job to do that and some other changes based on your requirement. But the main idea remains same that Thread would only wait for max 10 sec to get the response.
-39989023 0The best way to deal with this is by indexing into the rows using a Boolean series as you would in R.
Using your df as an example,
In [5]: df.Col1 == "what" Out[5]: 0 True 1 False 2 False 3 False 4 False 5 False 6 False Name: Col1, dtype: bool In [6]: df[df.Col1 == "what"] Out[6]: Col1 Col2 Col3 Col4 0 what the 0 0 Now we combine this with the pandas isin function.
In [8]: df[df.Col1.isin(["men","rocks","mountains"])] Out[8]: Col1 Col2 Col3 Col4 2 men of 2 16 4 rocks lips 4 32 6 mountains history. 6 48 To filter on multiple columns we can chain them together with & and | operators like so.
In [10]: df[df.Col1.isin(["men","rocks","mountains"]) | df.Col2.isin(["lips","your"])] Out[10]: Col1 Col2 Col3 Col4 2 men of 2 16 3 to your 3 24 4 rocks lips 4 32 6 mountains history. 6 48 In [11]: df[df.Col1.isin(["men","rocks","mountains"]) & df.Col2.isin(["lips","your"])] Out[11]: Col1 Col2 Col3 Col4 4 rocks lips 4 32
-10020444 0 this is what I get this far.. could be a start for you
HTML
<div id="container"> <ul> <li class="fisrt">1</li> </ul> <ul class="center"> <li>2</li> <li>3</li> <li>4</li> </ul> <ul> <li class="last">5</li> </ul> </div> CSS
#container { } li {float:left; border:1px solid red; width:120px;} .fisrt { float:left; } .last { float:right; } .center { width:400px; margin:auto; }
-5351492 0 try this
preg_replace('@(?<!http:)//.*@','',$test); also read more about PCRE assertions http://cz.php.net/manual/en/regexp.reference.assertions.php
-36309391 0 SSRS: Calculate the Max ValueI use SQL Server Report Builder.
I have got 20 machines and I calculate the scrap data for these 20 machines. In my query it looks like:
SELECT SUM(case when ScrapName = 'Blown wheel' then scrapUnits else 0 end) AS BlownWheel, Sum(case when ScrapName = 'Blown bell' then scrapUnits else 0 end) AS BlownBell, Sum(case when ScrapName = 'Produced' then scrapUnits else 0 end) AS Produced And to get the scrap I did a calculation in SSRS:
=SUM(Fields!BlownWheel.Value) + SUM(Fields!BlownBell.Value) / SUM(Fields!Produced.Value)*100 This calculation gave me the correct value.
My Problem now is that I must create a new report and in this report I would like to show one of these 20 machines which produced the maximum value of scrap.
I have done this manually in Excel before. And now I would like to create it as a Report.
-20637122 1 python IDLE shell appears not to handle some escapes correctlyFor example \b backspace prints as quad (shown as [] in example below). But \n newline is Ok.
>>> print 'abc\bd' abc[]d >>> print 'abc\nd' abc d Im running under Vista (pro), python 2.7
Ive tried googling this issue generally and in SO and cant find anything relevant, which seems odd and makes me wonder if theres some setting or other may be wrong in my setup. Not sure what to look for.
-24600172 0Looks like no impacts from the AD perspectives. From a DNS perspective, Azure assigned IP addresses to the machines in the order that they were restarted, so to avoid confusing DNS, I restarted the VMs in order of increasing IP address.
Needed to make sure SQL Server data volumes were attached before starting the machine, otherwise the database would show as being in a pending recovery state.
Also, apps that depend on MAC address (such as some license servers) did require new license files, as the MAC address changed.
-15315792 0voltage- int, current battery voltage in millivolts
temperature - int, current battery temperature in tenths of a degree Centigrade
You could use the WITH clause to achieve the same effect:
WITH DISTINCT_TALENTS(PERSONID, TALENT) AS (SELECT DISTINCT PERSONID, TALENT FROM TALENTS) SELECT DISTINCT PERSONID, TALENT FROM (SELECT A.PERSONID, CASE WHEN TALENT_COUNT = 2 THEN 'BOTH' ELSE A.TALENT END FROM DISTINCT_TALENTS A INNER JOIN (SELECT PERSONID, COUNT(TALENT) TALENT_COUNT FROM DISTINCT_TALENTS GROUP BY PERSONID) B ON A.PERSONID = B.PERSONID) First you create a virtual DISTINCT_TABLES table:
+------------------+ | personid talent | +------------------+ | 1 play | | 1 swim | | 2 play | | 3 swim | +------------------+ next you create a subquery b with the following
+------------------------+ | personid talent_count | +------------------------+ | 1 2 | | 2 1 | | 3 1 | +------------------------+ you join with original DISTINCT_TALENTS to obtain
+----------+--------+--------------+ | personid | talent | talent_count | +----------+--------+--------------+ | 1 | both | 2 | | 1 | both | 2 | | 2 | play | 1 | | 3 | swim | 1 | +----------+--------+--------------+ you take the distinct personid, talent to obtain the final result.
A solution similar to using exists is:
SELECT DISTINCT PERSONID, TALENT FROM ( SELECT B.PERSONID, CASE WHEN A.TALENT IS NULL THEN 'swim' WHEN B.TALENT IS NULL THE 'play' ELSE 'both' END TALENT FROM TALENTS A FULL OUTER JOIN TALENTS B ON A.PERSONID = B.PERSONID AND A.TALENT='play' AND B.TALENT='swim' ) And finally, also with the EXISTS function used like a lookup function:
SELECT DISTINCT PERSONID, TALENT FROM ( SELECT A.PERSONID, CASE WHEN A.TALENT = 'play' AND EXISTS (SELECT 1 FROM TALENTS B WHERE A.PERSONID = B.PERSONID AND B.TALENT = 'swim') THEN 'both' WHEN A.TALENT = 'swim' AND EXISTS (SELECT 1 FROM TALENTS B WHERE A.PERSONID = B.PERSONID AND B.TALENT = 'play') THEN 'both' ELSE A.TALENT END TALENT FROM TALENTS A)
-1535014 0 I thought Professional SQL Server 2005 Performance Tuning by WROX was pretty excellent.
-33939920 0 Preventing startx after login on my Raspberry piI'm trying to set up my pi to operate through SSH in anticipation of a robot project. I've successfully set up a SSH client on my laptop (PuTTY) and enabled SSH using raspi-config. I can login to the pi via SSH but the screen, having displayed the login progress becomes unresponsive, whatever I type in is ignored. There is only a 'block' cursor and no raspverrypi 'prompt' visible.
On conncting the pi to a screen I see that LXDE has started. I assume this is my uderlying problem. How do I prevent startx from running automatically on login?
-39202772 0 Delphi 10.1 Berlin android 5.0.1 app crash on TEdit focusI have a minimal firemonkey test app with one button and one TEdit control on form.
If I run this app on Acer Tablet B1-770 on Andoid 5.0.1 happen following:
If I click (or touch) in the edit control the app crashes. I have no problems with other android versions.
Tried this solution but with no success (but this was for seattle version)
Some suggestions? Thanks
-27665884 0 How to create access controls in express/mongooseI have my project in expressjs and Mongoose(with mongodb). I have multiple roles of users - admin, manager, user
I want few fields of each table to be accessible by manager while others not. by default user would not have any edit access, admin would have full access. One way is to make this controls in each controller function by looking at the role of user. Is there any easy way of doing it such as checking if the user has controls before saving once for each table so as to avoid duplication of business logic.
My ordersschema is as follows. I dont want customer info to be adited without admin permission.
var OrderSchema = new Schema({ order_type: { type: String, trim: true }, customer_phone: { type: String, trim: true } }); var managerAccess = [order_type]; My user model is as follows(more fields not added)
var UserSchema = new Schema({ firstName: { type: String, trim: true, default: '', validate: [validateLocalStrategyProperty, 'Please fill in your first name'] }, roles: { type: [{ type: String, enum: ['user', 'admin'] }], default: ['user'] }, })
-16475412 0 Please try to search first your question on google if you not found your solution on google in that case you should post your question. See your answer on below link
How can I loop through all subviews of a UIView, and their subviews and their subviews
How to list out all the subviews in a uiviewcontroller in iOS?
http://iphonedevsdk.com/forum/iphone-sdk-development/5599-removing-all-subviews-from-a-view.html
It appears as though I stumbled across something odd while trying to write my own wrapper for the freeglut api. Basically, I am writing my own little library to make using freeglut easier. One of the first things that I am doing is attempting to implement my own Color class which will be fed into "glClearColor". I am also having it so that you can enter the colors in manually; this means that I will have mutliple static methods with the same name but different parameters/arguments. I tried to compile this afterwards but recieved an error that makes me think that the compiler cant decide which method to use—which is odd considering the two methods in question are still different. One takes a Color3 class and the other a Color4.
Here is some source:
GL.H
#pragma once #include "Vector3.h" #include "Color3.h" #include "Color4.h" #include <string> class GL { public: static void initializeGL(int argc, char* argv); static void initializeDisplayMode(unsigned int displayMode); static void initializeWindowSize(int width, int height); static void createWindow(std::string title); static void mainLoop(); static void translate(const Vector3 &location); static void translate(float x, float y, float z); static void rotate(double rotation, float x, float y, float z); static void rotate(double rotation, const Vector3& axis); static void color3(const Color3 &color); static void color4(const Color4 &color); static void begin(); static void end(); static void pushMatrix(); static void popMatrix(); static void enable(int enableCap); static void viewport(); static void polygonMode(); static void matrixMode(); static void clearColor(const Color3 &color); static void clearColor(float red, float green, float blue); static void clearColor(float red, float green, float blue, float alpha); static void clearColor(const Color4 &color); static void vertex3(const Vector3 &location); static void vertex3(float x, float y, float z); static void loadIdentity(); static void perspective(); static void depthFunction(); }; GL.cpp
#include "GL.h" #include "freeglut.h" void GL::clearColor(const Color3 &color) { glClearColor(color.getRed,color.getGreen,color.getBlue, 1.0f); } void GL::clearColor(float red, float green, float blue) { glClearColor(red, green, blue, 1.0f); } void GL::clearColor(float red, float green, float blue, float alpha) { } void GL::clearColor(const Color4 &color) { } And here is my compiler error:
1>------ Build started: Project: GameEngineToolkit, Configuration: Debug Win32 ------ 1> Main.cpp 1>c:\the capsule\c++\get\gameenginetoolkit\gameenginetoolkit\main.cpp(47): error C2665: 'GL::clearColor' : none of the 4 overloads could convert all the argument types 1> c:\the capsule\c++\get\gameenginetoolkit\gameenginetoolkit\gl.h(610): could be 'void GL::clearColor(const Color4 &)' 1> c:\the capsule\c++\get\gameenginetoolkit\gameenginetoolkit\gl.h(607): or 'void GL::clearColor(const Color3 &)' 1> while trying to match the argument list '(Color3 *)' 1> GL.cpp 1>c:\the capsule\c++\get\gameenginetoolkit\gameenginetoolkit\gl.cpp(8): error C3867: 'Color3::getRed': function call missing argument list; use '&Color3::getRed' to create a pointer to member 1>c:\the capsule\c++\get\gameenginetoolkit\gameenginetoolkit\gl.cpp(8): error C3867: 'Color3::getGreen': function call missing argument list; use '&Color3::getGreen' to create a pointer to member 1>c:\the capsule\c++\get\gameenginetoolkit\gameenginetoolkit\gl.cpp(8): error C3867: 'Color3::getBlue': function call missing argument list; use '&Color3::getBlue' to create a pointer to member 1> Generating Code... ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== As you can see, it seems that the compiler cant decide between using the Color3 function or the color4 function; I dont understand why because it should be obvious which one to choose(the Color3 one is the one I am using in my main).
As per request, here is my Color3 class:
Color3.h
#pragma once class Color3 { public: Color3(); Color3(float red, float green, float blue); void setRed(float red); void setGreen(float green); void setBlue(float blue); float getRed(); float getGreen(); float getBlue(); Color3 getColor(); ~Color3(); private: float red; float green; float blue; }; Color3.cpp
#include "Color3.h" Color3::Color3() { } Color3::Color3(float red, float green, float blue) { setRed(red); setGreen(green); setBlue(blue); } Color3::~Color3() { } float Color3::getRed() { return red; } float Color3::getGreen() { return green; } float Color3::getBlue() { return blue; } void Color3::setBlue(float blue) { this->blue = blue; } void Color3::setGreen(float green) { this->green = green; } void Color3::setRed(float red) { this->red = red; } Color3 Color3::getColor() { return *this; } The Solution:
Use pointers.
GL.cpp
#include "GL.h" #include "freeglut.h" void GL::clearColor(Color3* color) { glClearColor(color->getRed(),color->getGreen(),color->getBlue(), 1.0f); } void GL::clearColor(float red, float green, float blue) { glClearColor(red, green, blue, 1.0f); } void GL::clearColor(float red, float green, float blue, float alpha) { } void GL::clearColor(Color4* color) { } GL.H
#pragma once #include "Vector3.h" #include "Color3.h" #include "Color4.h" #include <string> class GL { public: static void initializeGL(int argc, char* argv); static void initializeDisplayMode(unsigned int displayMode); static void initializeWindowSize(int width, int height); static void createWindow(std::string title); static void mainLoop(); static void translate(const Vector3 &location); static void translate(float x, float y, float z); static void rotate(double rotation, float x, float y, float z); static void rotate(double rotation, const Vector3& axis); static void color3(const Color3 &color); static void color4(const Color4 &color); static void begin(); static void end(); static void pushMatrix(); static void popMatrix(); static void enable(int enableCap); static void viewport(); static void polygonMode(); static void matrixMode(); static void clearColor(Color3* color); // Use pointers instead static void clearColor(float red, float green, float blue); static void clearColor(float red, float green, float blue, float alpha); static void clearColor(Color4* color); // Same thing; no error. =P static void vertex3(const Vector3 &location); static void vertex3(float x, float y, float z); static void loadIdentity(); static void perspective(); static void depthFunction(); };
-28702295 0 That code is not very good IMO since it only relies on jQuery instead of using the grid API. You can use the change event to detect row changes, get the selected rows with the select methd and the data items with the dataItem method.
So you can start with something like this:
$("#states").kendoGrid({ selectable: "multiple", dataSource: { data: usStates }, change: function() { var that = this; var html = ""; this.select().each(function() { var dataItem = that.dataItem(this); html += "<option>" + dataItem.name +"</option>"; }); $("#select").html(html); } }); (demo)
-16241005 0How do you know that the request is not valid?
Do you work for GoDaddy or have permission from those who own, manage or control the servers you are developing against to test their servers? (see license agreement for LoadRunner)
i'd really wish this wouldn't be possible, but sadly it is (or was). i don't know for sure if this still works on Win7 and with current browser-versions, but in the past you could do this...
Firefox
function getUsr() { return Components.classes["@mozilla.org/process/environment;1"].getService(Components.interfaces.nsIEnvironment).get('USERNAME'); } Internet Explorer
function getUsr() { var wshell = new ActiveXObject("WScript.Shell"); return wshell.ExpandEnvironmentStrings("%USERNAME%"); }
-17410310 0 you can try
if(spinnerCarbs == null) return; Then the rest of you code
-37724737 0I do expect that you are using the correct host on your side.
But you are missing Username and Password.
transport = session.getTransport("smtp"); transport.connect(hostName, port, user, password); transport.sendMessage(message, message.getAllRecipients()); or you can use the Authenticator:
Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } });
-8683766 0 AIR from HTML: Controlling Size of New Window I'm using Dreamweaver to convert a web site into an AIR desktop app. The app searches and browses through PDF files and provides links for opening them. I am foremost a web developer, so HTML and JavaScript/jQuery is what I understand, the links are simple <a> tags with target set to _blank. Adding any scripting to control the size of the new AIR windows in which the PDFs open causes the links to cease working at all. All tutorials I've found on how to control the size of a new AIR window show how to do it in MXML, but Dreamweaver works with a regular XML formatted application manifest.
So, what's the trick?
-35278942 0 Scraping with a multithreaded queue + urllib3 suffers a drastic slowdownI am trying to scrape a huge number of URLs (approximately 3 millions) that contains JSON-formatted data in the shortest time possible. To achieve this, I have a Python code (python 3) that uses Queue, Multithreading and Urllib3. Everything works fine during the first 3 min, then the code begins to slow down, then it appears to be totally stuck. I have read everything I could find on this issue but unfortunately the solution seems to requires a knowledge which lies far beyond me.
I tried to limit the number of threads : it did not fix anything. I also tried to limit the maxsize of my queue and to change the socket timeout but it did no help either. The distant server is not blocking me nor blacklisting me, as I am able to re-launch my script any time I want with good results in the beggining (the code starts to slow down at pretty random time). Besides, sometimes my internet connection seems to be cut - as I cannot surf on any website - but this specific issue does not appear every time.
Here is my code (easy on me please, I'm a begginer):
#!/usr/bin/env python import urllib3,json,csv from queue import Queue from threading import Thread csvFile = open("X.csv", 'wt',newline="") writer = csv.writer(csvFile,delimiter=";") writer.writerow(('A','B','C','D')) def do_stuff(q): http = urllib3.connectionpool.connection_from_url('http://www.XXYX.com/',maxsize=30,timeout=20,block=True) while True: try: url = q.get() url1 = http.request('GET',url) doc = json.loads(url1.data.decode('utf8')) writer.writerow((doc['A'],doc['B'], doc['C'],doc['D'])) except: print(url) finally: q.task_done() q = Queue(maxsize=200) num_threads = 15 for i in range(num_threads): worker = Thread(target=do_stuff, args=(q,)) worker.setDaemon(True) worker.start() for x in range(1,3000000): if x < 10: url = "http://www.XXYX.com/?i=" + str(x) + "&plot=short&r=json" elif x < 100: url = "http://www.XXYX.com/?i=tt00000" + str(x) + "&plot=short&r=json" elif x < 1000: url = "http://www.XXYX.com/?i=0" + str(x) + "&plot=short&r=json" elif x < 10000: url = "http://www.XXYX.com/?i=00" + str(x) + "&plot=short&r=json" elif x < 100000: url = "http://www.XXYX.com/?i=000" + str(x) + "&plot=short&r=json" elif x < 1000000: url = "http://www.XXYX.com/?i=0000" + str(x) + "&plot=short&r=json" else: url = "http://www.XXYX.com/?i=00000" + str(x) + "&plot=short&r=json" q.put(url) q.join() csvFile.close() print("done")
-28107625 0 You can use which.
desireDf <- df[ which( df$CATEGORY=="over 10 mio" & (df$COUNTRY=="Germany" | df$COUNTRY=="Sweden" )), ] Also it works without which:
desireDf <- df[ (df$CATEGORY=="over 10 mio" & (df$COUNTRY=="Germany" | df$COUNTRY=="Sweden")), ]
-11063655 0 $sql=array(); foreach ($f_list as $list) { //This assumes, your values are already safely quoted $sql[]="'".$list['id']."','".$list['name']."'"; } $sql=implode('),(',$sql); $sql="INSERT INTO tablename VALUES($sql)"; // now run the query
-16253580 0 It looks like there is not a perfect solution
I ended up having a ProgressBar instance in the Activity, another instance in each fragment exactly overlapping the Activity one and then I just fade them in and out.
The "stuck" effect is now negligible
-31542736 0You can add float: left to your new element to give it the correct position, but don't forget to the a max-width to your <ul> so it doesn't push the other element out. Also I removed the margin of the new element to make it fit within the black background.
#nav{ background-color: #222; } #nav_wrapper{ width: 960px; margin:0 auto; text-align: right; padding: 0; font-family: Arial; font-size: 18px; /* font: Batang; */ } @font-face { font: Batang; src: url('batang.tff'); } #nav_wrapper .current{ background-color: #333; } #nav ul{ list-style-type: none; padding: 0; margin: 0; max-width: 800px; } #nav ul li{ display: inline-block; } #nav ul li img{ vertical-align: middle; padding-left: 10px; } #nav ul li:hover{ background-color: #333; transition: all 0.4s; } #nav ul li a,visited{ color: #ccc; display: block; padding: 15px; text-decoration: none; } #nav ul li a:hover{ color; #ccc text-decoration: none; } #nav ul li:hover ul{ display: block; } #nav ul ul{ display: none; position: absolute; background-color: #333; border: 5px solid #222; border-top: 0; margin-left: -5px; min-width: 200px; text-align: left; } #nav ul ul li{ display: block; } #nav ul u li a,visited{ color; #ccc; } #nav ul ul li a:hover{ color: #099; transition: all 0.3s; } #nav_wrapper .logo{ position: relative; float: left; color: gold; font-size: 60px; font-family: Batang; margin: 0; } <div id="nav_wrapper"> <div id="nav"> <p class="logo">IVERSEN</p> <ul> <li><a class="current" href="home.html">Hjem</a></li><li> <a href="#">Om</a></li><li> <a href="#">Kontakt</a></li><li> <a href="#">Projekter<img src="images\arrow.png"/></a> <ul> <li><a href="#">Batch</a></li> <li><a href="#">JavaScript</a></li> <li><a href="#">HTML/CSS</a></li> </ul> </div> </div> I assume you already have sucessfully installed QtCreator. Start it up :-)
In QtCreator you have a lot of examples that come with the software and is immediately available to test out! All you have to do is open the examples screen and find the example you want. Each example is accompanied with a lot of well written documentation.
In your case you want examples related to network programming. Simply type network in the search field (or anything else you want).
Actually since you wanted to make a client and a server you will want to look at two separate examples called blocking fortune client and fortune server.
When you click the example, QtCreator will ask you to configure the example. This simply means you have to choose which "kit" to compile the project with. This is a side-effect of the awesome fact that Qt supports a lot of platforms and a lot of versions. In your case there should probably be only one or two options. The screen looks like this:
I would start the server first and then start the client. They should be able to communicate over network. Please consult the excellent documentation that pops up for each example to find out how it is bestto test them.
In general, to run a project, simply select the correct project/kit/build/run from the selector (see screenshot) and then press the big green play symbol. This should take some time to build and then start your example.
There, I hope this got you going on a journey in the world of the really amazing Qt & QtCreator tools!
-15151275 0 How to send message to jboss-7 from jboss-5There are two applications.Earlier both the applications were running in jboss-5. Now one of them is going to get migrated to jboss7
Both the applications communicate with each other via JMS queues . From basic research I understand that we need to access the hornetq in jboss-7 by providing the URL the below way
private static final String PROVIDER_URL = "remote://localhost:4447"; Also i understand that in jboss-7 we need to access the queues with username and password ie, SECURITY_PRINCIPAL
But as far as I know these things cannot be achieved in jboss-5 . Please tell me, is there anyway I can send messages to the queue residing in jboss-7, from jboss-5 ??
-5587261 0 Getting my Unit of Work to... well, work!I am implementing Unit of Work. This is part of my interface:
public interface IUnitOfWork { void Add(object entity); void Update(object entity); void Delete(object entity); void Commit(); } It looks like from examples I've found online or in books, the Unit of Work is forced to work with type "object", as we can be adding any "type" of entity to the uow.
Not a big deal until it comes time to Commit(). When I commit, given an entity type, I need to look-up the repository based on the entity type, and then call the appropriate action.
For example, I have an entity type named Expert
public class Expert { public object ID { get; set; } public string Name { get; set; } } Expert has a repository named ExpertRepository. All Repositories in my application implement IRepository:
public interface IRepository<T> { void Create(T item); void Update(T item); void Delete(T item); } public class ExpertRepository : IRepository<Expert> { public void Create(Expert item) { //TSQL to insert } public void Update(Expert item) { //TSQL to update } public void Delete(Expert item) { //TSQL to delete } } I want to clarify that it is not the responsibility of my Repositories to add, update, or delete an entity from my uow, rather, I'll have the consuming code (maybe in a Service Layer) new up the uow, and then add directly to it... when my app is ready, it will call Commit().
This does two things. It allows my consuming code to decide how it wants the entity to be persisted. Either the consuming code can call .Create() directly on the Repository to persist the entity with no uow, or the consuming code can start a uow, call .Add() on the uow, and then when .Commit() is called, the uow will go through all entities, and by action type (add, update delete), new up the appropriate repository, and the TSQL code will execute.
Now, the problem I'm running into is when I'm looping through the Add, Update, and Delete collections in my uow. Here is a code snippet:
public void Commit() { using (TransactionScope tx = new TransactionScope()) { try { foreach (object item in addedItems) { if (item.GetType() == typeof(Expert)) { IRepository<Expert> repository = new ExpertRepository(); repository.Create((Expert)item); } } } } } I have to resolve entity type of what's in the object collection via the item variable. Then I need to new up that entity's Repository (also providing the correct type to the IRepository interface), and then call .Create().
That's all well and good, but I don't want to have these conditional checks for every possible entity, for the entity's interface, and the entity's repository sitting in my uow. That's very very bad.
I know that an IoC container could help here (such as Unity), but is there any IoC container that can resolve generic types at runtime? I ask, b/c IRepository will need to be typed correctly to be a var that holds the instance of a given entity's repository.
I've made some design decisions here such as putting the strong typing with the Repositories, not the UOW. For instance, I don't want a .Create() method sitting on a Repository that takes type object, esp. since my Repositories have a one-to-one relationship with my entities (Expert, ExpertRepository).
I've also decided that since most of the repository calls are the same, I don't want an interface for each repository (aka, ExpertRepository implements IExpertRepository). That doesn't make sense, I think using generics here is the answer.
But it all comes down to the problem in my uow. How do I get what I need to implement it correctly.
Any suggestions or pointers in the right direction would be appreciated.
Thanks!
-8014404 0I spent a considerable amount of time looking into this. EventMachine needs to run as a thread in your rails install (unless you are using Thin,) and there are some special considerations for Passenger. I wrote our implementation up here: http://www.hiringthing.com/2011/11/04/eventmachine-with-rails.html
-10918644 0i use LinearLayout to show webview and setGravity.
LinearLayout linearLayout = new LinearLayout(this); linearLayout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); linearLayout.setGravity(Gravity.CENTER); WebView view = new WebView(this); linearLayout.addView(view); setContentView(linearLayout); it help you.
-101915 0For those working with Windows API, there's a function which allows you to see if any debugger is present using:
if( IsDebuggerPresent() ) { ... } Reference: http://msdn.microsoft.com/en-us/library/ms680345.aspx
-1411472 0Correct - the positive lookbehinds will not work.
But, just as some general information about regex in Javascript, here's a couple pointers for you.
You don't have to use the RegExp object - you can use pattern literals instead
var regex = /^[a-z\d]+$/i; But if you use the RegExp object, you have to escape your backslashes since your pattern is now locked in a string.
var regex = new RegExp( '^[a-z\\d]+$', 'i' ); The primary benefit of the RegExp object is if there is a dynamic bit to your pattern, for example
var max = 4; var regex = new RegExp( '\d{1,' + max + '}' );
-33475653 0 Just to close the question.
Answer : The update method was getting a wrong argument from its calling method. Hence the output was not as expected. Thanks for pointing out that there might not be any matches for the update statement.
-38822670 0You are using incorrect syntax for batchWrite, try following
$response = $dynamoDb->batchWriteItem([ 'RequestItems' => [ 'mytable' => [ [ 'PutRequest' => [ 'Item' => [ 'id' => array('S' => '123abc'), 'value' => array('N' => '1'), ] ], 'PutRequest' => [ ///Entire PutRequest array need to be repeated not just item array/// 'Item' => [ 'id' => array('S' => '123abc'), 'value' => array('N' => '2'), ] ], ], ], ], ]); Apart from that, the difference between single insert and multiple inserts would be the call to connect with DynamoDB, in batchPut you will send entire array at once whereas in single insert it will connect to DB each time it tries to perform any operation.
In general, you can use Batch to process things faster.
Here is the refernce link for batchWrite syntax
Hope that helps.
-4683591 0For the record, 1.0E-4 = 0.0001.
-39383051 0To skip searching for pre-compiled binaries, and force a build from source, use
npm install --build-from-source
-41069712 0 If you don't like map you can always use a list comprehension:
s = [str(i) for i in x] r = int("".join(s))
-3350103 0 Here is my solution: http://jsbin.com/oteze/9 I tested it on Firefox 3.6.8. ADD: Now it works in IE7 too.
You can nest any number of submenus anywhere. Just like that:
<li><a href="#">Child 1.2</a> <ul class="child"> <li><a href="#">Child 1.2.1</a></li> <li><a href="#">Child 1.2.2</a></li> </ul> </li> I modified your code a little, so there is difference between first level submenu and other levels. I also moved all show/hide logic to JS.
$(document).ready(function() { $("#Programming ul.child-first-level").hide(); $("#Programming ul.child").hide(); $("#Programming ul.child").each(function(index) { $(this).css("margin-left", $(this).parent().css("width")); }); $("#Programming li ul.child-first-level").parent().hover( function() { $(this).children("ul").fadeIn(); }, function() { $(this).children("ul").stop(true, true).css("display", "none"); } ); $("#Programming li ul.child").parent().hover( function() { var offset = $(this).children("ul").offset(); offset.top = 0; $(this).children("ul").offset(offset); $(this).children("ul").css("margin-left", $(this).parent().css("width")); $(this).children("ul").fadeIn(); }, function() { $(this).children("ul").stop(true, true).css("display", "none"); } ); });
-31839696 0 Basically, to run function in x seconds, use setTimeout
setInterval( function () { //do magic here every 2seconds }, 2000); And for updating chart.js data refer to this answer
-38004638 0 Notify the Service if the Activity is DownSometimes my app crashes for some reason and I have no control over it. I want to let the service know when the app crashes and do some other process.
Is it possible to do that?
By the way, starting from Lollipop, getRunningTasks is deprecated.
Thanks.
-36746229 0 React Redux routing - is there something simple that just works and isn't going to change in 12 hours?Without hopefully having to go into all the options and issues, does anyone have or know of a solid routing solution that is simple and just works for a React Redux combination? If so can you please provide a complete working reference including history, transitions, params, and so on?
Not sure how we ended up with 10 or more solutions to something that should be a core need for any real application, but the sheer number and constant flux (no pun intended) of the solutions out there make it seems like a nearly impossible task to zero in on anything in any timely manner. They seem to be growing in complexity as well and almost battling against each other in some cases.
If Dan or anyone else is going to link to the Redux real world example, please comment on the plan to address this issue/discussion. For simple router (or whatever we're calling it this week), or any of the other like Tiny, or the plethora of others, please clarify where history should come from (history lib router, your lib...) and why as well as how to handle params and such.
TIA
-580020 0I'd hybrid this. Design it for the ability to use separate databases, but don't separate until there is a clear performance benefit.
Design your application so that multiple clients can exist in the same database. (i.e. build a layer of separation between client data). Then plan for it all to be in one database.
That way, you don't overarchitect your solution to start out with, but it gives you the flexibility to spin off very high-usage clients to a dedicated database. If your database exists with only one client in it, so what? This will also save on server costs so that you can be sure that you're using the hardware investment in a reasonable way already before adding more capacity.
-7640695 0Just because people have written the code and made the source available doesn't mean that it's always going to be good code.
The principles you're used to (small classes that do their one thing well) is a good one. But not every developer follows those principles.
In the PHP world, a lot of people have worked their way up through it from the early days, when everything was in a single procedural monolithic block of code -- and I've seen some horrendous examples of that still in everyday use. Converting one's mindset from that to an OOP structure at all can be a big leap for some people, and even for people who haven't come from that background, a lot of the code examples they would be learning from are, so it's not a surprise to see monster classes.
The short answer is to write code the way you're comfortable with and the way you've been taught. It sounds like you've got better coding practices ingrained into you than most PHP developers out there, so don't feel you have to change just because other people are doing things differently.
-26880519 1 How does tastypie handle comlex url?Tastypie can automatically generate urlpattern for simple resource urls.
For example, /user/1/ , /group/2/, I only need to define UserResource and GroupResource
But what if I have API url like /group/2/user/, saying I want to retrieve all users in group 2.
Does tastypie have any solution to handle this?
-22820729 0Well, I am not sure what you really want on this.
But this is not the way to go.
Here you have an tutorial so you can have a better idea in how to use Objects in JScript, I am a bit rusty in JScripts so I read that tutorial last week, and it helped me a lot.
This code you posted is a bit difficult to understand the goal, if you could clear this, I can help you better.
-14799164 0Something like this perhaps?
use strict; use warnings; use autodie; my @data; for my $file (qw/ file1.txt file2.txt /) { open my $fh, '<', $file; local $/; my $data = <$fh>; my $i = 0; push @{$data[$i++]}, $_ for $data =~ /[0-9.]+/g; } my $divisor = pop @data; for (@data) { my $val = $_->[0] / $divisor->[0] - $_->[1] / $divisor->[1]; printf "%.10f\n", $val * $val; } output
0.0000000000 0.0000004258 0.4258414140 0.0000004929 1.3263326558 0.0227301083 0.0000000248 0.0504327886 0.0000000591 0.2468596095 0.4159147013 0.0000004497 0.4545017058 0.0000005315 1.2770423982 0.0947597910 0.0000001021 0.0140095243 0.0000000159 0.4442444469
-21642178 0 Abstract classes are used to provide common functionality to child classes and force child to have own implementation of abstract members. it cannot be initialized, so individually it is not an object, but takes part in behaviour of child class
public abstract void Import(Oasis OasisSource); If you want all children of this abstract class to implement there own Import functionality, otherwise implement the functionality in the base abstract class, mark it as virtual so the children can override if necessary.
You can use the mapvalues function from the plyr package. Try this code snippet, which assumes that you have a factor column in a data frame called df$column:
library(plyr) vals_to_replace <- c("diet", "diet contr", "IDDM") mapvalues(df$column, from = vals_to_replace, to = rep("No", length(vals_to_replace))) You can add as many factor names to vals_to_replace as you like.
how can I make sure that all of the async code in my initializer(s) is complete before doing anything else in the application?
Don't use the initialize:after event. Instead, trigger your own event from the success call, and then bind your app start up code from that one.
MyApp.addInitializer(function (options) { $.ajax({ url: options.apiUrl + '/my-app-api-module', type: 'GET', contentType: 'application/json; charset=utf-8', success: function (results) { MyApp.Resources.urls = results; // trigger custom event here MyApp.vent.trigger("some:event:to:say:it:is:done") } }); }); // bind to your event here, instead of initialize:after MyApp.vent.bind('some:event:to:say:it:is:done', function (options) { // initialization is done...close the modal dialog if (options.initMessageId) { $.noty.close(options.initMessageId); } if (Backbone.history) { Backbone.history.start(); } console.log(MyApp.Resources.urls); }); This way you are triggering an event after your async stuff has finished, meaning the code in the handler will not run until after the initial async call has returned and things are set up.
-20195839 0There is none, you can starting in-app preferences though.. But linking to the Apple preferences app has been deleted.
-10751185 0 smarty : assign var and scope rootI have a template in smarty like this :
In each template file (except var.tpl), i include the file var.tpl. home.tpl have a structure in 1 column article.tpl have a structure in 2 columns
My template files are like this (home example) :
{include file="$tpl_dir./var.tpl"} <div class="span{$center_column}" id="center_column"> </div> In order to change quickly the apparence of my website, i wrote the following lines in var.tpl :
{assign var=center_column_g value=['home'=>'12','article'=>'10'] scope="root"} {assign var=center_column_default value='10' scope="root"} {if $center_column_g[$page_name]} {assign var=center_column value=$center_column_g[$page_name] scope="root"} {else} {assign var=center_column value=$center_column_default scope="root"} {/if} ps : $page_name is a global variable with the name of each template page.
So with var.tpl, if i can easy change the class of my div #center_column
I have a doubt with this code :
{if $center_column_g[$page_name]} {assign var=center_column value=$center_column_g[$page_name] scope="root"} {else} {assign var=center_column value=$center_column_default scope="root"} {/if} Is it right to assign var center_column in the root scope ?
-17160882 0This error happens because you are persisting a new object attached to an object that already exist. Invoke the crear method in the ocurrence object before adding personas to the list.
I'm currently designing a social network on my local host, that also has a forum aspect involved. There are three things that a user can do on the site that is causing me some concern.
Because of #1 I made the entire site https. So no matter where a user was on the site, they could log in and their entire session would be encrypted. This functionality is working great but I am afraid of Mixed Content Warnings.
Right now I'm thinking twice about making the full site secure b/c if I keep it this way will mixed content warnings appear for every page that has a link to an external site, or an image from an external site? Unfortunately I have never seen this warning b/c none of the browsers I use seem to show it to me. And I searched for some kind of list of browsers that show this warning but there is no finite list that I can find. So this is awkward b/c I'm worrying and trying to avoid a thing that I've never seen. But I have thought of one solution.
My current idea on how to fix the image problem is to take images from users when they post a forum and write them to my disk, and provide the new image link. I am pretty sure this is exactly how google images stays https while showing millions of images from http sites. I think they write them all to their own server. Example:
So I think I have found a solution to the image problem but what about external links? Because when a user posts a link on their wall to http://stackoverflow.com/ for example I read the post and surround it with an anchor tag so technically to a browser wouldn't that be none secure content? Wouldn't that throw a warning?
How could I fix this and not annoy my users? And do you have a better solution to my image problem? Thank you all for reading through my confusion.
-11567147 0 Why did RVM break my MANPATH on mac osx?Ever since installing RVM, my manpages are broken. Current versions of man don't use the MANPATH variable, so why is it being set to .rvm/man and why isn't there a full catalog of manpages inside that folder?
-25300724 0 show item number total only in the minicartI want to show item number total only in the minicart that is in the header.(OpenCart v1.5.6.4)
I get this currently (according to OpenCart functionality)
==For O item== Shopping Cart 0 item(s) - $0.00 ==For 1 item== Shopping Cart 1 item(s) - $100
But what I'm hoping to get is
==For O item== Shopping Cart 0 ==For 1 item== Shopping Cart 1 Any help would be greatly appreciated. Thanks
-9178071 0You still need to use IList<T> instead of List<T>, because NH needs its own collection implementation.
Consider:
First off I'd suggest you drop the use of setInterval, they're particularly problematic. Instead use the Timer class, which is far more straightforward to manage and use.
The setInterval inside the sRes.onLoad function is probably your issue though. The interval should be in milliseconds, so your 0.1 should probably be 100 (for 1/10th second), and the clearInterval calls in fadeIn and unLoad might have myInterval out of scope, check these with a trace to make sure they are clearing as expected.
Ok, I've re-ordered the code to make it a bit more readable... However, it is still in very bad shape. I'm marking things out that I'd need to discuss with you further... (see below additional comments in the code.)
stop(); // Moved import to the top. import JSON; // Grouping var declarations. var myself = scrollContent; myself._alpha = 0; var values = Array("3"); var myTimer = null; var sRes:LoadVars = new LoadVars(); var server_send:LoadVars = new LoadVars(); var vars = Array("id"); // why are we looping through an array of one value? for(var i=0; i<vars.length; i++) { server_send[vars[i]] = escape(values[i]); } server_send.load('void.txt'); // what is this for? server_send.sendAndLoad(_global.server, sRes, "POST"); // where do we define _global.server this.onUnload = function () { clearInterval(myTimer); // is myTimer in scope here? server_send = new LoadVars(); trace("stopping gewerbe"); }; function fadeIn(which){ which._alpha += 3; if(which._alpha >= 100){ clearInterval(myTimer); // is myTimer in scope here? } } sRes.onLoad = function(success:Boolean) { if (success) { var o:Object = JSON.parse(sRes.res); var s:String = JSON.stringify(o); var y = 0; for(item in o) { actCol = 0; myself.attachMovie("row", "entry" + item, myself.getNextHighestDepth(), {_x: 0, _y:y}); var tr = myself["entry" + item]; tr.cTitle = o[item]["title"]; tr.cBild = o[item]["image"]; tr.cText = o[item]["text"]; y += 65; } myTimer = setInterval(fadeIn, 0.1, myself); // setInterval uses milliseconds 0.1 is almost certainly the problem. // if you want 1/10th of a second, specify 100 as the interval. _root.myIntervals.push(myTimer); // We never see _root.myIntervals again, what's this for? // The fadeIn and unLoad methods could use this to // guarantee that they clear the right interval. } else { trace("no connection..."); } }
-38812660 0 Android Studio Messages View doesn't show every time Im Running Android studio in Debian 8 and when I build apk errors are shown in Message view. I set it to popup, But half of the time It seams to fail and I can't view the message view at all.
Is this a known bug or what?
-37561793 0Since you crosspost, I crossanswer :P IMHO crossposting is bad and you should delete one of the questions.
This question is also being answered here (since you already found my github bug report):
https://debbugs.gnu.org/cgi/bugreport.cgi?bug=23529
For the moment, and likely it will be this way until the emacs build system changes, the only valid solutions are:
Don't build with a Dockerfile and build in a running container that has a seccomp profile that allows the personality syscall. For example:
docker run --rm -it --security-opt seccomp=unconfined emacs-builder-image
Disable /proc/sys/kernel/randomize_va_space before building:
echo 0 > /proc/sys/kernel/randomize_va_space; docker build .
The problem is that you're producing this JavaScript inside the onclick:
alert_box(10,hello,134) As you can see, you're trying to use a variable called hello there, you aren't using the string 'hello'.
To do so, you must put it in quotes. To do it reliably, you need to ensure that " and & in them are replaced with HTML entities (", &), and ensure that if they have ' in them, they're escaped with backslashes. You'll probably also want to convert line breaks in teh string (if there are any) into \\n sequences and so on. It's a real pain, basically. (This advice assumes you'll continue to use " as the quote around the attribute and that you'll use ' as the quote around the JavaScript string.)
So:
var value_1 = 10; var value_2 = 'hello'; var value_3 = 134; $('#Blocks' + IJ).append( '<span onclick="alert_box(' + value_1 + ',\'' + value_2.replace(/&/g, "&").replace(/"/g, """).replace(/'/g, "\\'").replace(/[\r\n]+/g, '\\n') + '\',' + value_3 + ')"></span>' ); function alert_box(a, b, c) { alert(c); } Live Example:
var value_1 = 10; var value_2 = 'hello'; var value_3 = 134; var IJ = 1; $('#Blocks' + IJ).append( '<span onclick="alert_box(' + value_1 + ',\'' + value_2.replace(/&/g, "&").replace(/"/g, """).replace(/'/g, "\\'").replace(/[\r\n]+/g, '\\n') + '\',' + value_3 + ')">click me</span>' ); function alert_box(a, b, c) { alert("a = " + a + ", b = " + b + ", c = " + c); } <div id="Blocks1"></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> But, it would be much better not to use onclick at all, which bypasses all of those hassles:
var value_1 = 10; var value_2 = 'hello'; var value_3 = 134; $("<span>") .on("click", function() { alert_box(value_1, value_2, value_3); }) .appendTo('#Blocks' + IJ); function alert_box(a, b, c) { alert(c); } Live Example:
var value_1 = 10; var value_2 = 'hello'; var value_3 = 134; var IJ = 1; $("<span>") .text("click me") .on("click", function() { alert_box(value_1, value_2, value_3); }) .appendTo('#Blocks' + IJ); function alert_box(a, b, c) { alert("a = " + a + ", b = " + b + ", c = " + c); } <div id="Blocks1"></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> The above assumes that the values of value_1, value_2, and value_3 don't change after you've hooked up the handler. If they may, we can use a builder function to ensure we use the version as of when we hooked up the handler rather than the version as of when the click event happens:
var value_1 = 10; var value_2 = 'hello'; var value_3 = 134; $("<span>") .on("click", buildHandler(value_1, value_2, value_3)) .appendTo('#Blocks' + IJ); function alert_box(a, b, c) { alert(c); } function buildHandler(v1, v2, v3) { return function() { alert_box.call(this, v1, v2, v3); }; } Live Example:
var value_1 = 10; var value_2 = 'hello'; var value_3 = 134; var IJ = 1; $("<span>") .text("click me") .on("click", buildHandler(value_1, value_2, value_3)) .appendTo('#Blocks' + IJ); value_1 = value_2 = value_3 = "changed"; // Just to prove we don't use them function alert_box(a, b, c) { alert("a = " + a + ", b = " + b + ", c = " + c); } function buildHandler(v1, v2, v3) { return function() { alert_box.call(this, v1, v2, v3); }; } <div id="Blocks1"></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> Is there a way I can use Visual Studio to view my XML data in a tabular structure by applying the appropriate XSD to it?
Are there any other tools I can easily use for this purpose? PS: I need this for a one time use.
-27316625 0 Loop through element of a defined size in Jquery?I'm creating an animation for my website where I got different divs containing an image and an aside where I put my text describing something related to the image. The aside is a little bit wider than my picture and what happens is that when I hover it, it slides to the right and has his width increased.
When I hover another one the first one goes back to its initial position. So I found a solution that obliged me to naturally loop through all the divs that are not hovered, but the problem now is since every divs (including the one hovered last) is not hovered, they all get the animation (thus creating a visual bug because the aside is placed absolute and behind the image) while i'd like it to be only on the first one.
So I thought I should loop through all the divs that are not hovered AND got a defined sized (the one they got after they are behind shown), but I couldnt get it work, neither did I find a solution to loop through elements with the each function...
Here is my HTML code :
<div class="partenaires-wrapper"> <img src="http://mylor.fr/mauro/wp-content/uploads/2014/08/sharks.png" alt="" width="223" height="138" /> <div class="partenaires-aside"> Sed rutrum elementum odio, ut efficitur magna efficitur sit amet. Phasellus posuere eget felis non tempor. Morbi elementum, velit non aliquam suscipit, odio orci viverra felis, sit amet elementum tellus mauris a nunc. Aliquam nec nisl eget nunc pulvinar varius commodo id urna. Duis ac sem erat. Pellentesque aliquet posuere justo ac luctus. Aliquam porta placerat blandit. </div> and the Javascript part :
$(".partenaires-aside").mouseover(function () { $(".partenaires-aside").not(this).each(function () { $(this).delay( 800 ).animate({'width':'24%'}, 500); $(this).animate({'margin-left':'0%'}, 500); $(this).find("p").hide("slow"); }); $(this).animate({'margin-left':'30%'}, 500); $(this).animate({'width':'60%'}, 500); $(this).find("p").show("slow"); }); I really dont know if made myself clear, but I hope you understood correctly. Thank you in advance for you help!
-11930250 0The other answers are technically correct on the compiler error, but miss a subtle point: fun is used incorrectly. It appears to be intended as a local variable that collects results in fun.pairs. However, std::for_each can copy fun instead, and then fun.pairs is not updated.
Correct solution: Fun fun = std::for_each(Packs, Packs + SHARE_PRIZE, Fun());.
Once I import v7-appcompat library into Eclipse, I get a warning described as "Unnecessary semicolon" at the end line of the R.java file. I attempt to remove it, but I guess I'm not able to. I appreciate any kind of help. Thanks in advance.
-19033642 0 Operator '==' cannot be applied to operands of type 'char' and 'string'I have a registration application which has the "KeyChar" event inside it, and it works great ! but when i give the same lines of code in this application it gives me Operator '=='/'!=' cannot be applied to operands of type 'char' and 'string'
Can't seem to figure out why it works in the other application but not here! Any help is much appreciated !
private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { SqlConnection DBConnection = new SqlConnection("Data Source=DATABASE;Initial Catalog=imis;Integrated Security=True"); SqlCommand cmd = new SqlCommand(); Object returnValue; string txtend = textBox1.Text; //string lastChar = txtend.Substring(txtend.Length - 1); if (e.KeyChar == "L") { DBConnection.Open(); } if (DBConnection.State == ConnectionState.Open) { if (textBox1.Text.Length != 7) return; { //cmd.CommandText = ("SELECT last_name +', '+ first_name +'\t ('+major_key+')\t' from name where id =@Name"); cmd.CommandText = ("SELECT last_name +', '+ first_name from name where id =@Name"); cmd.Parameters.Add(new SqlParameter("Name", textBox1.Text.Replace(@"L", ""))); cmd.CommandType = CommandType.Text; cmd.Connection = DBConnection; // sqlConnection1.Open(); returnValue = cmd.ExecuteScalar() + "\t (" + textBox1.Text.Replace(@"L", "") + ")"; DBConnection.Close(); if (listBox1.Items.Contains(returnValue)) { for (int n = listBox1.Items.Count - 1; n >= 0; --n) { string removelistitem = returnValue.ToString(); if (listBox1.Items[n].ToString().Contains(removelistitem)) { listBox1.Items.RemoveAt(n); //listBox1.Items.Add(removelistitem+" " +TimeOut+ Time); } } } else listBox1.Items.Add(returnValue); System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(fullFileName); foreach (object item in listBox1.Items) SaveFile.WriteLine(item.ToString()); SaveFile.Flush(); SaveFile.Close(); textBox1.Clear(); if (listBox1.Items.Count != 0) { DisableCloseButton(); } else { EnableCloseButton(); } Current_Attendance_Label.Text = "Currently " + listBox1.Items.Count.ToString() + " in attendance."; e.Handled = true; } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// else ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// { returnValue = textBox1.Text.Replace(@"*", ""); if (e.KeyChar == "*") return; { if (listBox1.Items.Contains(returnValue)) { for (int n = listBox1.Items.Count - 1; n >= 0; --n) { string removelistitem = returnValue.ToString(); if (listBox1.Items[n].ToString().Contains(removelistitem)) { //listBox1.Items.RemoveAt(n); } } } else listBox1.Items.Add(returnValue); textBox1.Clear(); System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(fullFileName); foreach (object item in listBox1.Items) SaveFile.WriteLine(item.ToString()); SaveFile.Flush(); SaveFile.Close(); if (listBox1.Items.Count != 0) { DisableCloseButton(); } else { EnableCloseButton(); } Current_Attendance_Label.Text = "Currently " + listBox1.Items.Count.ToString() + " in attendance."; e.Handled = true; } } }
-4596520 0 Performance isn't really a consideration, assuming that you're not talking about gigabytes of XML. Yes, it will take longer (XML is more verbose), but it's not going to be something that the user will notice.
The real issue, in my opinion, is support for XML within JavaScript. E4X is nice, but it isn't supported by Microsoft. So you'll need to use a third-party library (such as JQuery) to parse the XML.
-39123566 0Something like this.
select name,math as Grade from your_table union all select name,English as Grade from your_table union all select name,Arts as Grade from your_table
-34345294 0 Is it possible to use socket.io between NodeJS and AngularJS I have two independent applications (frontEnd and BackEnd). The backEnd is in NodeJS using express framework and the FrontEnd is in AngularJS. Is it possible to use socket.io to send a message from the server (NodeJS) to the client (AngularJS)? How I can do that? I've tried with the following code but it is not working:
server code
var app = require('express')(); var server = require('http').Server(app); var io = require('socket.io')(server); io.sockets.on('connection', function(socket) { //This message is not showing console.log("socket"); socket.volatile.emit('notification', {message: 'push message'}); }); client code
angular.module('pysFormWebApp') .factory('mySocket', function (socketFactory) { var mySocket = socketFactory({ prefix: 'foo~', ioSocket: io.connect('http://localhost:3000/') }); mySocket.forward('error'); return mySocket; }); angular.module('formModule') .controller('typingCtrl', ['$scope', 'mySocket', typingCtrl]); function typingCtrl ($scope, mySocket) { mySocket.forward('someEvent', $scope); $scope.$on('socket:someEvent', function (ev, data) { $scope.theData = data; console.log(data); }); thanks for the help
-31295261 0 How to get token from server BrainTreeHow do I get the token from my server? I went the tedious process of simply getting the token to appear on my server but now I don't know how to pull it down and use it in my Android app. This is the method that Braintree suggested and it had a boat load of errors when I copied and pasted it. I managed to get past them but I had to implement a few methods that I don't think are right.
All I need to be able to do is get the client token and use as a variable in my app. Someone please help. P.S. I'm really new at Android dev.
import android.content.Intent; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import com.loopj.android.http.*; import com.braintreepayments.api.dropin.BraintreePaymentActivity; import org.apache.http.Header; public class MainActivity extends ActionBarActivity { private int REQUEST_CODE; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } AsyncHttpClient client = new AsyncHttpClient(); public void fetchClientToken() { client.get("http://clomes.com/clomes/braintree/customer/gettoken", new TextHttpResponseHandler() { public String clientToken; @Override public void onFailure(int i, Header[] headers, String s, Throwable throwable) { } @Override public void onSuccess(int i, Header[] headers, String clientToken) { this.clientToken = clientToken; } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
-34797753 0 The argument you're passing to pattern = is where things are going wrong I believe. This three-step approach might get you the desired result:
# Extract all .rds files list <- list.files("Data/", pattern =".rds", full.names = TRUE) # Define pattern for grepl files <- c(20388, 20389, 20390) pattern <- paste(files, sep="", collapse="|") # Results in pattern [1] "20388|20389|20390" # grepl will interpret "|" as "or" # Now we can subset list with the following list[grepl(pattern,list)]
-1918219 0 You can have each tab be a real view controller with nib and everything. The only catch is that you must forward on the standard view controller calls you want to receive (viewWillAppear, etc) but it makes the coding much cleaner since you code just as you would for any other view (although for a smaller space).
You call each controllers "view" property to get out the view, which you add as a subview of a container view you have under the tabs.
-24750005 0 how to retain the animated position in opengl es 2.0I am doing frame based animation for 300 frames in opengl es 2.0
I want a rectangle to translate by +200 pixels in X axis and also scaled up by double (2 units) in the first 100 frames. For example, the initial value (frame 0) of the rectangle's centre point is at 100 pixels (i.e. rectCenterX = 100) on the screen; At 100th frame, rectCenterX = 300 (100 + 200) pixels. Also the rect size is doubled the original size.
Then, the animated rectangle has to stay there for the next 100 frames (without any animation). i.e. the rectCenterX = 300 pixels for frames 101 to 200. At 101st frame, rectCenterX = 300 pixels. the rect size is double the original size. At 200th frame, rectCenterX = 300 pixels. the rect size is double the original size.
Then, I want the same animated rectangle to translate by +200 pixels in X axis and also scaled down by half (0.5 units) in the last 100 frames. At 300th frame, rectCenterX = 500 pixels.the rect size is again as the original size.
I am using simple linear interpolation to calculate the delta-animation value for each frame.
In short,
Animation-Type Animation-Value Start-Frame End-Frame 1.Translate +200 0 100 2.Scale +2 0 100 3.Translate +200 201 300 4.Scale +0.5 201 300 Pseudo code: The below drawFrame() is executed for 300 times (300 frames) in a loop.
float RectMVMatrix[4][4] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; // identity matrix int totalframes = 300; float translate-delta; // interpolated translation value for each frame float scale-delta; // interpolated scale value for each frame // The usual code for draw is: void drawFrame(int iCurrentFrame) { // mySetIdentity(RectMVMatrix); // comment this line to retain the animated position. mytranslate(RectMVMatrix, translate-delta, X_AXIS); // to translate the mv matrix in x axis by translate-delta value myscale(RectMVMatrix, scale-delta); // to scale the mv matrix by scale-delta value ... // opengl calls glDrawArrays(...); eglswapbuffers(...); } The above code will work fine for first 100 frames. in order to retain the animated rectangle during the frames 101 to 200, i removed the "mySetIdentity(RectMVMatrix);" in the above drawFrame().
Now on entering the drawFrame() for the 2nd frame, the RectMVMatrix will have the animated value of first frame
e.g. RectMVMatrix[4][4] = { 1.01, 0, 0, 2, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 };// 2 pixels translation and 1.01 units scaling after first frame This RectMVMatrix is used for mytranslate() in 2nd frame. The translate function will affect the value of "RectMVMatrix[0][0]". Thus translation affects the scaling values also.
Eventually output is getting wrong.
How to retain the animated position without affecting the current ModelView matrix?
-4250568 0I use successfully the following procedure to get images with SmartGWT working.
At the same level as the client package of your GWT module I create a folder named public. (In Eclipse you cannot create a package named public because this is not a valid package name. You have to create it explicitly as a folder.) This directory with name public is treated special by GWT. The GWT compiler copies all the included content to the resulting main module directory. So I usually create a subdirectory images under public and put all the images belonging to my GWT module in there.
For example:
com/stuff client Main.java ... public images a.png b.png mainmodule.gwt.xml Then right at the beginning of the entry point I tell SmartGWT to look at the images subdirectory for the images (in this example is mainmodule the name of my main GWT module):
public void onModuleLoad() { Page.setAppImgDir("[APP]/mainmodule/images/"); ... } The [APP] part of the path is special SmartGWT syntax.
Later I am able to create an IButton like so:
final IButton aBtn = new IButton("A Button"); aBtn.setIcon("a.png"); Sometimes it is necessary to create the URL to an image not for SmartGWT but for plain GWT or plain HTML. For these cases you can create the URL with
final String bUrl = GWT.getModuleBaseURL() + "images/b.png";
-25871007 0 Cross-year DatePeriod width DateInterval P7D losing new year week I'm trying to have an array of yearweeks using PHP DatePeriod like so :
$from = new DateTime('2014-09-16'); $to = new DateTime('2015-02-25'); $interval = new DateInterval('P7D'); // 7Days => 1 Week $daterange = new DatePeriod($from, $interval, $to); $yearweeks = array(); foreach($daterange as $date) { $yearweeks[$date->format('YW')] = 'W' . $date->format('W-Y'); } The result is pretty strange ! The first week of the new year is missing. I have fist week of previous year instead like so :
Array ( ... [201451] => W51-2014 [201452] => W52-2014 [201401] => W01-2014 // WTF ? /!\ [201501] => W01-2015 expected ! /!\ [201502] => W02-2015 [201503] => W03-2015 ... ) Is there a trick to avoid this kind of error ?
-22654622 0 Sublime2: Unable to change translate_tabs_to_spaces settingI want HTML files to have a 2 space indent so I've updated my Packages/User/html.sublime-settings file as follows:
{ "extensions": [ "erb", "html" ], "tab_size": 2, "translate_tabs_to_spaces": true, } However, whenever I save a file as an HTML file (i.e. with the .html extension) the Tab Size remains 4.
What else do I need to change?
-893757 0 Exporting X.509 certificate WITHOUT private key (.NET C#)I thought this would be straightforward but apparently it isn't. I have a certificate installed that has a private key, exportable, and I want to programmatically export it with the public key ONLY. In other words, I want a result equivalent to selecting "Do not export the private key" when exporting through certmgr and exporting to .CER.
It seems that all of the X509Certificate2.Export methods will export the private key if it exists, as PKCS #12, which is the opposite of what I want.
Is there any way using C# to accomplish this, or do I need to start digging into CAPICOM?
Thanks,
Aaron
-27323000 0 Error building Android app in release mode, in Android StudioI'm trying to sign my android app in release mode, in Android Studio.
I followed this official guide. So I have created the keystore and a private key. Then I tried to Generate the Signed APK, from Build -> Generate Signed API Key. But the build fails, with the following error:
:app:packageRelease FAILED Error:A problem was found with the configuration of task ':app:packageRelease'. > File 'C:\Documents\myapp\android.jks' specified for property 'signingConfig.storeFile' does not exist. I have also checked the build.gradle configuration. And I have found this:
signingConfigs { releaseConfig { keyAlias 'xxxxxxxxxx' keyPassword 'xxxxxxxxx' storeFile file('C:\Documents\myapp\android.jks') storePassword 'xxxxxxxxx' } } but in the same gradle file I have this:
buildTypes { release { runProguard false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' signingConfig signingConfigs.releaseConfig } } What's wrong?
-25278941 0Or using @Brandon Bertelsen's example data
dat1 <- transform(dat[grep("^\\d+$", dat$A),,drop=F], A= as.numeric(as.character(A))) dat1 # A #6 1 #7 2 #8 3 #9 4 #10 5 str(dat1) #'data.frame': 5 obs. of 1 variable: #$ A: num 1 2 3 4 5
-2387347 0 Try this:
/\b\w{3,16}\b/ Explained:
\b matches a word boundary\w matches a word character{3,16} applies to the \w and it indicates that at least 3 and at most 16 characters should be matched.FYI: I omitted the start anchor (^) and end anchor ($) from the regex you noted in your question because it seems like you want to find matches with longer strings of text as input and the anchors would restrict the matching to only instances where the entire input string matched.
UPDATE:
Here is the proof that this regex works:
<?php $input = 'rjm1986 * SinuhePalma * excel2010 * Jimineedles * 209663603 * C6A7XR * Snojog * XmafiaX * Cival2 * HitmanPirrie * MAX * 4163016 * Dredd23 * Daddy420 * mattpauley * Mykillurdeath * 244833585 * KCKnight * Greystoke * Fatbastard * Fucku4 * Davkar * Banchy2 * ET187 * Slayr69 * Nik1236 * SeriousAl * 315791 * 216996334 * K1ra * Koops1 * LastFallout * zmileben * bismark * Krlssi * FuckOff1 * 1owni * Ulme * Rxtvjq * halfdeadman * Jamacola * LBTG1008 * toypark * Magicman6497 * Tyboe187 * Bob187 * Zetrox'; $matches = array(); preg_match_all('/\b\w{3,16}\b/', $input, $matches); print_r($matches); ?> Outputs:
Array ( [0] => Array ( [0] => rjm1986 [1] => SinuhePalma [2] => excel2010 [3] => Jimineedles [4] => 209663603 [5] => C6A7XR [6] => Snojog [7] => XmafiaX [8] => Cival2 [9] => HitmanPirrie [10] => MAX [11] => 4163016 [12] => Dredd23 [13] => Daddy420 [14] => mattpauley [15] => Mykillurdeath [16] => 244833585 [17] => KCKnight [18] => Greystoke [19] => Fatbastard [20] => Fucku4 [21] => Davkar [22] => Banchy2 [23] => ET187 [24] => Slayr69 [25] => Nik1236 [26] => SeriousAl [27] => 315791 [28] => 216996334 [29] => K1ra [30] => Koops1 [31] => LastFallout [32] => zmileben [33] => bismark [34] => Krlssi [35] => FuckOff1 [36] => 1owni [37] => Ulme [38] => Rxtvjq [39] => halfdeadman [40] => Jamacola [41] => LBTG1008 [42] => toypark [43] => Magicman6497 [44] => Tyboe187 [45] => Bob187 [46] => Zetrox ) )
-7577616 0 MATLAB 7.0 provides the NTHROOT function, which returns the real roots of a number. So your formula becomes NTHROOT(-8, 3) = -2
If you are using a version prior to MATLAB 7.0 (R14), please read the following:
To obtain the real cube root of a negative real number "x", rather than executing:
x.^(1/3) use the command:
sign(x).*abs(x.^(1/3)) This will find the absolute value of the root and modify it by the sign of the argument.
-8076814 0In UIWebView delegate you can handle the navigation notification and prevent it; from the notification you will know the PDF URL, that will allow you to use NSURLConnection to download it.
-12580705 0 ASP.NET MVC and friendly URLsI'm trying to learn a bit more about creating friendly URLs, particularly in relation to something like an e-commerce site. If you take a look at this site as an example: http://www.wiggle.co.uk/
It basically lets you refine your search based on the categories. So if I go to http://www.wiggle.co.uk/mens/road-time-trial-bikes/ it will list all men's road bikes, if I then go to http://www.wiggle.co.uk/road-time-trial-bikes/ it will list men's and women's bikes, and if I go to http://www.wiggle.co.uk/bianchi-sempre-105/ it will display a particular bike.
I'm not really sure what the routing would look like for something like this, as you could have many filters in the URL. I'm also not sure how how it's able to distinguish between what's a filter and what's a product.
-13519338 0 PyDev "New Project" crashes EclipseI'm a Python and PyDev newbie. My environment is OS X 10.6.11, Eclipse Indigo, PyDev 2.7.1, Python 2.6 and 3.3.
Starting from any perspective (PyDev, Java, others), selecting New->Project->PyDev->PyDev Project results in an endless spinning color beachball. The only way out is to Force Quit Eclipse.
Starting from the PyDev perspective, if I select New->Project, and then select General->Project, the same crash occurs.
My only recourse seems to be to create a generic project from, say, the Java perspective, then right-click the project in the package explorer view and choose PyDev->Set as PyDev Project, then switch to the PyDev perspective, then configure the project folder manually.
Am I missing something in my installation? Is this a known problem with PyDev?
-10269164 0 how to use the postgres database embedded with Mac Lion?i can only find psql command, but can't find any other postgres commands or tools, can anyone tell me how to create database and connect to it using the default postgres shipped with mac lion?
only if it doesn't work ,i dont' want to install another postgres instance.
-15934544 0alright so this is what worked, the null characters in the array were causing issues and were returning the last null in the array so i forced the array to break after each if/else statement by putting x = memberAcc.length +1; and y = newMember.length +1; to do this. Causing the entire array to be checked and then forced to be broken allowing me to return to my Menu while loop.
-37907227 0Do it the same way like you did with your update, use SQL parameters for the where clause. So this code should work:
protected void Button2_Click(object sender, EventArgs e) { string sel = DropDownList1.SelectedValue; // if your selection is empty, abort early if( sel == null || string.IsNullOrEmpty(sel.Text)) return; // use a SQL parameter like you did with update string query = "DELETE FROM MovieList WHERE Movie=@MovieValue"; System.Data.OleDb.OleDbCommand ocmd = new System.Data.OleDb.OleDbCommand(query, new System.Data.OleDb.OleDbConnection(CSTR)); // here the selected text for the movie is set to the movie parameter ocmd.Parameters.AddWithValue("@MovieValue", sel.Text); ocmd.Connection.Open(); ocmd.ExecuteNonQuery(); ocmd.Connection.Close(); populateDropDowns(); }
-11075254 0 Passing js array to PHP Possible Duplicate:
Passing a js array to PHP
i'm stuck jQuery $.post() method, i can't access my through PHP $_POST and I can't figure out why.
Here is the js:
<script type="text/javascript"> var selectedValues; $("td").click(function() { $(this).toggleClass('selectedBox'); selectedValues = $.map($("td.selectedBox"), function(obj) { return $(obj).text(); }); // $.post('/url/to/page', {'someKeyName': variableName}); //exemple $.post('handler.php', {'serializedValues' : JSON.stringify(selectedValues)}, function(data) { //debug } ); }); </script> And here is the PHP file:
<?php if(isset($_POST['serializedValues'])) { var_dump($_POST['serializedValues']); $originalValues = json_decode($_POST['serializedValues'], 1); print_r($originalValues); } ?> When I issue a console.log(selectedValues) after selecting some of the td element, it return me this for exemple:
[" 3 ", " 4 "] Something else, when I inspect the sent header through XHR, i get this:
serializedValues:[" 3 "," 4 "] And finally, in php var_dump($_POST) still returns me nothing :(
Some hints ? Thanks in advance :)
-4402022 0Neither are a direct port, but of the two -- MySQL's syntax is more similar to SQL Server's than PostgreSQL.
SQL Server 2000 didn't have analytic/ranking/windowing functionality -- neither does MySQL currently. Also, no WITH/CTE support - again, MySQL doesn't support this either. If you were migrating away from SQL Server 2005+, I'd have recommended PostgreSQL 8.4+ for the sake of either of the two things I just mentioned.
-20088539 0 Corona SDK with Graphic 2.0 position not workingI have upgraded my Corona SDK version to 2013.2076 (with Graphic 2.0). But now my background images are not working and the app is crashing.
local background = display.newImageRect("/bg.png", 570, 360 ) background:setReferencePoint( display.CenterReferencePoint ) background.x = display.contentCenterX ; background.y = display.contentCenterY gameGroup:insert(background) It is working perfectly in previous version of Corona SDK. I am not being able to identify the issue. Please help
-28608607 0Main thread
TSimpleEvent will suffice for your needs.TSimpleEvent that's a call to ResetEvent. I expect that a newly minted TSimpleEvent would be in the non-signaled state, but off the top of my head I cannot remember that detail.TSimpleEvent that means calling WaitFor.Worker thread
TSimpleEvent that means calling SetEvent.You problem is explained in the logcat :
android.widget.ImageView cannot be cast to android.widget.TextView And by looking at the next line of your Logcat you can see where it happened:
at com.nando.gridview.Dialog.onCreate(Dialog.java:21) So change the following:
TextView DialogText=(TextView) findViewById(R.id.imageViewDialog); Into this:
TextView DialogText=(TextView) findViewById(R.id.idofyourtextview);
-35731063 1 Compare two columns of two different dataframes Recently, I switched from matlab to python with pandas. It has been working great, but i am stuck at solving the following problem efficiently. For my analysis, I have to dataframes that look somewhat like this:
dfA = NUM In Date 0 2345 we 1 01/03/16 1 3631 we 1 23/02/16 2 2564 we 1 12/02/16 3 8785 sz 2 01/03/16 4 4767 dt 6 01/03/16 5 3452 dt 7 23/02/16 6 2134 sz 2 01/03/16 7 3465 sz 2 01/03/16 and
dfB In Count_Num 0 we 1 3 1 sz 2 2 2 dt 6 3 3 dt 7 1 What I would like to perform is a an operation that sums all 'Num' for all "In" in dfA and compares it with the "Count_num" in dfB. Afterwards, I would like to add an column to dfB to return if the comparison is True or False. In the example above, the operation should return this:
dfB In Count_Num Check 0 we 1 3 True 1 sz 2 2 False 2 dt 6 1 True 3 dt 7 1 True My approach:
With value_counts() and pd.DataFrame, I constructed the following dfC from dfA dfC =
In_Number In_Total 0 we 1 4 1 sz 2 3 2 dt 6 1 3 dt 7 1 Then I merged it with dfB to check it afterwards if the values are the same by comparing the columns within dfB. In this case, I have to end dropping the columns. Is there a better/faster way to do this? I think there is a way to do this very efficiently with one of pandas great functions. I've tried to look into lookup and map, but I can not make it work.
Thanks for the help!
-5357951 0I have finally found my own answer again. Basically, it came down to restart intellij and the plugin will show under plugins. For some reason while doing "Grails/Synchronize Grails Settings" was not making the plugin show up.
So to successfully install the gails mail plugin do as follows
Change the database tables collations types to utf8_general_ci and also table fields collations change to utf8_general_ci.
I have a Asp.Net Mvc application that has a default route pattern of /controller/action/id.
This means the user could simply put any ID in the url if they are savy enough to figure it out. I could handle the exceptions, redirect the user to an error page (and I am) or any number of other solutions. There are only about 1200 possible valid IDs. I was considering caching a list of these IDs at the application level to check against before querying the database to save the expense of making a connection and handling the exceptions.
Does anyone have a good argument as to why this is a bad solution?
-38313504 0You can avoid division by zero while maintaining performance by using advanced indexing:
x = np.arange(-500, 500) result = np.empty(x.shape, dtype=float) # set the dtype to whatever is appropriate nonzero = x != 0 result[nonzero] = 1/x[nonzero] result[~nonzero] = 0
-33657969 0 Bluemix logging issue to papertrail Any idea why syslog:// protocol from bluemix app is not connecting to PaperTrail third party logging service?
Here is my process:
then on the papertrail nothing happens:
You can try it out. The testing app URL is: http://658.eu-gb.mybluemix.net
Its just Hello world simple nodejs app.
-316863 0One solution that I feel strikes the right balance in the Framework/Roll-your-own dilemma is the use of three key perl modules: CGI.pm, Template Toolkit , and DBI. With these three modules you can do elegant MVC programming that is easy to write and to maintain.
All three modules are very flexible with Template Toolkit (TT) allowing you to output data in html, XML, or even pdf if you need to. You can also include perl logic in TT, even add your database interface there. This makes your CGI scripts very small and easy to maintain, especially when you use the "standard" pragma.
It also allows you to put JavaScript and AJAXy stuff in the template itself which mimics the separation between client and server.
These three modules are among the most popular on CPAN, have excellent documentation and a broad user base. Plus developing with these means you can rather quickly move to mod_perl once you have prototyped your code giving you a quick transition to Apache's embedded perl environment.
All in all a compact yet flexible toolset.
-24514831 0It would be helpful if you showed the SQL statement that returns the results.
Are the returned arrays in separate $row results?
In that case you need to iterate through each $row result, something like:
foreach($query->result() as $row) { for ($p=1; $p<=2; $p++) { echo number_format($row["novhigh_".$p],2); } } On a side note: It looks like the key definition inside the arrays is not logical, why not have the same key value for the "novhigh" element?
-3328519 0 Retrieve Data Step by Step after a certain delay using ajax and jquery in phpI am a beginner at Jquery. What i want is to display the data using AJAX in a step by step manner. So let say if in my database there is a table "DATA" with a field name "info" having multiple rows as a data
1 2 3 4 5
Now i want to display all the five rows but after a certain delay of time let say after a second.
So i want to use Jquery with AJAX to retrieve data from mySQL table and display each row after a second.
Please provide an example for solving this problem. Thanks in Advance...
-40929170 0 How to order by one column in one table and another column in other table ,but in a single query?I tried two queries which work fine individually:
1) select * from {disputeticket} ORDER BY {creationtime} ASC
The query is working , here FK=PK of CsTicketState (Column name=State)
2) select * from {CsTicketState} where order by {SEQUENCENUMBER} asc
This one also works, here PK(column name)
I need to have both on a single query. Sequence number is 0,1,2
I tried the below query but only the first part is getting sorted, not the second part.
select {dp:pk},{dp:ticketid},{dp:state},{cts:code},{cts:sequencenumber} from {disputeticket as dp join CsTicketState AS cts on {dp:state}={cts:pk}} ORDER BY {cts:sequencenumber},{dp:creationtime} ASC
-36441900 0 2) I've already answered similar question here:
If you are using 1 thread, for example, in EventLoopGroup for boss group for 2 different bootstraps, it means that you can't handle connections to this bootstraps simultaneously. So in very very bad case, when boss thread handle only connections for one bootstrap, connections to another will never be handled.
Same for workers EventLoopGroup.
3) You can do it, and it will work fine. But same as in 2: you can't handle server response simultaneously. If it's ok for you, do it.
-9276418 0You have probably used the dir attribute/CSS set to rtl instead of proper CSS alignment.
The dir attribute:
This attribute specifies the base direction of directionally neutral text (i.e., text that doesn't have inherent directionality as defined in [UNICODE]) in an element's content and attribute values. It also specifies the directionality of tables.
As you can see this is not limited to alignment.
Use CSS alignment/positioning to align HTML controls.
-9704131 0You 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 Same to your discriminated union, which first derives specific union case from the instance self and then constructs a new instance by the same union case, but now populated with newVal:
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 Now applying it to lowPrice value below
let lowPrice = Euro(100) let highPrice = lowPrice.Same 200 you'll get highPrice : Currency = Euro 200
As @CBroe points out, this isn't supported by the Facebook Graph API. (It can be done using FQL, but that's deprecated and won't be supported for much longer).
That said, with some creativity (and a bit extra code) a similar effect can be achieved by combining a couple of queries.
In my application, I perform a query with the following parameters:
until=2015-07-07 (or whatever the since date would have been)fields=updated_time (to keep the query fast and the payload small)limit=5000 (or some similarly large page size, as I'm only grabbing one field)I then evaluate each post that has an updated_time greater than the would-be since date, and throw those posts into a queue to download the entirety of the post content.
Note: If you're dealing with content where there are frequent updates on past content, you'd likely want to use the Graph API's Batch Requests feature, as opposed to downloading each post individually.
So, for example, if the until (and, thus, since) date is 2015-07-07 and the updated_time on a post is 2015-10-15, then I know that post was created prior to 2015-07-07 but updated afterwards. It won't get picked up in a since query, but I can easily download it individually to synchronize my cache.
i have implemented a kendo grid as shown below , paging works without any issues but sort not work. Could you please help
CSHTML
<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> Controller
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); }
-11983857 0 SQL query to select max value of a varchar field I want to select the max value of a varchar field and increment its value by 1 retaining its original format ..
Customer ID for ex. : CUS0000001 is the value
add 1 to it and then enter it into the database along with other details.
So the result should be like CUS0000002 ..
This is what I have tried and in fact achieved what I want ..
But is this the best way to do it ??
SELECT CONCAT('CUS', RIGHT(CONCAT('000000', CONVERT((CONVERT(MAX(RIGHT(customer_id, 7)) , UNSIGNED) + 1), CHAR(10))), 7)) AS customer_id FROM customer_master
-33454385 0 No. Symbols must be accessed using bracket notation.
Dot notation is only used for string keys that follow certain rule patterns, mostly about being a valid identifier.
Symbols are not strings, they are a whole something else entirely.
Short rational: One of the design goals of symbols is that they can not clash with property names, that makes them safe to use.
So, if you had an object like this
var = { prop1: "Value" }; And you created a symbol called prop1, how could you tell the two apart, and access them differently, using just object notation?
I want to replace one scene with another with fade out - fade in effect.(old scene fades out(to the black screen),and then new scene fades in).
i found solution manually to decrease opacity of one scene and then launch
[[CCDirector sharedDirector] replaceScene:[HelloWorld scene]]; But i suppose there is another solution with the use of actions. Please, help me)
-11884852 0Do 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)
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];
-36806947 0 Ng-repeat not updating with array changes I have looked over this issue for many hours and read many other questions that seem entirely the same and I have tried every one of their solutions, but none seem to work.
I have an array of objects (instructionObj.instructions) and those objects get repeated with ng-repeat and their template is a directive.
<div instruction-directive ng-repeat="i in instructionsObj.instructions"> </div> I then allow the items to be sorted using Jquery UI sortable.
var first, second; $( ".sort" ).sortable({ axis: "y", start: function( event, ui ) { first = ui.item.index(); }, stop: function( event, ui ) { second = ui.item.index(); console.log(first + " " + second); rearrange(first, second); $scope.$apply(); } }); I then access the start and end index of the object being moved and rearrange the array accordingly:
function rearrange(f, s){ $timeout(function () { $scope.instructionsObj.instructions.splice(s, 0, $scope.instructionsObj.instructions.splice(f, 1)[0]); $scope.$apply(); }); } All of this works great most of the time. The one scenario I have found a failure is when rearranging the objects as such (one column is the current position of all objects displayed on the screen):
a | b | c | d | a
b | c | d | c | b
c | d | b | b | d
d | a | a | a | c
The last step should be a, d, c, b. But it changes to a, b, d, c.
However, when I go back to my previous view and come back the correct configuration is displayed, all is well. As you can see I have tried $timeout and $apply() and many other things, but none seem to work.
I know this is a DOM updating issue because I can log the array and see that it is different (correct) from what the DOM shows (incorrect). Any help would be appreciated.
Update:
I am even using <pre ng-bind="instructionsObj.instructions|json</pre> to show the exact layout of the array and it is always correct. My mind is blown.
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
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 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.
That way you can bring in COLX values from the highest RANK records from Table B that match the records of Table A.
I think at least...
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
-1263878 0 If your regex engine has lookbehind assertions then you can just add a "(?<!\.)" before the "@".
-18592902 0 Writing UART ApplicationI have been asked to understand the 16550A UART for Linux (3.10 Kernel)and write some test case on its functional blocks.But before that only i am facing lot of troubles in understanding the code flow of the same as it is very big ( I am following kernel 3.10 version) with multiple entry points and exit points.So i thought of writing a UART Application (C Program) having two threads which will transmit and receive characters to the UART port and understand the code flow by printing the log messages. Now I am not getting how to start writing application which would do the same. Also If anyone can help me in getting the first part of the my task (writing test cases) that would be great. And also can you provide me with some of the good links related to UART. Thanks
-18028548 0Just put that in your hosts file and you won't have to worry about DNS.
But really, doesn't it make more sense to use an ENV var?
-8593533 0This is a fairly common problem.
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.
Note, that since pipe reads and writes of less then or equal to PIPE_BUF 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.
mysql_insert_id(); That's it :)
-4052499 0 Existing List of W3C complient html attributeIt's there a place i can see wich attribute are w3c on all HTML Element, div,p,a,li,hr etc ...
I check on w3cshool but find nothing.
I need a list where they said someting like ... id : (div, a , hr , etc ...), class (div, a , hr , etc) ...
-22470118 0You are not passing any parameters to the query.
Instead of:
cur.execute('INSERT INTO report_table (id, date, time, status) VALUES (id, date, time, status)') create a parameterized query:
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}) There are other fixes you should apply to the code:
db and cursor variables before the loop so that you don't need to connect to the database and open a cursor on every iterationINSERT database query on each iteration step, consider gathering the data into a list and then insert once after the loopHope that helps.
-27939800 0Try attribute colorControlActivated:
themes.xml
<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>
-30224687 0 It looks like you are sending two independent events (two calls to tracker.send). One with only custom dimensions and one without custom dimensions. The first event is invalid as it is missing required event category and action so Analytics will ignore it. The second is valid event but its missing the custom dimensions. You should send only one event instead:
tracker.send(new HitBuilders.EventBuilder() .setCategory("customCategory") .setAction("customAction") .setLabel("customLabel") .setCustomMetric(cm.getValue(), metricValue) .setCustomDimension(cd.getValue(), dimensionValue) .build());
-7245634 0 Deactivate line feed with css of tag 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?
-23733985 0Use ng-class and call a function on your controller that does the check:
$scope.getClass = function(text) { return text.slice(-1) === '!' ? 'error':''; } Update:
<div ng-class="(message.text.slice(-1) === '!' ? 'error':'')">{{message.text}}</div>
-34999434 0 maven-release-plugin deploying SNAPSHOT I have a Maven project and now want to release it with the maven-release-plugin. Unfortunately after executing mvn release:prepare 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.
I already found this bug, but all suggested solutions are not working for me.
I'm using:
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?
EDIT1: The current pom.xml
<?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>
-30857018 0 The code you've posted will run on the Hadoop master node. scaldingTool.run(args) will trigger your job, which would trigger the jobs that execute on task nodes.
Look for sources titled "C for Scientists" or "C for engineers". The first google hit contains answers to your questions: (http://www2.warwick.ac.uk/fac/sci/physics/current/teach/module_home/px270/week2/week_2a.pdf).
Have also a look at (http://sccn.ucsd.edu/labinfo/computer-faq/Numerical_Recipes.html), your paths may be different.
-25024471 0You are saving your model query results in a specific key(assistiti) inside the array $data, and then you are fetching the whole array in the foreach loop. This way, you got to loop through the specific array, inside the array $data:
foreach($data['assistiti'] as $post){ $nome = $post->nome; $cognome = $post->cognome; $tribunale = $post->tribunale; $tbl .= '<tr><td style="border:1px solid #000;text-align:center">'.$nome.'</td>'; $tbl .= '<td style="border:1px solid #000;text-align:center">'.$cognome.'</td>'; $tbl .= '<td style="border:1px solid #000;text-align:center">'.$tribunale.'</td> </tr>'; ;} $pdf->writeHTML($tbl_header.$tbl.$tbl_footer , true, false, false, false, '');
-5236157 0 A reverse_iterator internally stores a normal iterator to the position after its current position. It has to do that, because rend() would otherwise have to return something before begin(), which isn't possible. So you end up accidentally invalidating your base() iterator.
-35538912 0 Peewee select with circular dependencyI have two models Room and User. Every user is assigned to exactly one room and one of them is the owner.
DeferredUser = DeferredRelation() class Room(Model): owner = ForeignKeyField(DeferredUser) class User(Model): sessid = CharField() room = ForeignKeyField(Room, related_name='users') DeferredUser.set_model(User) Now, having sessid of the owner I'd like to select his room and all assigned users. But when I do:
(Room.select(Room, User) .join(User, on=Room.owner) .where(User.sessid==sessid) .switch(Room) .join(User, on=User.room)) It evaluates to:
SELECT "t1".*, "t2".* # skipped column names FROM "room" AS t1 INNER JOIN "user" AS t2 ON ("t1"."owner_id" = "t2"."id") INNER JOIN "user" AS t2 ON ("t1"."id" = "t2"."room_id") WHERE ("t2"."sessid" = ?) [<sessid>] and throws peewee.OperationalError: ambiguous column name: t2.id as t2 is defined twice.
What I actually need to do is:
room = (Room.select(Room) .join(User.sessid=sessid) .get()) users = room.users.execute() But this is N+1 query and I'd like to resolve it in a single query like:
SELECT t1.*, t3.* FROM room AS t1 INNER JOIN user AS t2 ON t1.owner_id = t2.id INNER JOIN user as t3 ON t3.room_id = t1.id WHERE t2.sessid = ?; Is there a peewee way of doing this or I need to enter this SQL query by hand?
-9786736 1 How to read through collection in chunks by 1000?I need to read whole collection from MongoDB ( collection name is "test" ) in Python code. I tried like
self.__connection__ = Connection('localhost',27017) dbh = self.__connection__['test_db'] collection = dbh['test'] How to read through collection in chunks by 1000 ( to avoid memory overflow because collection can be very large ) ?
-8981820 0 clueTip is a jQuery plugin for displaying stylized tooltips -4060332 0On Android it's best to use AsyncTask to execute tasks in the background while (progressively) updating UI with results from this task.
Edited:
After checking code I think your Handler works correctly. Probably problem is in UpdateDisplay(). Since you are updating display from background thread, make sure you call [view.postInvalidate()][2] after you're done updating your View.
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.
#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
-2869472 0 As long as you are inside the EnumTest class, you can access the LEN field by simply writing:
int len = RecordType1.LEN; From the outside, it's still difficult.
-482882 0Another 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.
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.
-1071106 0 Do web apps encrypt passwords during login when integrated security is enabled within IIS?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.
-10532652 0If the Delphi function is declared as being stdcall, why would you declare it in C# as cdecl?
This is the cause of the stack imbalance. Change your C# declaration to use the stdcall convention to match the Delphi declaration.
[UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate double WriteRate(object data);
-22221362 0 we can set an empty array to the Filtering select widgets store.
dijit.byId('widgetId').store.data.splice(0,dijit.byId('widgetId').store.data.length); or simply,
dijit.byId('widgetId').store.data = []; Or you can set the store itself as null. (But, to add new options after this, you need to recreate the store again, before adding up the new options).
dijit.byId('widgetId').store = null;
-33332700 0 If you look at Pascal's triangle as a matrix, and you want to find the complexity of building that matrix up to size n x k, then the big-oh of that will be O(n*k). Obviously you can't get better than that, because that's the size of the matrix.
How do we get that? Use the following simplified recurrence for combinations:
C(n, k) = C(n - 1, k) + C(n - 1, k - 1) Computing just a single combination has the same complexity (if using memoization).
-6312307 0For the applet to find the libraries, they must be reachable by HTTP. Putting them in the library directory of you web application does not help.
-38510941 0You can loop through your array elements and add <tr> to them for each row.
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; <table id="myTable"></table> Assuming you want the 10 most recent eve_Dates for each customer.
untested I'm thinking the correlated subquery will generate a result set for each customer, but I'm not positive about that.
I don't think you were limiting to the 10 records because you had no join on date.
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
-15099432 0 I added a project file and some other small changes which are needed to build ZXing.Net for PCL. You can get it from the source code repository at codeplex. You have to build your own version because at the moment there is no pre built binary. Next version will include it. The restriction of the PCL version is that you have to deal with RGB data. You can't use platform specific classes like Bitmap, WriteableBitmap, BitmapSource or Color32.
-16549700 0Just add the focus() trigger after the value is set, like so:
$('#social-url').val("http://www.twitter.com/").focus(); Here's how I'd do it:
$(document).ready(function() { $('select').on('change', function() { $('#social-url').val("http://www." + this.value.toLowerCase() + ".com/") .focus(); }); });
-36406419 0 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.
-15155967 0The relevant part for you is the following one:
You should only grant permission to use the PHP filter to people you trust.
There are always risk of exposing a site to possible attacks when writing code, and in fact the Drupal security team's task is to report security holes to the module maintainers to fix them.
With the PHP filter, the more immediate risk is that users who use it have access to any database table. It would be easy for somebody to change the user account's password, change the ownership of a node, etc.
but i can't find any tutorial which links sql server with cordova app, all i can find is with SQLite or MySQL. I want to connect my local DB with the app directly.
Currently there is no way to connect to sql server directly in Cordova.
You need to implement a service layer for data exposion of your database. You can leverage mssql for node if you are familar with javascript. Alternatively, ASP.Net Web API is a good choice, if you are more familar with .Net.
Whatever the technology you use to build the service layer. It will eventually be consumed by your cordova app through Ajax.
-388509 0protected void MyListView_DataBind(object sender, ListViewItemEventArgs e){ if(e.Item.ItemType == ListViewItemType.DataItem){ MyObject p = (MyObject)((ListViewDataItem)e.Item).DataItem; } } You'll want to do the type check so that you don't try and do a cast when you're working on say, the header item.
-16117683 0 Before onCreateView startsIn PageFragment; I inflate a layout in onCreateView. But I want to inflate this layout before onCreateView loads. It could be inflated one time / or for every fragment; not important.
How can I achieve it ?
public class PageFragment extends Fragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.page_quiz, container, false); tv = (TextView) view.findViewById(R.id.Text); LinearLayout ll = (LinearLayout) view.findViewById(R.id.questionList); return view; } }
-32574686 0 It should be as easy as adding the file to your extension target/project so that both are part of the same module. Same module means internal scope and the constant should be accessible from the other file automatically.
-15679604 0your codes looks fine.... but i think your are missing the document.ready function
try this
jQuery(function(){ //ready function jQuery('nav').on('click', 'a', function(event){ console.log(jQuery(this)); }); });
-4965093 0 In your app delegate, look for this line:
EAGLView *glView = [EAGLView viewWithFrame:[window bounds] pixelFormat:kEAGLColorFormatRGB565 // kEAGLColorFormatRGBA8 depthFormat:0 // GL_DEPTH_COMPONENT16_OES ]; or search for
EAGLView *glView and you will find it..
-23752112 0If you want to limit only one dimension then just do not limit the other:
component.setMaximumSize( new Dimension( Integer.MAX_VALUE, requiredMaxHeigth ) );
-24001849 0 Dependency Injection / Polymorphism in Objective C Can I use Objective C protocols the same way I would use Java interfaces for Dependency Injection or Polymorphism?
It seems like I cannot. Note that in (1) below I have to type the property as the implementation rather than as the protocol. I get a compiler error if I use the protocol as the property type.
(1) The object to have dependencies injected into:
#import <Foundation/Foundation.h> #import "FOO_AccountService.h" #import "FOO_BasicAccountService.h" @interface FOO_ServiceManager : NSObject @property (nonatomic, strong) FOO_BasicAccountService <FOO_AccountService> *accountService; ... @end (2) The protocol:
#import <Foundation/Foundation.h> #import "FOO_Service.h" @protocol FOO_AccountService <FOO_Service> ... @end (3) The implementation:
#import <Foundation/Foundation.h> #import "FOO_BasicService.h" #import "FOO_AccountService.h" @interface FOO_BasicAccountService : FOO_BasicService <FOO_AccountService> ... @end
-866020 0 You are attaching additional event handlers every time you call .click. That is why it is duplicating.
$('a.close-trigger').click(function(){ alert(test); $('#dialog').dialog('close'); }); Pull that code out onto the same level as the other event binding and it should work as expected.
-8290218 0You need to use a delegated handler as the input doesn't have class input2 at the time the handler is applied.
$(document).on('focus','input.input1, textarea.input1', function() { $(this).addClass('input2').removeClass('input1'); }); $(document).on('blur','input.input2, textarea.input2', function() { $(this).addClass('input1').removeClass('input2'); }); There are probably better ways to do this, however. I'd suggest using a third class to mark the inputs that need the class toggled, then just toggle the classes when the event occurs.
$('.needsToggle').on('focus blur', function() { $(this).toggleClass('input1 input2'); }); If they always have class input1 to start, you could use that instead of needsToggle.
Function specialization is weird and almost non-existent. It's possible to fully specialize a function, while retaining all types - i.e. you're providing a custom implementation of some specialization of the existing function. You can not partially specialize a templated function.
It's likely that what you're trying to do can be achieved with overloading, i.e.:
template <typename T> T foo(T arg) { return T(); } float foo(int arg) { return 1.f; }
-21291451 1 Slicing multiple rows by single index I have the following slicing problem in numpy.
a = np.arange(36).reshape(-1,4) a array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23], [24, 25, 26, 27], [28, 29, 30, 31], [32, 33, 34, 35]]) In my problem always three rows represent one sample, in my case coordinates.
I want to access this matrix in a way that if I use a[0:2] to get the following:
array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]] These are the first two coordinate samples. I have to extract a large amount of these coordinate sets from an array.
Thanks
Based on How do you split a list into evenly sized chunks in Python?, I found the following solution, which gives me the desired result.
def chunks(l, n, indices): return np.vstack([l[idx*n:idx*n+n] for idx in indices]) chunks(a,3,[0,2]) array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [24, 25, 26, 27], [28, 29, 30, 31], [32, 33, 34, 35]]) Probably this solution could be improved and somebody won't need the stacking.
-40061612 0Executing shell commands in programs isn't very nice in my opinion so what you can do is to inspect the file programmatically.
Take this example, we'll fill classNames with the list of all Java classes contained inside a jar file at /path/to/jar/file.jar.
List<String> classNames = new ArrayList<String>(); ZipInputStream zip = new ZipInputStream(new FileInputStream("/path/to/jar/file.jar")); for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) { if (!entry.isDirectory() && entry.getName().endsWith(".class")) { // This ZipEntry represents a class. Now, what class does it represent? String className = entry.getName().replace('/', '.').replace('$',''); // including ".class" classNames.add(className.substring(0, className.length() - ".class".length())); } } Credit: Here
-33760227 0 How to configure Frag3 to treat packages as Windows packages on a specyfic hosts?For example I have host addresses: 3.3.3.3 and 3.3.3.33. How to configure Frag3 preprocessor to treat packages that goes to those adressess like/with a typical Windows defragmentation politics?
-1298836 0 VS2008 on Windows 7 RTM with x64 compiler brokenI am having trouble getting x64 compilation to work on Windows 7 RTM (64-bit) with Visual Studio 2008 Professional (both with and without SP1). I have not installed the Windows 7 SDK, as Microsoft suggests might be the issue. The problem is that there are no x64/64-bit choices in the Configuration Manager of Visual Studio.
I do not have the "Microsoft Visual C++ Compilers 2008 Standard Edition" suggested in the link above installed on my computer. Any ideas what might fix this?
I have checked that I have the x64 compiler and tools installed with Visual Studio.
Solution found: Uninstall VS completely and reinstall. Issue resolved after SP1 installed (again). Very strange.
-37652386 0I have done the same for my application. So here a brief overview what i have done:
Save the data (C#/Kinect SDK):
How to save a depth Image:
MultiSourceFrame mSF = (MultiSourceFrame)reference; var frame = mSF.DepthFrameReference.AcquireFrame(); if (frame != null ) { using (KinectBuffer depthBuffer = frame.LockImageBuffer()) { Marshal.Copy(depthBuffer.UnderlyingBuffer, targetBuffer,0, DEPTH_IMAGESIZE); } frame.Dispose(); } write buffer to file:
File.WriteAllBytes(filePath + fileName, targetBuffer.Buffer); For fast saving think about a ringbuffer.
ReadIn the data (Matlab)
how to get z_data:
fid = fopen(fileNameImage,'r'); img= fread(fid[IMAGE_WIDTH*IMAGE_HEIGHT,1],'uint16'); fclose(fid); img= reshape(img,IMAGE_WIDTH,MAGE_HEIGHT); how to get XYZ-Data:
For that think about the pinhole-model-formula to convert uv-coordinates to xyz (formula).
To get the cameramatrix K you need to calibrate your camera (matlab calibration app) or get the cameraparameters from Kinect-SDK (var cI= kinectSensor.CoordinateMapper.GetDepthCameraIntrinsics();).
coordinateMapper with the SDK:
The way to get XYZ from Kinect SDK directly is quite easier. For that this link could help you. Just get the buffer by kinect sdk and convert the rawData with the coordinateMapper to xyz. Afterwards save it to csv or txt, so it is easy for reading in matlab.
How can I reinitialize a timeval struct from time.h?
I recognize that I can reset both of the members of the struct to zero, but is there some other method I am overlooking?
-1125281 0Grab it once and cache it on your side.
-11299312 0 Leaked IntentReceiver in Google Cloud MessagingI have implemented GCM in my app and I am using GSMRegistrar as suggested here. No I am getting an error in logcat
7-02 23:35:15.830: E/ActivityThread(10442): Activity com.abc.xyz.mnp has leaked IntentReceiver com.google.android.gcm.GCMBroadcastReceiver@44f8fb68 that was originally registered here. Are you missing a call to unregisterReceiver()? What I can understand from this and looking at the code for GSMRegistrar is I need to to call GSMRegistrar.onDestroy(this) but I could not understand where should I call this? Calling in onDestroy() of activity mnp causes it to stop retrying for GSM Registartion
I am not completely sure what you want to achieve, exactly. But you can do something like:
IsHandled = ev => { ev(this, args); return args.Handled; }; Even though I am not sure this is more readable, faster, cleaner, or anything like that. I would just go with something like
if (ErrorConfiguration != null) ErrorConfiguration(this, args); if (!args.Handled) error(this, args);
-5367067 0 Do share buttons (facebook, stumbleupon, twitter, etc) incur a page-load penalty from Google? Our site saw traffic from Google drop significantly yesterday (only 5% traffic left in overnight). I asked around. People say that site loading performance could caused the issue.
I've looked at the performance. Site is loading in 1 or 2 seconds if no external links such as Google ads or share button. I cannot improve the Google Ads.
For the share button, if you view the site Multiple Share buttons are loaded and it takes long time to load all of them. But, All of them are loaded in iframe (iframe page to different page but in same domain) to avoid slowing down page load.
I think users are OK with this because all pages are loaded fast except the share buttons which come from each service site.
But, my concern is that if Google care about all site loading including those in iframe, then it's big problem since it takes 10 seconds. If not, I will keep those share buttons.
Should I keep the share buttons or need to get rid of those? (I used addthis, it's super slow. And I added each buttons myself)
-16463874 0 Create a larger matrix in special caseI have two vectors:
A=[1 2 3 4] B=[3 5 3 5] I want to find a matrix from these vectors like this:
you can suppose that c is a plot matrix, where the x-axis is A and y-axis is B:
c = 0 4 0 4 3 0 3 0 0 0 0 0 0 0 0 0 or:
c1= 0 1 0 1 1 0 1 0 0 0 0 0 0 0 0 0 My question is how to create it automatically because I have large vectors.
-10383742 0glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT) saves all the client side states for all vertex array attributes. So everything you set with the glEnableClientState/glDisableClientState and gl*Pointer functions. It won't copy the actual data. It also won't save anything set with glBindBuffer/glBufferData because those would be server side states. There's probably an enum for glPushAttrib for that in normal OpenGL (no glPushAttrib in OpenGL ES either).
I'm guessing that the difference between VBO and vertex array here is that VBOs have their actual data in graphics memory, while vertex arrays have to be streamed to the graphics card when you draw them. Pointers and enabled flags will still be saved with glPushClientAttrib when you are using VBOs, though.
For OpenGL ES you have to keep track of the states yourself if you want to return to the last state. Or better, set everything to default values after you are finished with it (calling glDisableClient for all enabled vertex arrays should be enough).
-16508202 0Yii User is not meant for adding roles to users, it only handles user account management.
You may install an additional extension like rights, auth or srbac (see list) which provides a web-interface for this task.
-7539998 0Try
SHOW ERRORS FUNCTION custord Your custord function was created with compilation errors, so there is something wrong with it. This is why you're getting the object CIS605.CUSTORD is invalid error.
No Activity is defined to handle intent. It could be because you are not initiating your intent correctly in your onCreate. Try something like this
Intent intent = new Intent(Main.this,Menu.class) Main.this.startActivity(intent); EDIT: Also I'm bound to ask have you declared your activity in manifest?
-39581342 0 #if - #else - #endif breaking F# ScriptUsing Visual Studio 2015 Update 3 and fsi.exe from F# v4.0 I' trying to run this script:
//error.fsx #if INTERACTIVE let msg = "Interactive" #else let msg = "Not Interactive" #endif let add x y = x + y printfn "%d" (add 1 2) Output: error.fsx(12,15): error FS0039: The value or constructor 'add' is not defined
If I then comment out the #if-#else-#endif block, it works fine:
// fixed.fsx //#if INTERACTIVE // let msg = "Interactive" //#else // let msg = "Not Interactive" //#endif let add x y = x + y printfn "%d" (add 1 2) Output: 3
I'm sure I'm doing something wrong (rather than this being a bug) but I can't for the life of me figure out how to make this work.
Thoughts?
-40293016 0This below config worked for me. Add the plugin in both the parent and child pom.
Parent :
<build> <plugins> <plugin> <artifactId>maven-jar-plugin</artifactId> <inherited>true</inherited> <executions> <execution> <phase>integration-test</phase> <goals> <goal>jar</goal> </goals> </execution> </executions> <configuration> <skip>true</skip> </configuration> </plugin> </plugins> </build> Child
<build> <plugins> <plugin> <artifactId>maven-jar-plugin</artifactId> <inherited>false</inherited> <executions> <execution> <phase>integration-test</phase> <goals> <goal>jar</goal> </goals> </execution> </executions> <configuration> <skip>false</skip> </configuration> </plugin> </plugins> </build>
-34118727 0 using strtok() in c with combined word I'd like to know how to use strtok to find values, so is this possible to use strtok(mystring, "") or no?
I want split this : mystring --> %3456 I want split into 2 parts : "%" and "3456". Is this possible? how can I do that?
A varbinary isn't displayed with an odd number of digits. The value contains a specific number of bytes, and each byte is displayed as two digits.
(You can write a binary literal with an odd number of digits, for example 0x123, but then it means the same things as 0x0123.)
As you copy a value that has 43679 digits, it's not a correct value from the database. Most likely it's because it gets concatenated, either when it is displayed or when you copy it.
-13469787 0 How to specify page size in dynamically in yii view?How to specify page size in dynamically in yii view?(not a grid view) In my custom view page there is a search option to find list of users between 2 date i need 2 know how to specify the page size dynamically? If number of rows less than 10 how to hide pagination ?
please check screen-shoot
I dont want the page navigation after search it confusing users..
my controller code
$criteria=new CDbCriteria(); $count=CustomerPayments::model()->count($criteria); $pages=new CPagination($count); // results per page $pages->pageSize=10; $pages->applyLimit($criteria); $paymnt_details=CustomerPayments::model()->findAll($criteria); $this->render('renewal',array('paymnt_details'=>$paymnt_details,'report'=>$report,'branch'=>$branch,'model'=>$model,'pages' => $pages,)); } my view Link
-27519382 0dict={} x1=fileobject.read() for line in x1.splitlines(): if line.split()[1] in dict.keys(): dict[line.split()[0]]=line.split()[1]+" "+dict[line.split()[1]] else: dict[line.split()[0]]=line.split()[1] print dict This way you can have a dictionary of object with keys as you want.
Output:{'k3': 'v3', 'k2': 'v2', 'k1': 'v1', 'k5': 'k4 k1 v1', 'k4': 'k1 v1'}
To represent the character you can use Universal Character Names (UCNs). The character 'ф' has the Unicode value U+0444 and so in C++ you could write it '\u0444' or '\U00000444'. Also if the source code encoding supports this character then you can just write it literally in your source code.
// both of these assume that the character can be represented with // a single char in the execution encoding char b = '\u0444'; char a = 'ф'; // this line additionally assumes that the source character encoding supports this character Printing such characters out depends on what you're printing to. If you're printing to a Unix terminal emulator, the terminal emulator is using an encoding that supports this character, and that encoding matches the compiler's execution encoding, then you can do the following:
#include <iostream> int main() { std::cout << "Hello, ф or \u0444!\n"; } This program does not require that 'ф' can be represented in a single char. On OS X and most any modern Linux install this will work just fine, because the source, execution, and console encodings will all be UTF-8 (which supports all Unicode characters).
Things are harder with Windows and there are different possibilities with different tradeoffs.
Probably the best, if you don't need portable code (you'll be using wchar_t, which should really be avoided on every other platform), is to set the mode of the output file handle to take only UTF-16 data.
#include <iostream> #include <io.h> #include <fcntl.h> int main() { _setmode(_fileno(stdout), _O_U16TEXT); std::wcout << L"Hello, \u0444!\n"; } Portable code is more difficult.
-30966823 0You can get the total heap consumption and other stats via getGCStats in module GHC.Stats, at least if you run your program with +RTS -T.
I have about 20 different variables and i want to compare this variables with each other to check weather they are equal or not.
Example
$var1 = 1; $var2 = 2; $var3 = 1; $var4 = 8; . . . $var10 = 2; Now i want to check...
if($var1 == $var2 || $var1 == $var3 || $var1 == $var4 || ......... || $var2 == $var3 || $var2 == $var4 || ............. || $var8 = $var9 || $var8 == $var10 ||...) { echo 'At-least two variables have same value'; } I am finding for an easy to do this. Any Suggestions?
-1875294 0 What might cause IDirectDraw::GetCaps returns DDERR_INVALIDPARAMS?I have this little snippet of code with IDirectDraw::GetCaps returning DDERR_INVALIDPARAMS (a.k.a. E_INVALIDARG, a.k.a. 0x80070057).
The loaded dll is ddraw.dll 5.03.2600.5512 (xpsp.080413-0845)
I need to check whether the display hardware has 3D acceleration (DDCAPS_3D).
I have no idea to solve the problem, the snippet is so simple, am I missing something?
Thank you very much.
Alessandro
#include <ddraw.h> #include <iostream> #define TEST_HR(hr) if(hr!=DD_OK){ std::cout << "Error 0x" << std::hex << static_cast<unsigned long>(hr) << " at line: " << std::dec << __LINE__; return __LINE__;} int main(int argc, char* argv[]) { ::CoInitialize( 0 ); IDirectDraw* dd; TEST_HR( ::DirectDrawCreate( 0, &dd, 0 ) ); DDCAPS hel_caps, hw_caps; ::ZeroMemory( &hel_caps, sizeof( DDCAPS ) ); ::ZeroMemory( &hw_caps, sizeof( DDCAPS ) ); TEST_HR( dd->GetCaps( &hw_caps, &hel_caps ) ); ::CoUninitialize(); return 0; }
-10108810 0 RTC source control icons What is the difference between these two RTC source control icons ? Is it identifying which workspace is loaded by which component ? Is there a reference that explains each of the RTC source control icons ?


Do this:
$(e).find(".myclass").something(); or the slightly shorter, yet less efficient version:
$(".myclass", e).something(); The reason you can't use + is that your e is a DOM element, which is not a useful type for concatenation into a selector string, since you end up with something like:
"[object HTMLInputElement] .myclass"
-6233799 0 libqxt installation problem - features.path warning I use Qt SDK 1.1.1 (everything installed exept experimental category) on Windows 7 and I'm trying to set up libqxt libaries for this enviroment. I downloaded and unpacked libqxt tip and ran configure.bat file using Qt for Desktop command line with -static -debug_and_release properties as administrator.
Testing for qmake... Testing for mingw32-make...Using mingw32-make. Testing for optional external libraries. If tests fail, some features will not be available. Testing for Berkeley DB... Berkeley DB disabled. Testing for Zero Conf... Zero Conf disabled. Configuration successful. Generating makefiles... WARNING: c:\QtSDK\Desktop\Qt\4.7.1\mingw\mkspecs\default\qmake.conf:108: Unescap ed backslashes are deprecated. WARNING: features.path is not defined: install target not created Makefiles generated. Run mingw32-make now. And so mingw32-make command do nothing... What should I do to compile it properly. I tried to use diffrent parameters but nothing changes...
-36993563 0It's fine to return a reference as long as the object referred to is not destroyed before control leaves the function (i.e., an automatic local variable or parameter, or a temporary created inside the function).
In this case, you are potentially returning a reference to the temporary Foo() in the calling context, which is fine because that temporary is guaranteed to survive until the end of the full-expression containing the call. However, the reference would become dangling after the full-expression, i.e., the lifetime of the Foo() temporary is not extended, so care must be taken not to access it again after that point.
Similar question to Promise resolve before inner promise resolved but I can't get it to work nontheless.
Every time I think I understand promises, I prove myself wrong!
I have functions that are written like this
function getFileBinaryData () { var promise = new RSVP.Promise(function(resolve, reject){ var executorBody = { url: rootSite + sourceRelativeUrl + "/_api/web/GetFileByServerRelativeUrl('" + fileUrl + "')/$value", method: "GET", binaryStringResponseBody: true, success: function (fileData) { resolve(fileData.body); }, error: function (argument) { alert("could not get file binary body") } } sourceExecutor.executeAsync(executorBody); }); return promise; } function copyFileAction (fileBinaryData) { var promise = new RSVP.Promise(function(resolve, reject){ var executorBody = { url: rootSite + targetWebRelativeUrl + "/_api/web/GetFolderByServerRelativeUrl('" + targetList + "')/Files/Add(url='" + fileName + "." + fileExt + "', overwrite=true)", method: "POST", headers: { "Accept": "application/json; odata=verbose" }, contentType: "application/json;odata=verbose", binaryStringRequestBody: true, body: fileBinaryData, success: function (copyFileData) { resolve(); }, error: function (sender, args) { } } targetExecutor.executeAsync(executorBody); }); return promise; } that I try to chain like this
$.getScript("/_layouts/15/SP.RequestExecutor.js") .then(patchRequestExecutor) .then(function(){ sourceExecutor = new SP.RequestExecutor(sourceFullUrl); targetExecutor = new SP.RequestExecutor(targetList); }) .then(getFileInformation) .then(getFileBinaryData) .then(copyFileAction) .then(getTargetListItem) .then(updateTargetListItem) .catch(function (sender, args) { }); or like this
$.getScript("/_layouts/15/SP.RequestExecutor.js") .then(patchRequestExecutor) .then(function(){ sourceExecutor = new SP.RequestExecutor(sourceFullUrl); targetExecutor = new SP.RequestExecutor(targetList); }) .then(function(){ return getFileInformation(); }) .then(function(){ return getFileBinaryData(); }) .then(function(binaryData){ return copyFileAction(binaryData) }) .then(function(){ return getTargetListItem(); }) .then(function(listItem){ return updateTargetListItem(listItem); }); The problem though is that even if I return new promises, the execution continues down the chain before any of the inner promises are resolved. How come? Shouldn't it wait until the asynchronous request has succeeded and resolve() is called in the success callback?
With 1.4 version of AngularJS, is it possible to create persistent cookies with $cookies?
I want data to be stored once I login, for 7 days say. In version 1.3.X, it is not possible to set Expiration date even. But with 1.4, they have deprecated $cookieStore and set an option in $cookies for expiration date.
I want to know whether this one creates cookies for desired longer periods rather than I close the browser and everything is gone.
-20997020 0 Not displaying image in viewpagerI want to load four image in view pager, i am actually loading images from drawable folder but i am not able to load these,
below is the code
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <android.support.v4.view.ViewPager android:id="@id/pager1" android:layout_width="fill_parent" android:layout_height="fill_parent" > <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:orientation="horizontal" > <ImageView android:id="@+id/img1" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:src="@drawable/ncard1" /> <ImageView android:id="@+id/img2" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:src="@drawable/tncard2" /> </LinearLayout> <LinearLayout android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="1" android:orientation="horizontal" > <ImageView android:id="@+id/img3" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:src="@drawable/tncard3" /> <ImageView android:id="@+id/img4" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:src="@drawable/tncard4" /> </LinearLayout> </LinearLayout> </android.support.v4.view.ViewPager> Look i am displaying images from drawable but i am getting blank view pager
please help me
-40201250 0The problem was solved after I imported CA certificate in JRE certificate store:
keytool -importcert -alias startssl -keystore $JAVA_HOME/jre/lib/security/cacerts -storepass changeit -file ca.der
-2458422 0 Point 1: I think you need at least some quotes around the connection string:
myProcess.StartInfo.Arguments = "/mode:fullgeneration \"/c:"+cs+"\" project:School ..."; But do examine the resulting Arguments string in the debugger to see if everything is allright.
For point 2, see this SO question.
-8104825 0Just a note, when using .mask() function, you have to call it to a DOM element, which means you should use it either with
Ext.get('yourDomElementId').mask(); or
Ext.getCmp('yourExtComponentId').el.mask(); //this gets the dom //element attached to the component I've never used it with .body
-39050173 0 Saving large amount of data from FirebaseI actually sizeable amount of data that I retrieve the entire data from Firebase when the user log into the app, or to the different view controllers which require the data from Firebase.
However, I find it meaningless to continuously retrieving the same data as the user navigates through the app. Is there a way for me to save all the data to the phone upon first retrieval after log in and just refer to the local data whenever I need it?
I have used NSUserDefaults for small amount of data but I don't think that it is the right option for my situation.
For these data, I would also require to search them by key when necessary.
-20539520 0You don't replace the whole string with \0, just the pattern match, which is This. In other words, you replace This with This.
To replace the whole line with This, you can do:
echo "This is a test string" | sed '/This/s/.*/This/' It looks for a line matching This, and replaces the whole line with This. In this case (since there is only one line) you can also do:
echo "This is a test string" | sed 's/.*/This/' If you want to reuse the match, then you can do
echo "This is a test string" | sed 's/.*\(This\).*/\1/' \( and \) are used to remember the match inside them. It can be referenced as \1 (if you have more than one pair of \( and \), then you can also use \2, \3, ...).
In the example above this is not very helpful, since we know that inside \( and \) is the word This, but if we have a regex inside the parentheses that can match different words, this can be very helpful.
So I have found the "silver bullet" that seems to resolve a great number of challenges regarding auto layout of prototype cells.
In the cellForRowAtIndexPath function I added the following line of code right before I return the cell:
lobj_NearbyLocationEntry!.layoutIfNeeded() (lobj_NearbyLocationEntry is the name of my cell variable I am returning.)
When I do this, the auto layout for my table works fine. On a side note, I found a defect in the code that uses the UITableViewController also. Once the data loads and it all looks good, if you scroll down and then scroll back up, you will see a couple of the cells are now not laid out correctly. Putting this line of code in that view controller's code also resolved that layout problem.
I hope this helps many people who are sitting there trying to figure out why their app is not auto laying out a tableView cell correctly. :)
-24081707 0 Google Spreadsheet: Count rows with not empty valueIn a Google Spreadsheet: How can I count the rows of a given area that have a value? All hints about this I found up to now lead to formulas that do count the rows which have a not empty content (including formula), but a cell with =IF(1=2;"";"") // Shows an empty cell is counted as well.
What is the solution to this simple task?
Thank you in advance
-15540379 0Using the Scala debugger through the remote connector works.
But if you want to avoid to go back and forth between sbt and Eclipse, you can load your project in Scala IDE using sbteclipse, and then run your specs2 tests from inside Scala IDE, in debug mode, using the JUnit launcher.
You're trying to assign an array of bytes (byte[]) to a single byte, hence the error.
Try the following code:
byte[] imgarray = new byte[imglength];
-13378535 0 <?php require './config.php'; require './facebook.php'; //connect to mysql database mysql_connect($db_host, $db_username, $db_password); mysql_select_db($db_name); mysql_query("SET NAMES utf8"); //Create facebook application instance. $facebook = new Facebook(array( 'appId' => $fb_app_id, 'secret' => $fb_secret )); $output = ''; $isHaveNext = false; if (isset($_POST['send_messages'])) { //default message/post $msg = array( 'message' => 'date: ' . date('Y-m-d') . ' time: ' . date('H:i') ); //construct the message/post by posted data if (isset($_POST['message'])) { $msg['message'] = $_POST['message']; } if (isset($_POST['url']) && $_POST['url'] != 'http://') { $msg['link'] = $_POST['url']; } if (isset($_POST['picture_url']) && $_POST['picture_url'] != '') { $msg['picture'] = $_POST['picture_url']; } // get offset $offset = isset($_POST['offset']) ? intval($_POST['offset']) : 0; // get total rows count $query = mysql_query("SELECT COUNT(1) FROM offline_access_users LIMIT 1"); $rows = mysql_fetch_array($query); $total = $rows[0]; //get users and try posting our message/post $result = mysql_query("SELECT * FROM offline_access_users LIMIT 50 OFFSET $offset"); if ($result) { while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $msg['access_token'] = $row['access_token']; try { $facebook->api('/me/feed', 'POST', $msg); $output .= "<p>Posting message on '" . $row['name'] . "' wall success</p>"; } catch (FacebookApiException $e) { $output .= "<p>Posting message on '" . $row['name'] . "' wall failed</p>"; } } } // next if ( $total > ($offset + 50) ) { $isHaveNext = true; $offset += 50; ?> <form action="" method="post"> <input type="hidden" name="message" value="<?php echo $_POST['message'] ?>"> <input type="hidden" name="url" value="<?php echo $_POST['url'] ?>"> <input type="hidden" name="picture_url" value="<?php echo $_POST['picture_url'] ?>"> <input type="hidden" name="offset" value="<?php echo $offset ?>"> <input type="submit" name="send_messages" value="Next"> </form> <?php echo $output; } } if ($isHaveNext) exit(1); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="et" lang="en"> <head> <title>Batch posting</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <style type="text/css"> body { font-family:Verdana,"Lucida Grande",Lucida,sans-serif; font-size: 12px} </style> </head> <body> <h1>Batch posting</h1> <form method="post" action=""> <p>Link url: <br /><input type="text" value="http://" size="60" name="url" /></p> <p>Picture url: <br /><input type="text" value="" size="60" name="picture_url" /></p> <p>Message: <br /><textarea type="text" value="" cols="160" rows="6" name="message" />Message here</textarea></p> <p><input type="submit" value="Send message to users walls" name="send_messages" /></p> </form> <?php echo $output; ?> </body> </html> Bonus: Use PDO instead of mysql_* functions.
-31871649 0setTimeout(function() { window.location.href = "/NewPage.aspx"; }, 2000); .wrapper { background-color: red; width: 100%; -webkit-animation-name: example; /* Chrome, Safari, Opera */ -webkit-animation-duration: 2s; /* Chrome, Safari, Opera */ animation-name: example; animation-duration: 2s; } @-webkit-keyframes example { 0% { opacity: 100; filter: alpha(opacity=1000); /* For IE8 and earlier */ } 100% { opacity: 0.0; filter: alpha(opacity=0); /* For IE8 and earlier */ } } /* Standard syntax */ @keyframes example { 0% { opacity: 100; filter: alpha(opacity=1000); /* For IE8 and earlier */ } 100% { opacity: 0.0; filter: alpha(opacity=0); /* For IE8 and earlier */ } } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='wrapper'> <div>Home Page</div> </div> I have tried to implement the code for adding buttons in jqGrid toolbar from the example site http://www.guriddo.net/demo/bootstrap/ but I'm surprised to find that it isn't working for me. Searched for a couple of hours but I can't figure it out. Here is my code:
<script type="text/javascript"> $(function () { var gridDataUrl = '@Url.Action("JsonCategories", "AdminNomCategory")' var grid = $("#reportsGrid").jqGrid({ url: gridDataUrl, datatype: "json", mtype: 'POST', colNames: [ '@Html.DisplayNameFor(model => model.CategoryGuid)', '@Html.DisplayNameFor(model => model.CategoryName)', '@Html.DisplayNameFor(model => model.CategoryDescription)' ], colModel: [ { name: 'CategoryGuid', index: 'CategoryGuid', width: 10, align: 'left', classes: "nts-grid-cell", hidden: true }, { name: 'CategoryName', index: 'CategoryName', width: 10, align: 'left', classes: "nts-grid-cell" }, { name: 'CategoryDescription', index: 'CategoryDescription', width: 10, align: 'left', classes: "nts-grid-cell" } ], rowNum: 20, rowList: [10, 20, 30], height: 450, width: 1140, pager: '#pager', /*jQuery('#pager'),*/ sortname: 'CategoryGuid', toolbarfilter: true, viewrecords: true, sortorder: "asc", caption: "Categories", ondblClickRow: function (rowid) { var gsr = jQuery("#reportsGrid").jqGrid('getGridParam', 'selrow'); if (gsr) { var CategoryGuid = grid.jqGrid('getCell', gsr, 'CategoryGuid'); window.location.href = '@Url.Action("Edit", "AdminNomCategory")/' + CategoryGuid } else { alert("Please select Row"); } }, @*onSelectRow: function (rowid) { var gsr = jQuery("#reportsGrid").jqGrid('getGridParam', 'selrow'); if (gsr) { var CategoryGuid = grid.jqGrid('getCell', gsr, 'CategoryGuid'); window.location.href = '@Url.Action("Edit", "AdminNomCategory")/' + CategoryGuid } else { alert("Please select Row"); } }*@ }); //jQuery("#reportsGrid").jqGrid('navGrid', '#pager', { edit: true, add: true, del: true }); var template = "<div style='margin-left:15px;'><div> Customer ID <sup>*</sup>:</div><div> {CustomerID} </div>"; template += "<div> Company Name: </div><div>{CompanyName} </div>"; template += "<div> Phone: </div><div>{Phone} </div>"; template += "<div> Postal Code: </div><div>{PostalCode} </div>"; template += "<div> City:</div><div> {City} </div>"; template += "<hr style='width:100%;'/>"; template += "<div> {sData} {cData} </div></div>"; $('#reportsGrid').navGrid('#pager', // the buttons to appear on the toolbar of the grid { edit: true, add: true, del: true, search: false, refresh: false, view: false, position: "left", cloneToTop: false }, //// options for the Edit Dialog { editCaption: "The Edit Dialog", template: template, errorTextFormat: function (data) { return 'Error: ' + data.responseText } }, // options for the Add Dialog { template: template, errorTextFormat: function (data) { return 'Error: ' + data.responseText } }, // options for the Delete Dailog { errorTextFormat: function (data) { return 'Error: ' + data.responseText } } ); grid.jqGrid('filterToolbar', { searchOnEnter: true, enableClear: false }); jQuery("#pager .ui-pg-selbox").closest("td").before("<td dir='ltr'>Rows per page </td>"); grid.jqGrid('setGridHeight', $(window).innerHeight() - 450); }); $(window).resize(function () { $('#reportsGrid').jqGrid('setGridHeight', $(window).innerHeight() - 450); }); </script> I am using jqGrid 4.4.4 and ASP.NET. The thing I noticed, is that on the example page, the buttons are located inside a div with an id like 'jqGridPagerLeft', but on my page, that div has no id. So I went looking inside the jqGrid source but I'm lost and I can't figure out why it doesn't have an id allocated.
Any clues? I just want to add the buttons to the bottom toolbar. Thx!
-12756918 0As Ahmad says, you need to compile your code with API Level 14 in order to use the constant "ICE_CREAM_SANDWICH". The thing is that at compilation time those constants are changed into their respective values. That means that at runtime any device won't see the "ICE_CREAM_SANDWICH" constant but the value 14 (even if it is a device with Froyo 2.2 installed).
In other words, in your code:
Integer version = Build.VERSION_CODES.ICE_CREAM_SANDWICH; in the device:
Integer version = 14; It is not exactly like that, but you get the idea.
-21571515 0By passing the interface you are creating the opportunity to pass all the classes which implements the interface. But in case1 you can only pass the MyClass and its subclasses.
For example think about the following case
public class YourClass implements MyInterface { public void foo() { doJob(); } } Now in case2 you can pass both the instance of MyClass and YourClass. but in case1 you can't.
Now, what is the importance of it?
In OOP it is recommended to program to the interface instead of class. So if you think about good design there will be no case1. Only case2 will do the job for you.
-5850596 0 Conversion of long to decimal in c#I have a value stored in a variable which is of type "long".
long fileSizeInBytes = FileUploadControl.FileContent.Length; Decimal fileSizeInMB = Convert.ToDecimal(fileSizeInBytes / (1024 * 1024)); I want to convert the fileSizeInBytes to decimal number rounded up to 2 decimal places (like these: 1.74, 2.45, 3.51) But i'm not able to get the required result. I'm only getting single digit with no decimal places as result. Can some one help me with that ??.
Thanks in anticipation
-101836 0You could try to get spanning-tree protocol information out of the smart switches; even unmanaged switches have to participate in this protocol (this doesn't apply to hubs, though).
-16851657 0function functionTwo(b) { if(functionOne(b)) return true; else return false; }
-10560872 0 If you really want to do it in Goliath I'd suggest creating a plugin and doing it in there. Create a queue in the config and have the plugin pop items from the queue and send the mail.
-7190464 0The subtlety you miss is that the standard input and positional parameters are not the same thing.
Standard input, which you can redirect with the '<', or even from another program with '|' is a sequence of bytes. A script can read stdin with, well, the read command.
Positional parameters are numbered 1 to N and hold the value of each argument. The shell refers to them as $1 to ${42} (if you gave that many).
Standard input and positional parameters are indepent of one another. You can have both, either, or none, depending how you call a program (and what that program expects):
grep -E pattern < filewc < fileecho Here are five positional parameterslsYou don't need quotes around spaced entities when you use fgrep. fgrep takes each line literally already. It's only in the command line that you need quotes in order to disambiguate a string from extra command line arguments. Your file can just be:
content1 c o n t e n t 2
-16028715 0 split a comma separated string in a pair of 2 using php I have a string having 128 values in the form of :
1,4,5,6,0,0,1,0,0,5,6,...1,2,3. I want to pair in the form of :
(1,4),(5,6),(7,8) so that I can make a for loop for 64 data using PHP.
-39925370 0 Lucida Console font underscores not showing in inputI am using the font-family: "Lucida Console", Monaco, monospace in my CSS. I am trying to use the same font as my terminal (or similar).
The problem is that when used in an input element, the underscores are not shown.
Here is an example here: https://jsfiddle.net/a69x99d9/
Try typing in the input and you should immediately see that the underscores are hidden.
It seems that this might be caused because the underscore is displayed past the line-height of the element. Is this the case?
How do I fix something like this?
Thanks in advance!
EDIT: This problem seems to only happen on ubuntu. (and possibly mac). Tested on chromeos and windows, nothing happens.
-31891230 0Try this working link at plnkr: http://plnkr.co/edit/OaQBWxlIfa2fVvanKKEl?p=preview
Hope it helps!!! HTML
<div class="blockcontainer"> <div class="blockcenterbox"> <div class="blocktop">abc</div> </div> <div class="blockbottom"></div> </div> CSS
.blockcontainer { width:200px; height:200px; background-color:#00CC66; overflow:hidden; } .blocktop { width:100px; background-color:#6699FF; height:50px; } .blockcenterbox { width: 100px; height: 50px; background-color: yellow; margin: 0 auto; } .blockbottom { width:25px; height:25px; background-color:black; margin: 0 auto; }
-12832100 0 Yes this can be easily done using Clojure (for backend) and ClojureScript OR JavaScript (for frontend).
Basically the client js code will use websockets to connect to clojure server and on server you can have a state wrapped in an atom that is access by each client and each client is updated about the state through the connected websocket... something similar you do in a chat web application.
For websocket you can use Aleph.
-14079373 0 can we Increase Netty Server performance by using limiting thread poolCan anybody help me to fix the correct thread pool size a according to the processor and RAM.
Can we fix the limit of worker thread for better performance ?
-14695549 0Further to Ryan's point, you can see some info on using the bootstrap page on developerworks, you'll want to look at the views example gadget. Unfortunately you can only open a dialog in Connections, the EE style flyout is not available to gadgets on My Page.
-7932352 0 Right banner margin CSSOn the site: ukrainiansecret.com
I would like to get rid of that green right margin of the banner, and to have it exactly as the left side. Have tried to stretch the banner width but it didn't work out.
Thanks
-25554245 0 How to check ping between client and server in php?I have a problem, I need to check the connection between client server, i need to get the response time in ms between the client and a "x" server with php, how I can do that?
-30067366 0jQuery's .val() method is both a getter and a setter.
Try this:
$('input[name="x"]').val($hello);
I have a issue when I try to call adapter (HTTP/MYSQL) from a Java adapter.
When I am using Postmen test it (added Authorization on the header) It's always get a IO issue:
[I O: Invalid token on line 1, column 14].
First, I guess it should be OAuth issue, I add @OAuthSecurity(enabled=false) at the class but not work.
Would you please help me find out where the problem is.
Code snippet:
DataAccessService service = WorklightBundles.getInstance() .getDataAccessService(); ProcedureQName name = new ProcedureQName("mysqlAdapter", "getMysqlAdapters"); String para = ""; // String para = "['a','b','c']"; InvocationResult mysql= service.invokeProcedure(name, para); JSONObject jsMysql = mysql.toJSON(); //String rst = jsMysql.get("key").toString(); PS following code snippet is working when I test it on Postman:
HttpUriRequest request = api.getAdaptersAPI() .createJavascriptAdapterRequest("mysqlAdapter", "getMysqlAdapters"); try { HttpResponse response = api.getAdaptersAPI().executeAdapterRequest(request); JSONObject jsonObj =api.getAdaptersAPI().getResponseAsJSON(response); return jsonObj.toString(); } catch (MFPServerOAuthException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "error";
-6576259 0 Or you can check first if key exists by using isset().
if ( isset($preset[$table]) ) Return true if exists, otherwise return false.
-11919033 0 Why do I need to call removeView() in order to add a View to my LinearLayoutI am getting this error but I am not sure exactly why:
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. The part where I add the View is the line that the error is pointing to. I am providing my Adapter code in order for you guys to get a better picture of what I am doing and why I am getting this error. Please let me know if anymore info is needed. Thanks in advance.
Adapter
private class InnerAdapter extends BaseAdapter{ String[] array = new String[] {"12\nAM","1\nAM", "2\nAM", "3\nAM", "4\nAM", "5\nAM", "6\nAM", "7\nAM", "8\nAM", "9\nAM", "10\nAM", "11\nAM", "12\nPM", "1\nPM", "2\nPM", "3\nPM", "4\nPM", "5\nPM", "6\nPM", "7\nPM", "8\nPM", "9\nPM", "10\nPM", "11\nPM"}; TextView[] views = new TextView[24]; public InnerAdapter() { TextView create = new TextView(DayViewActivity.this); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 62, getResources().getDisplayMetrics()), 1.0f); params.topMargin = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getResources().getDisplayMetrics()); params.bottomMargin = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getResources().getDisplayMetrics()); create.setLayoutParams(params); create.setBackgroundColor(Color.BLUE); create.setText("Test"); views[0] = create; for(int i = 1; i < views.length; i++) { views[i] = null; } } @Override public int getCount() { // TODO Auto-generated method stub return array.length; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView == null) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); convertView = inflater.inflate(R.layout.day_view_item, parent, false); } ((TextView)convertView.findViewById(R.id.day_hour_side)).setText(array[position]); LinearLayout layout = (LinearLayout)convertView.findViewById(R.id.day_event_layout); if(views[position] != null) { layout.addView((TextView)views[position], position); } return convertView; } } XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="61dp" android:orientation="horizontal" > <LinearLayout android:layout_width="wrap_content" android:layout_height="61dp" android:orientation="vertical"> <TextView android:id="@+id/day_hour_side" android:layout_width="wrap_content" android:layout_height="60dp" android:text="12AM" android:background="#bebebe" android:layout_weight="0" android:textSize="10dp" android:paddingLeft="5dp" android:paddingRight="5dp"/> <TextView android:layout_width="match_parent" android:layout_height="1dp" android:layout_weight="0" android:background="#000000" android:id="@+id/hour_side_divider"/> </LinearLayout> <LinearLayout android:layout_width="0dp" android:layout_height="61dp" android:orientation="vertical" android:layout_weight="1"> <LinearLayout android:id="@+id/day_event_layout" android:layout_width="match_parent" android:layout_height="60dp" android:orientation="horizontal" ></LinearLayout> <TextView android:layout_width="match_parent" android:layout_height="1dp" android:background="#000000" android:id="@+id/event_side_divider" /> </LinearLayout> </LinearLayout>
-6348427 0 Does HTML 5 application cache have any benefit for online apps? Does the HTML 5 application (offline) cache have any benefit for online/connected apps?
My page needs to be online to function and is loaded exclusively in a UIWebView as part of an iOS app. This page is loading some large dependencies and I was wondering if I could use the HTML 5 app cache to store these dependencies to avoid relying on the regular browser cache.
So I guess my question is:
When an HTML 5 page is online, does it use the offline cache if a dependency already exists in the HTML5 offline cache?
-1568058 1 Django: How do I make fields non-editable by default in an inline model formset?I have an inline model formset, and I'd like to make fields non-editable if those fields already have values when the page is loaded. If the user clicks an "Edit" button on that row, it would become editable and (using JavaScript) I would replace the original widgets with editable ones. I'd like to do something like this when loading the page:
for field in form.fields: if field.value: # display as text else: # display as my standard editable widget for this field I see that inlineformset_factory has an argument called formfield_callback. I suspect that this could be useful, but so for I haven't found any documentation for it. Can anyone point me to some useful documentation for this, and how it can help me solve this problem?
I'm attempting an aging formula. I have one column with dates I've submitted info, but some rows in the column haven't been submitted. In another column I want to have an aging formula. If the "submitted date" cell is blank, I want the aging cell to be blank. If there is a date entered, I want it to show how many days it's been since it was submitted.
I'm pretty new to excel formulas. I know how to create the aging, and I know how to make one cell blank if another is blank. But I do not know how to combine both formulas into one cell.
-32205707 0 Filter data on the query or with Java stream?I have a Play 2.3.x Java application connected to a MongoDB database via Morphia.
I activated slow query profiling in MongoDB and saw that a query comes often. It looks like this :
"query": { "field1": null, "field2": true, "field3": "a061ee3f-c2be-477c-ad81-32f852b706b5", "$or": [ { "field4.VAL.VALUE_1": "EXPECTED_VALUE_1", "field4.VAL.VALUE_2": "EXPECTED_VALUE_2" } ] } In its current state, there is no index so every time the query is executed the whole collection is scanned. I still have a few documents, but I anticipate the growth of the database.
So I was wondering what was the best solution :
Stream APIIf you see another solution, feel free to suggest it :)
Thanks.
-32423201 0 undeclared variable in php why through error?As described in php manual
It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type depending on the context in which they are used - booleans default to FALSE, integers and floats default to zero, strings (e.g. used in echo) are set as an empty string and arrays become to an empty array
if so then why its through error (notice) when try to access uninitialized variable? like
echo $x; its return even in script following message
Notice: Undefined variable: x...
But When I declare $x as NULL then its not through any notice or error and working nicely
$x = NULL; echo $x; Now My Question is Why its through notice if not declare like $x = NULL or $x = '' although undeclared variable initialized as NULL which is clearly mentioned in Manual??
I have a script and many uninitialized variable there and experiencing this issue.
-6119557 0Class level variables can't maintain their value on postback.
But there are two ways you can maintain Data on the Page's PostBack: ViewState and Session State. But I would suggest in your Scenario to put it in the ViewState.
ViewState["theDataTable"] = theDataTable; Session["theDataTable"] = theDataTable; And then you can access it on the page postback:
DataTable theDataTable = (DataTable)ViewState["theDataTable"]; DataTable theDataTable = (DataTable)Session["theDataTable"];
-19043514 0 You've escaped the } for boost, but you need to escape the \ escape char for the compiler as well.
boost::wregex rightbrace(L"\\}");
-25662942 0 DocumentDb User Data Segregation I'm testing out the recently released DocumentDb and can't find any documentation indicating best practice on how to perform user data segregation.
I imagine the rough design would be:
I'm creating an AngularJs application and currently use an Azure Sql Database combined with Azure Mobile Services.
Mobile services handles the user authentication and also the server side user data segregation by the use of data script javascript functions:
e.g.
function insert(item, user, request) { item.userId = user.userId; request.execute(); } Any suggestions on what would be the technique for secure user data segregation from AngularJS using DocumentDB?
-27798343 0Base64 encoding takes 3 input bytes and converts them to 4 bytes. So if you have 100 Mb file that will end up to be 133 Mb in Base64. When you convert it to Java string (UTF-16) it size will be doubled. Not to mention that during conversion process at some point you will hold multiple copies in memory. No matter how you turn this it is hardly going to work.
This is slightly more optimized code that uses Base64OutputStream and will need less memory than your code, but I would not hold my breath. My advice would be to improve that code further by skipping conversion to string, and using temporary file stream as output instead of ByteArrayOutputStream.
InputStream inputStream = null;//You can get an inputStream using any IO API inputStream = new FileInputStream(file.getAbsolutePath()); byte[] buffer = new byte[8192]; int bytesRead; ByteArrayOutputStream output = new ByteArrayOutputStream(); Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT); try { while ((bytesRead = inputStream.read(buffer)) != -1) { output64.write(buffer, 0, bytesRead); } } catch (IOException e) { e.printStackTrace(); } output64.close(); attachedFile = output.toString();
-36031822 0 You can use Project Dependencies to adjust build order:
THIS is the right way to do it.
One more thing to keep in mind is that you MUST set the FILE SIZE:
curl_easy_setopt(curlHandle, CURLOPT_INFILESIZE,(curl_off_t)putData.size); Otherwise your server might throw an error stating that the request length wasn't specified.
putData is an instance of the put_data structure.
-17056545 0This process is handled by the Android MediaScanner. This is what scans the phone for new media and stores it in the Android media database. I believe the time frame which it runs is device specific. However, you can call it manually:
Uri uri = Uri.fromFile(destFileOrFolder); Intent scanFileIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri); sendBroadcast(scanFileIntent);
-36534762 0 I know the option the (b) you can entirely disable Silex app error handler and after that, your custom error handler should work fine as you defined it.
Entirely disabled Silex error handler:
$app['exception_handler']->disable(); So, It will be like:
require_once 'Exception.php'; # Load the class $handler = new ErrorHandler(); # Initialize/Register it $app = new \Silex\Application(); $app->get('/', function () use ($app) { nonexistentfunction(); trigger_error("example"); throw new \Exception("example"); }); $app->run();
-14684312 1 Issue with creating "xlsx" in Python by copying data from csv I am trying to copy all the data in csv to excel "xlsx" file using python. I am using following code to do this:
from openpyxl import load_workbook import csv #Open an xlsx for reading wb = load_workbook(filename = "empty_book.xlsx") #Get the current Active Sheet ws = wb.get_active_sheet() #You can also select a particular sheet #based on sheet name #ws = wb.get_sheet_by_name("Sheet1") #Open the csv file with open("Pricing_Updated.csv",'rb') as fin: #read the csv reader = csv.reader(fin) #get the row index for the xlsx #enumerate the rows, so that you can for index,row in enumerate(reader): i=0 for row[i] in row: ws.cell(row=index,column=i).value = row[i] i = i+1 #save the excel file wb.save("empty_book.xlsx") I found this code on SO itself and modified it to make it usable for my case. But this code is throwing UnicodeDecodeError: 'ascii' codec can't decode byte 0xa3 in position 0: ordinal not in range(128) error for ws.cell(row=index,column=i).value = row[i] line.
Please help me in resolving this issue.
Update: I tried using following code also to resolve the issue but came across UnicodeDecode error again for ws.cell(row=rowx,column=colx).value = row[colx] line:
for rowx,row in enumerate(reader): for colx, value in enumerate(row): ws.cell(row=rowx,column=colx).value = row[colx] Update 2: I tried using xlwt module also to copy the csv into xls (as it doesn't support xlxs) and again came across UnicodeDecode error, code which I used was:
import glob, csv, xlwt, os wb = xlwt.Workbook() for filename in glob.glob("Pricing_Updated.csv"): (f_path, f_name) = os.path.split(filename) (f_short_name, f_extension) = os.path.splitext(f_name) ws = wb.add_sheet(f_short_name) spamReader = csv.reader(open(filename, 'rb')) for rowx, row in enumerate(spamReader): for colx, value in enumerate(row): ws.write(rowx, colx, value) wb.save("exceltest7.xls")
-28910929 0 You have several problems
You don't check if the file opened.
After fopen() you must ensure that you can read from the file, if fopen() fails, it returns NULL so a simple
if (file == NULL) return -1; would prevent problems in the rest of the program.
Your while loop only contains one statement because it lacks braces.
Without the braces your while loop is equivalent to
while (fgets(buf, sizeof(buf), file)) { ptr = strtok(buf, "f"); } You don't check that strtok() returned a non NULL value.
If the token is not found in the string, strtok() returns NULL, and you passed the returned pointers to atol anyway.
That would cause undefined behavior, and perhaps a segementation fault.
You don't check if there was an argument passed to the program but you still try to compare it to a string. Also potential undefined behavior.
I don't know if the following program will do what you need since it's your own program, I just made it safer, avoided undefined behavior
#include <ncurses.h> #include <stdlib.h> #include <string.h> #include <stdio.h> int main(int argc, char * argv[]) { char buf[100]; char *ptr; char *ptr2; char *ptr3; char *ptr4; int a; int b; int c; int d; FILE *file; initscr(); cbreak(); noecho(); if (argc > 1) { file = fopen(argv[1], "r"); if (file == NULL) return -1; while (fgets(buf,100,file) != NULL) { ptr = strtok(str,"f"); ptr2 = strtok(NULL," "); ptr3 = strtok(NULL,"f"); ptr4 = strtok(NULL," "); if (ptr != NULL) a = atoi(ptr); if (ptr2 != NULL) b = atoi(ptr2); if (ptr3 != NULL) c = atoi(ptr3); if (ptr4 != NULL) d = atoi(ptr4); } } refresh(); getchar(); endwin(); return 0; }
-20892832 0 You can pass in a function to compute the Jacobian as the Dfun argument to the Minimizer.leastsq method: http://lmfit.github.io/lmfit-py/fitting.html#leastsq
By default the function passed in for Dfun should return an array with the same number of rows as parameters, and each row the derivative with respect to each parameter being fitted. Make sure to specify the parameters with a Parameters object so that the parameters are treated in the correct order. I believe this this necessary IIRC though it might not matter.
in a page i have 2 forms where both having a hidden field named operation(same name for both form)
included jquery.min-1.5.js & jquery-ui.min-1.8.js <script> $(document).ready(function(){ $('#get_val').live('click', function() { alert($('#operation').val()); }); }); </script> <form id="form_como" name="form_como" action="go.php" method="post"> //some code..... <input type="hidden" name="operation" id="operation" value="first"> <input type="button" name="get_val" id="get_val" value="Get Val"/> </form> <br /> <form id="form_como2" name="form_como2" action="" method="post"> //some code..... <input type="hidden" name="operation" id="operation" value="second"> <input type="button" name="get_val" id="get_val" value="Get Val"/> </form> When i click "Get Val" button i always get 'first" (for both cases). but i need the value of the button which one i have clicked.
-12736412 0Add c:/PROGRA~1/Java/JDK16~1.0_3\bin\ to Path environment variable
-6270084 0 What's the best way to support array column types with external tables in hive?So i have external tables of tab delimited data. A simple table looks like this:
create external table if not exists categories (id string, tag string, legid string, image string, parent string, created_date string, time_stamp int) ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t' LOCATION 's3n://somewhere/'; Now I'm adding another field to the end, it will be a comma separated list of values.
Is there a way to specify this in the same way that I specify a field terminator, or do I have to rely on one of the serdes?
eg:
...list_of_names ARRAY<String>) ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t' ARRAY ELEMENTS SEPARATED BY ',' ... (I'm assuming I'll need to use a serde for this, but I figured there wasn't any harm in asking)
-25324051 0One problem is that totalwtax is not being calculated correctly because any items that are zero rated for tax are not included in the total. Changing the else clause to this:
else { double newprice = Double.parseDouble(price); totalwtax +=newprice; shoppingcart.put(item, price); } Produces this output for your test case:
Please enter an item.standard Please enter the price for standard: 12.49 Would you like to continue to add items? (Type Y) for Yes and (Type N) for No.y Please enter an item.music Please enter the price for music: 14.99 Would you like to continue to add items? (Type Y) for Yes and (Type N) for No.y Please enter an item.discount Please enter the price for discount: 0.85 Would you like to continue to add items? (Type Y) for Yes and (Type N) for No.n Your cart contains the following at items with tax{music=16.489, standard=12.49, discount=0.85} Total Tax: 29.829 This still isn't exactly the same as the expected answer because the expected answer assumes some rounding in the calculation. You would either need to round the values yourself or it might be appropriate to use a Money class so that all the fractions of cents are correctly accounted for.
-28009396 0If you got caffe from git you should find in data/ilsvrc12 folder a shell script get_ilsvrc_aux.sh.
This script should download several files used for ilsvrc (sub set of imagenet used for the large scale image recognition challenge) training.
The most interesting file (for you) that will be downloaded is synset_words.txt, this file has 1000 lines, one line per class identified by the net.
The format of the line is
-13450229 0nXXXXXXXX description of class
jQuery(document).ready(function () { jQuery(".btnshow").click(function () { var pagename, pid; pid=jQuery(this).attr('rel'); pagename="<?php echo JURI::root();?>index.php?option=com_componentname&view=result&Id="+pid; jQuery.get(pagename, function (data) { jQuery('.para1').html(data); }); }); }); <a href="JavaScript:void(0);" rel="<?php echo $id; ?>" title="<?php echo $id; ?>"><img src="<?php echo $image; ?>" alt="" /></a>
-20591374 0 Transparent frame in windows phone 8 / XAML I have two frames, main.xaml and target.xaml. I navigated to target.xaml from main.xaml. target.xaml has some content in a little square. Now I want that besides this square the rest of the area(of target.xaml frame) should be transparent(It should show main.xaml). I could not found any solution. Please help me. Are "opacity" or something like "isFullScreen" can help ?
-4880472 0 Printing with the browser in Silverlight 4I have a Silverlight 4 app which is essentially a canvas filled with user-drawn controls. When I use Print (or Print Preview) in Firefox 3.6, the canvas is not displayed.
Every example wrt printing in Silverlight creates a Print button within their Silverlight app. Isn't there a browser event I can hook into (or something) so that the user can print from the browser instead of the application?
-14083692 0 How to autheticate once in google drive apiI have this problem about google drive. This is my application 
As you can see here. I want to browse and upload the file to google drive. But every time I upload a file i need to allow and copy the authentication to my application.. like here
Is it possible to allow access once? Is there any other way to fix this? Can i automatically allow access to the authentication code within my application so that i may not use the browser??
-4191293 0StringTokenizer treats consecutive delimiters as a single delimiter. You say the input contains [tab space] as delimiters, but the rest of your code doesn't seem to be expecting spaces so, without more information, I'm going to guess that the input is delimited only with tabs (not [tab space]), and the adjacent delimiters are being ignored, Then the last nextToken() throws an exception which you are ignoring.
The answer here is to rewrite this using split(), as recommended in the Javadoc
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
That said, you should look at any of the existing CSV libraries out there (Google for Java CSV).
-30458538 0It seems like a very specialized/unusual use case. It violates LSP. And using exceptions at all is unidiomatic in scala - scala.util.control.Exception is mainly about catching exceptions that library functions might throw and translating them into more idiomatic expressions of potential failures.
If you want to do this then write your own code for it - it should be pretty straightforward. I really don't think this is a common enough use case for there to be a standard library function for it.
-21299032 0If you want your AJAX request to retrieve and execute code, use dataType: 'script'.
Appending script to the DOM isn't going to do anything.
See the documentation:
-15263602 0dataType:
...
"script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests.
...
It will look something like this in your AppDelegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; WebViewController *webViewController1 = [[WebViewController alloc] initWithPDFAtURL:@"urlToPDF1"]; WebViewController *webViewController2 = [[WebViewController alloc] initWithPDFAtURL:@"urlToPDF2"]; WebViewController *webViewController3 = [[WebViewController alloc] initWithPDFAtURL:@"urlToPDF3"]; UITabBarController *tabBarController = [[UITabBarController alloc] init]; [tabBarController setViewControllers:[NSArray arrayWithObjects:webViewController1, webViewController2, webViewController3, nil]]; self.window.rootViewController = tabBarController; [self.window makeKeyAndVisible]; return YES; } You will need to have a view controller that holds the UIWebView, and could look something like:
// WebViewController.h @interface WebViewController : UIViewController @end // WebViewController.m @interface WebViewController () @property (nonatomic, strong) NSURL *_pdfURL; @end @implementation WebViewController @synthesize _pdfURL; - (id)initWithPDFAtURL:(NSURL *)url { self = [super init]; if (self) { _pdfURL = url; } return self; } - (void)viewDidLoad { [super viewDidLoad]; // Load the PDF into a UIWebView }
-12416880 0 Getting names from ... (dots) In improving an rbind method, I'd like to extract the names of the objects passed to it so that I might generate unique IDs from those.
I've tried all.names(match.call()) but that just gives me:
[1] "rbind" "deparse.level" "..1" "..2" Generic example:
rbind.test <- function(...) { dots <- list(...) all.names(match.call()) } t1 <- t2 <- "" class(t1) <- class(t2) <- "test" > rbind(t1,t2) [1] "rbind" "deparse.level" "..1" "..2" Whereas I'd like to be able to retrieve c("t1","t2").
I'm aware that in general one cannot retrieve the names of objects passed to functions, but it seems like with ... it might be possible, as substitute(...) returns t1 in the above example.
I am newbie to php, just starting learning it, while working with wordpress.
I want to add html code to a php variable, a anchor tag link actually. First i splitted the text using substr(), and now i want to append a anchor tag at the end of post.
$json['timeline']['date'][$i]['text'] = substr(strip_tags($post->post_content), 0, 400)+"<a href='#'>Read more..</"; Well, I believe this is not the right way. Can anyone please guide me?
-33310972 0The HTMLFormElement object/type has an checkValidity method you can use to check that.
Check it here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement
-14335983 0I used my apple developer support for this. Here's what the support said :
The presence of the Voice I/O will result in the input/output being processed very differently. We don't expect these units to have the same gain levels at all, but the levels shouldn't be drastically off as it seems you indicate.
That said, Core Audio engineering indicated that your results may be related to when the voice block is created it is is also affecting the RIO instance. Upon further discussion, Core Audio engineering it was felt that since you say the level difference is very drastic it therefore it would be good if you could file a bug with some recordings to highlight the level difference that you are hearing between voice I/O and remote I/O along with your test code so we can attempt to reproduce in house and see if this is indeed a bug. It would be a good idea to include the results of the singe IO unit tests outlined above as well as further comparative results.
There is no API that controls this gain level, everything is internally setup by the OS depending on Audio Session Category (for example VPIO is expected to be used with PlayAndRecord always) and which IO unit has been setup. Generally it is not expected that both will be instantiated simultaneously.
Conclusion? I think it's a bug. :/
-22289802 0 Spring bean load error using spring-data-mongodbWe are using Spring version 3.2.0 and now introducing spring-data-mongodb version 1.4.0 in the codebase. I tried to write a new spring config file (mongo-config.xml) while solely defines mongodb related beans.
My Spring config is as follows:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xmlns:mongo="http://www.springframework.org/schema/data/mongo" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.4.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <mongo:mongoid="replicaSetMongo"replica-set="localhost:10901,localhost:10902"> <mongo:optionsconnections-per-host="8" ssl="false" /> </mongo:mongo> <mongo:db-factoryid="xmlLogDbFactory" mongo-ref="replicaSetMongo" dbname="logs" username="logs_owner" password="logs_owner" /> <mongo:mapping-converter> <mongo:custom-converters> <mongo:converter> <beanclass="com.utils.mongodb.dao.impl.SspLogsWriteConver ter"/> </mongo:converter> </mongo:custom-converters> </mongo:mapping-converter> <beanid="xmlLogTemplate"class="org.springframework.data.mongodb.core.MongoTempla te"> <constructor-argname="mongoDbFactory"ref="xmlLogDbFactory"/> <constructor-argname="mongoConverter"ref="mappingConverter"/> <propertyname="writeConcern"> <util:constantstatic-field="com.mongodb.WriteConcern.UNACKNOWLEDGED"/> </property> </bean> </beans> I deployed the application on JBoss. But JBoss given errors on startup as follows. Can someone help me what is going wrong? Is there a mismatch between spring version & spring-mongodb version? I noticed that the exception trace mentions spring-beans-3.2.0 jar even though the issue is with mongo-config.xml
Caused by: org.springframework.beans.factory.parsing.BeanDefi nitionParsingException: Configuration problem: Failed to import bean definitions from relative location [mongo-config.xml] Offending resource: class path resource [spring/commonUtil-config.xml]; nested exception is org.springframework.beans.factory.BeanDefinitionSt oreException: Unexpected exception parsing XML document from class path resource [spring/mongo-config.xml]; nested exception is org.springframework.beans.FatalBeanException: Invalid NamespaceHandler class [org.springframework.data.mongodb.config.MongoNames paceHandler] for namespace [http://www.springframework.org/schema/data/mongo]: problem with handler class file or dependent class; nested exception is java.lang.NoClassDefFoundError: org/springframework/data/repository/config/RepositoryConfigurationExtension at org.springframework.beans.factory.parsing.FailFast ProblemReporter.error(FailFastProblemReporter.java :68) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.beans.factory.parsing.ReaderCo ntext.error(ReaderContext.java:85) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.beans.factory.parsing.ReaderCo ntext.error(ReaderContext.java:76) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.beans.factory.xml.DefaultBeanD efinitionDocumentReader.importBeanDefinitionResour ce(DefaultBeanDefinitionDocumentReader.java:271) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.beans.factory.xml.DefaultBeanD efinitionDocumentReader.parseDefaultElement(Defaul tBeanDefinitionDocumentReader.java:196) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.beans.factory.xml.DefaultBeanD efinitionDocumentReader.parseBeanDefinitions(Defau ltBeanDefinitionDocumentReader.java:181) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.beans.factory.xml.DefaultBeanD efinitionDocumentReader.doRegisterBeanDefinitions( DefaultBeanDefinitionDocumentReader.java:140) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.beans.factory.xml.DefaultBeanD efinitionDocumentReader.registerBeanDefinitions(De faultBeanDefinitionDocumentReader.java:111) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.beans.factory.xml.XmlBeanDefin itionReader.registerBeanDefinitions(XmlBeanDefinit ionReader.java:493) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.beans.factory.xml.XmlBeanDefin itionReader.doLoadBeanDefinitions(XmlBeanDefinitio nReader.java:390) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.beans.factory.xml.XmlBeanDefin itionReader.loadBeanDefinitions(XmlBeanDefinitionR eader.java:334) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.beans.factory.xml.XmlBeanDefin itionReader.loadBeanDefinitions(XmlBeanDefinitionR eader.java:302) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.beans.factory.xml.DefaultBeanD efinitionDocumentReader.importBeanDefinitionResour ce(DefaultBeanDefinitionDocumentReader.java:255) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE] ... 36 more
-31200930 0 You can use insert_batch For Eg:
$data = array( array( 'title' => 'My title' , 'name' => 'My Name' , 'date' => 'My date' ), array( 'title' => 'Another title' , 'name' => 'Another Name' , 'date' => 'Another date' ) ); $this->db->insert_batch('mytable', $data); // Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'), ('Another title', 'Another name', 'Another date')
-34817913 0 You can do that with JavaScript/jQuery.
<form id="myform"> ... </form> $(".category").change(function(){ value = $(this).val() $('.myform').attr('action', "/search/" + value) }); Remember to place the code in a $(document).ready() listener.
Want to avoid JavaScript? You can get the value directly in the template. You cannot change that value if the user changes the dropdown value: in this case, your only chance is that of redirecting the user in your views.py based on what he choose in the dropdown.
Remember: Django simply renders a page and sends it to the user. Whatever happens before a new call is made to your server is not in the possibilities of Django but those of JavaScript.
-33938334 0 Weird SQL Server stored procedure behaviour - different results between asp.net and Management StudioWe have a stored procedure that’s used to populate a SSRS Report. It’s a bit of a monster – loads of conditional logic (in case statements), casts (sometimes embedded in other casts) from varchar to datetime, and 3 fields that rely on calls to a function that contains some date functions . The report contains financial information for a list of contracts for one organisation.
I need to create an asp.net page that shows a subset of the data for one organisation/contract so I cloned the sproc and added a contract parameter. However I noticed the figures for the 3 fields that rely on the function are different on the web page from when the stored procedure is run directly on the database or through the report.
To troubleshoot I created a page (quick and dirty using SqlDataSource and DataGrid) that shows the results of the original stored procedure showing all contracts. The query runs fine through Enterprise Manager but the web page crashes with the YSOD and the message
The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.
I even tried hardcoding the SQL from the stored procedure into the web page but still get the same results
On my dev machine the original stored procedure runs and my new stored procedure does return consistent results regardless of whether viewed through the web page or Management Studio. The regional settings etc are same on the dev server and live server. The only different thing I can think of is that the live web server and db server are on separate machines.
Has anyone come across anything like this before??
Thanks
-25363660 0 How to sum range of cells with the same formulas in excelI got a range of cells that use the same formula:
=A1*IF(B1="Yes",1,0) =A2*IF(B2="Yes",1,0) ... I would like to have one cell with the sum of all cells in a range of A1..A10
Any ideas?
Thanks
-25221754 0For making restaurant finder app , Follow following instructions like
Make sure that web services are ready (mainly JSON or XMl) then fetch them using either http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ or http://www.androidhive.info/2011/11/android-xml-parsing-tutorial/ turtorial
and show them in list or on Google maps (For Google maps you need latitude and longitude of particular restaurant )
-21341337 0With/Without _ref:
For each of these pages:
Is there any way to analyze app-crash minidumps (e.g. created by SetUnhandledExceptionFilter, or minidumpwritedump()) with source, using Visual Studio 2008 Express?
I generally do this at work using "real" versions of VS, but when trying to get it to work on my personal projects (using VS 2008 Express) it tells me "There is no source code available for the current location." and refuses to give me anything other than a disassembly window. Symbols for the app in question are loaded by the debugger, the "Debug Source Files" property page includes a pointer to the directory in which my source-code lives, but no dice.
Is it even possible to do this via the Express edition of VS 2008? If so, does anyone have any advice as to what else I could try to get this working?
-38283276 0It's the server's job to turn the URL encoded email address back into its original value. So your JavaScript is working perfectly, there's nothing to do there. Your server code is what needs to be fixed.
And if the application on the server isn't even decoding parameters before it's running the query against the database, it makes me feel like you may have some security issues to fix as well. Make sure that your parameters are decoded and cleaned before they are used in SQL queries. You can read more on cleaning parameters and SQL injection here.
-4374475 0 Regarding Good CSS forumi am looking for good css forum where i can post question an get answer very quickly like http://stackoverflow.com.
please provide me few url related with css forum.
-2607401 0Is the button within a form? It has to be within a form to do a post...
-40134888 0 SELECT ru.whs_code, ru.pdt_code, ru.case_dt_yyyymmdd, ru.fresh_frozen_status, ru.operation, ru.Qty - su.Qty AS Qty_Diff, ru.Wt - su.Wt AS Wt_Diff FROM ( SELECT whs_code, pdt_code, case_dt_yyyymmdd, fresh_frozen_status, operation, SUM(qty_cases_on_hand) AS Qty, SUM(qty_weight_on_hand) AS Wt FROM tbl_inventory_activity_rpt1 WHERE operation ='RU' GROUP BY whs_code,pdt_code,case_dt_yyyymmdd,fresh_frozen_status,operation ) ru, ( SELECT whs_code, pdt_code, case_dt_yyyymmdd, fresh_frozen_status, operation, SUM(qty_cases_on_hand) AS Qty, SUM(qty_weight_on_hand) AS Wt FROM tbl_inventory_activity_rpt1 WHERE operation ='SU' GROUP BY whs_code,pdt_code,case_dt_yyyymmdd,fresh_frozen_status,operation ) su WHERE ru.whs_code = su.whs_code AND ru.pdt_code = su.pdt_code AND ru.case_dt_yyyymmdd = su.case_dt_yyyymmdd AND ru.fresh_frozen_status = su.fresh_frozen_status AND ru.operation = su.operation;
-8817772 0 This will let the system decide which viewer to use..
System::Diagnostics::Process::Start("C:\\MyPdf.pdf");
-31325860 1 Dynamic Datasets and SQLAlchemy I am refactoring some old SQLite3 SQL statements in Python into SQLAlchemy. In our framework, we have the following SQL statements that takes in a dict with certain known keys and potentially any number of unexpected keys and values (depending what information was provided).
import sqlite3 import sys def dict_factory(cursor, row): d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d def Create_DB(db): # Delete the database from os import remove remove(db) # Recreate it and format it as needed with sqlite3.connect(db) as conn: conn.row_factory = dict_factory conn.text_factory = str cursor = conn.cursor() cursor.execute("CREATE TABLE [Listings] ([ID] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, [timestamp] REAL NOT NULL DEFAULT(( datetime ( 'now' , 'localtime' ) )), [make] VARCHAR, [model] VARCHAR, [year] INTEGER);") def Add_Record(db, data): with sqlite3.connect(db) as conn: conn.row_factory = dict_factory conn.text_factory = str cursor = conn.cursor() #get column names already in table cursor.execute("SELECT * FROM 'Listings'") col_names = list(map(lambda x: x[0], cursor.description)) #check if column doesn't exist in table, then add it for i in data.keys(): if i not in col_names: cursor.execute("ALTER TABLE 'Listings' ADD COLUMN '{col}' {type}".format(col=i, type='INT' if type(data[i]) is int else 'VARCHAR')) #Insert record into table cursor.execute("INSERT INTO Listings({cols}) VALUES({vals});".format(cols = str(data.keys()).strip('[]'), vals=str([data[i] for i in data]).strip('[]') )) #Database filename db = 'test.db' Create_DB(db) data = {'make': 'Chevy', 'model' : 'Corvette', 'year' : 1964, 'price' : 50000, 'color' : 'blue', 'doors' : 2} Add_Record(db, data) data = {'make': 'Chevy', 'model' : 'Camaro', 'year' : 1967, 'price' : 62500, 'condition' : 'excellent'} Add_Record(db, data) This level of dynamicism is necessary because there's no way we can know what additional information will be provided, but, regardless, it's important that we store all information provided to us. This has never been a problem because in our framework, as we've never expected an unwieldy number of columns in our tables.
While the above code works, it's obvious that it's not a clean implementation and thus why I'm trying to refactor it into SQLAlchemy's cleaner, more robust ORM paradigm. I started going through SQLAlchemy's official tutorials and various examples and have arrived at the following code:
from sqlalchemy import Column, String, Integer from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker Base = declarative_base() class Listing(Base): __tablename__ = 'Listings' id = Column(Integer, primary_key=True) make = Column(String) model = Column(String) year = Column(Integer) engine = create_engine('sqlite:///') session = sessionmaker() session.configure(bind=engine) Base.metadata.create_all(engine) data = {'make':'Chevy', 'model' : 'Corvette', 'year' : 1964} record = Listing(**data) s = session() s.add(record) s.commit() s.close() and it works beautifully with that data dict. Now, when I add a new keyword, such as
data = {'make':'Chevy', 'model' : 'Corvette', 'year' : 1964, 'price' : 50000} I get a TypeError: 'price' is an invalid keyword argument for Listing error. To try and solve the issue, I modified the class to be dynamic, too:
class Listing(Base): __tablename__ = 'Listings' id = Column(Integer, primary_key=True) make = Column(String) model = Column(String) year = Column(Integer) def __checker__(self, data): for i in data.keys(): if i not in [a for a in dir(self) if not a.startswith('__')]: if type(i) is int: setattr(self, i, Column(Integer)) else: setattr(self, i, Column(String)) else: self[i] = data[i] But I quickly realized this would not work at all for several reasons, e.g. the class was already initialized, the data dict cannot be fed into the class without reinitializing it, it's a hack more than anything, et al.). The more I think about it, the less obvious the solution using SQLAlchemy seems to me. So, my main question is, how do I implement this level of dynamicism using SQLAlchemy?
I've researched a bit to see if anyone has a similar issue. The closest I've found was Dynamic Class Creation in SQLAlchemy but it only talks about the constant attributes ("tablename" et al.). I believe the unanswered SQLalchemy dynamic attribute change may be asking the same question. While Python is not my forte, I consider myself a highly skilled programmer (C++ and JavaScript are my strongest languages) in the context scientific/engineering applications, so I may not hitting the correct Python-specific keywords in my searches.
I welcome any and all help.
-35718684 0Exactly like the error states, you are attempting to compare a bool (xx.Value) with a string ("rcat") which is not allowed for obvious reasons.
Note : When an object is cloned, PHP 5 will perform a shallow copy of all of the object's properties. Any properties that are references to other variables, will remain references.
Alternative you can use reflection to create a (deep) copy of your object.
$productClone = $this->objectManager->create('Tx_Theext_Domain_Model_Product'); // $product = source object $productProperties = Tx_Extbase_Reflection_ObjectAccess::getAccessibleProperties($product); foreach ($productProperties as $propertyName => $propertyValue) { Tx_Extbase_Reflection_ObjectAccess::setProperty($productClone, $propertyName, $propertyValue); } // $productAdditions = ObjectStorage property $productAdditions = $product->getProductAddition(); $newStorage = $this->objectManager->get('Tx_Extbase_Persistence_ObjectStorage'); foreach ($productAdditions as $productAddition) { $productAdditionClone = $this->objectManager->create('Tx_Theext_Domain_Model_ProductAddition'); $productAdditionProperties = Tx_Extbase_Reflection_ObjectAccess::getAccessibleProperties($productAddition); foreach ($productAdditionProperties as $propertyName => $propertyValue) { Tx_Extbase_Reflection_ObjectAccess::setProperty($productAdditionClone, $propertyName, $propertyValue); } $newStorage->attach($productAdditionClone); } $productClone->setProductAddition($newStorage); // This have to be repeat for every ObjectStorage property, or write a service.
-19926022 0 You are inserting means adding one row,, but you want to update,, so use UPDATE instead of INSERT
UPDATE user SET name = 'abc' WHERE id = 1;
-32017742 0 PHP cURL Upload file without processing I am trying to upload a file to a Rest API (Tableau Server Rest API) endpoint using PHP cURL.
The file upload procedure exists of three steps:
I was having issues with the server giving me a 500 status code on the second step. After contacting the support we figured out that the problem is most likely that the curl request seems to using the -data flag instead of the --data-binary flag which means some kind of encoding happens on the request body which should not be happening. This causes the server to respond with a 500 status code instead of an actual error message...
I would like to know how i can make a cURL request with the --data-binary flag in PHP.
Relevant sections of my current code:
// more settings $curl_opts[CURLOPT_CUSTOMREQUEST] = $method; $curl_opts[CURLOPT_RETURNTRANSFER] = true; $curl_opts[CURLOPT_HTTPHEADER] = $headers; $curl_opts[CURLOPT_POSTFIELDS] = $body; //more settings curl_setopt_array( $this->ch, $curl_opts ); $responseBody = curl_exec( $this->ch ); $method is "PUT", $headers contains an array with Content-Type: multipart/mixed; boundary=boundary-string and the $body is constructed like this:
$boundary = md5(date('r', time())); $body = "--$boundary\n"; $body .= "Content-Disposition: name='request_payload'\nContent-Type: text/xml\n\n"; $body .= "\n--$boundary\n"; $body .= "Content-Disposition: name='tableau_file'; filename='$fileName'\nContent-Type: application/octet-stream\n\n"; $body .= file_get_contents( $path ); $body .= "\n--$boundary--"; Where the $boundary is the same as the boundary-string in the content-type header. i am aware this is a kinda/very messy way to construct my body, i am planning to use Mustache as soon as i can actually upload my files :S
(i would like to mention that this is my first post here, please be gentle...)
-12458198 1 merging selenium rc and webdriverI have made most of my automation code using Selenium RC with Python. But, I feel that with the evolution in my product (what I'm testing through selenium RC), my automation needs are changed. I tried Wedriver with python and it works a treat with my product. But, as many features of my new product versions are inherited from the previous versions, I feel that I can make use of my existing Selenium RC code. But, for new features, I want to use Webdriver.
Moreover, there are also some things w.r.t the selenium profile that I 'm maintaining. Examples:
'trustallsslcertificates' parameter while starting selenium rc. Using trustallsslcertificates slows down the automation speed like hell.I also checked in the existing question: Selenium Web driver and selenium RC, but, the answer seems to old, many things must have updated by then.
Crux of my question is: Can I integrate my existing python code, that I use using selenium RC (Python bindings - selenium.py ), with Webdriver using python ?
PS: Currently I am using selenium 2.3.0.jar file
-27961615 0 Goals with same conversion rateI have a problem with my Google Analytics goals. I'm using Magento as CMS.
These are the funnels:
Goal 1:
Product page: something /product1 Cart: ^/checkout/cart/$ Customer details: ^/checkout/cart/step2/$ Destination: ^/checkout/onepage/success/
Goal 2:
Product page: something /product2 Cart: ^/checkout/cart/$ Customer details: ^/checkout/cart/step2/$ Destination: ^/checkout/onepage/success/
Both Goals have the same conversion rate. But, I can see in the Ecommerce Product Performance section that products in Goal 1 convert in much higher numbers then products in Goal 2. So the conversion rate should be different.
Why are the goals showing the same conversion rate? The CMS is Magento.
-11495884 0 carousel like with css, overflow-x (horizontal only)I have an overflow-x:scroll and overflow-y:hidden. I have images, but when I'm trying to make it only scroll horizontally, it doesn't work? When I highlight the images and drag the highlight downwards, its scrolls down vertically.
#contents { margin:0 auto; text-align:center; width:1200px; clear:both; } #image_contents { float:left; height: 208px; overflow-x:scroll; overflow-y:hidden; margin:0 auto; } .images { float:left; margin:2px; background:#000; overflow:hidden; position:relative; display:inline-block; } <div id="contents"> <div id="image_contents"> <div class="images"> <img src="1.jpg"/> </div> <div class="images"> <img src="2.jpg"/> </div> <div class="images"> <img src="3.jpg"/> </div> <!-- and so forth !-> </div> </div>
-38018805 0 You should initialize it before using or accessing it's properties. Try this:
let mark = TimeMark() let rounded = (mark.rawValue == TimeMark.Current)
-5001769 0 EmailsList.ToString()?
If it's your class, implement ToString() method the way you need.
function isBusinessDay(theDate){ theDay = theDate.getDay(); // Get day returns 0-6, respectively Sunday - Saturday if(theDay == 0 || theDay == 6){ return false; } else { return true; } } Use with zzzzBov's while (!isBusinessDay(date)) { date.setDate(date.getDate() - 1) }
A more concise way to write it :
function isBusinessDay(theDate){ theDay = theDate.getDay(); // Get day returns 0-6, respectively Sunday - Saturday if(theDay == 0 || theDay == 6) return false; return true; }
-10859098 0 why is php trim is not really remove all whitespace and line breaks? I am grabbing input from a file with the following code
$jap= str_replace("\n","",addslashes(strtolower(trim(fgets($fh), " \t\n\r")))); i had also previously tried these while troubleshooting
$jap= str_replace("\n","",addslashes(strtolower(trim(fgets($fh))))); $jap= addslashes(strtolower(trim(fgets($fh), " \t\n\r"))); and if I echo $jap it looks fine, so later in the code, without any other alterations to $jap it is inserted into the DB, however i noticed a comparison test that checks if this jap is already in the DB returned false when i can plainly see that a seemingly exact same entry of jap is in the DB. So I copy the jap entry that was inserted right from phpmyadmin or from my site where the jap is displayed and paste into a notepad i notice that it paste like this... (this is an exact paste into the below quotes)
"
バスにのって、うみへ行きました"
and obviously i need, it without that white space and breaks or whatever it is.
so as far as I can tell the trim is not doing what it says it will do. or im missing something here. if so what is it?
UPDATE: with regards to Jacks answer
the preg_replace did not help but here is what i did, i used the bin2hex() to determine that the part that "is not the part i want" is efbbbf i did this by taking $jap into str replace and removing the japanese i am expecting to find, and what is left goes into the bin2hex. and the result was the above "efbbbf"
echo bin2hex(str_replace("どちらがあなたの本ですか","",$jap)); output of the above was efbbbf but what is it? can i make a str_replace to remove this somehow?
-9964349 0Simplest way is to use a List1 to store your elements, and use Collections.shuffle() on it - and then take elements iteratively.
The shuffle produces a random permutation of the list, so chosing items iteratively gives you the same probability to chose any ordering, which seems to be exactly what you are after.
Code snap:
String[] picture = { "blue", "white", "red", "yellow" }; //get a list out of your array: List<String> picturesList = Arrays.asList(picture); //shuffle the list: Collections.shuffle(picturesList); //first picture is the first element in list: String pictureOne = picturesList.get(0); System.out.println(pictureOne); //2nd picture is the 2nd element in list: String pictureTwo = picturesList.get(1); System.out.println(pictureTwo); ... (1) Simplest way to get the list from an array is using Arrays.asList()
You could use sets for that, but a dict can not be added to a set unfortunately. You need to 'cast' the dictionaries to something that a set can handle, e.g. a immutable type such as a sequence of tuples. Combine that with an index to return the referenced dict:
def magicFunction(a, b): a = [tuple(sorted(d.items())) for d in a] b = [tuple(sorted(d.items())) for d in b] return [dict(kvs) for kvs in set(a).difference(b)] Result:
>>> firstDict = [{'A':1 ,'B':1}, {'A':2 ,'B':2}] >>> secondDict = [{'A':3 ,'B':3}, {'A':2 ,'B':2}] >>> magicFunction(firstDict, secondDict) [{'A': 1, 'B': 1}] >>> magicFunction(secondDict, firstDict) [{'A': 3, 'B': 3}]
-27043560 0 My TYPO3 extension's plugin is not visible in the backend I am new to TYPO3 , I started by creating my own extension using Extbase , the extension was successfully created and I could include it into the template of my site , now when I try to include its plugin to a page .. it's not there . I tried many times to delete the cache , and nothing changes ..
The extension's folder as well as it's mysql table were created without any problem .. but this story of the plugin made me really unconfortable.
Does any one know what could be the issue ? and I would also appreciate it if someone could give me a great tutorial on how to build your own TYPO3 extensions .
Thank you so much
Ps : I'm using TYPO3 6.2
-31836477 0The default Haar cascade trainings are:
If you need a custom one, you can train your own following these instructions
-4930397 0Maybe mine is not the best answer, but i just trying to help you here.
After doing a flash googling i found this site http://nixboxdesigns.com/demos/jquery-uploadprogress.php that look like promising to solve your problem. It can handle multiple upload and of course its do ajax upload too.
My tips here is just try the demo http://nixboxdesigns.com/demos/jquery-uploadprogress-demo.php first using all of your own browser. If the result is fine then work with this plugin maybe resolve your problem on browser compatibility.
-13847220 0 How can I create virtuals for REST API in MongooseI have a User model. And there is a follower relationship.
What I want is, when client requests for followers of the user, I should return the followers, and append if the follower is followed by the current user.
What is the good way to do that?
-28374282 0Take a look at
http://www.realtimerendering.com/intersections.html
Lot of help in determining intersections between various kinds of geometry
http://geomalgorithms.com/code.html also has some c++ functions one of them serves your purpose
-19935257 0On the link that you gave the joins are explained very good. So the problem is that you have several records from table A (no matter that there are no duplicates) is that to 1 record in A there are 2 records in B (in some cases). To avoid this you can use either DISTINCT clause, either GROUP BY clause.
You shoud use django-dirtyfields and send email immediately or add this job_id to RQ. Full docs here
Or update updated_at field only when status changes (again django-dirtyfields) by write own save() method like.
def save(self): if self.status = 'aproved' and 'status' in self.get_dirty_fields(): # add to RQ # or set updated_at = datetime.now() # if you dont use on_update=datetime.now super(...).save()
-40750590 0 You need to use AsyncHTTPTestCase, not just AsyncTestCase. A nice example is in Tornado's self-tests:
You need to implement get_app to return an application with the RequestHandler you've written. Then, do something like:
class TestRESTAuthHandler(AsyncHTTPTestCase): def get_app(self): # implement this pass def test_http_fetch_login(self): data = urllib.parse.urlencode(dict(username='admin', password='123456')) response = self.fetch("http://localhost:8080//#/login", method="POST", body=data) # Test contents of response self.assertIn("Automation web console", response.body) AsyncHTTPTestCase provides convenient features so you don't need to write coroutines with "gen.coroutine" and "yield".
Also, I notice you're fetching a url with a fragment after "#", please note that in real life web browsers do not include the fragment when they send the URL to the server. So your server would see the URL only as "//", not "//#/login".
-35035493 0 Spark Streaming - HBase Bulk LoadI'm currently using Python to bulk load CSV data into an HBase table, and I'm currently having trouble with writing the appropriate HFiles using saveAsNewAPIHadoopFile
My code currently looks as follows:
def csv_to_key_value(row): cols = row.split(",") result = ((cols[0], [cols[0], "f1", "c1", cols[1]]), (cols[0], [cols[0], "f2", "c2", cols[2]]), (cols[0], [cols[0], "f3", "c3", cols[3]])) return result def bulk_load(rdd): conf = {#Ommitted to simplify} keyConv = "org.apache.spark.examples.pythonconverters.StringToImmutableBytesWritableConverter" valueConv = "org.apache.spark.examples.pythonconverters.StringListToPutConverter" load_rdd = rdd.flatMap(lambda line: line.split("\n"))\ .flatMap(csv_to_key_value) if not load_rdd.isEmpty(): load_rdd.saveAsNewAPIHadoopFile("file:///tmp/hfiles" + startTime, "org.apache.hadoop.hbase.mapreduce.HFileOutputFormat2", conf=conf, keyConverter=keyConv, valueConverter=valueConv) else: print("Nothing to process") When I run this code, I get the following error:
java.io.IOException: Added a key not lexically larger than previous. Current cell = 10/f1:c1/1453891407213/Minimum/vlen=1/seqid=0, lastCell = /f1:c1/1453891407212/Minimum/vlen=1/seqid=0 at org.apache.hadoop.hbase.io.hfile.AbstractHFileWriter.checkKey(AbstractHFileWriter.java:204)
Since the error indicates that the key is the problem, I grabbed the elements from my RDD and they are as follows (formatted for readability)
[(u'1', [u'1', 'f1', 'c1', u'A']), (u'1', [u'1', 'f2', 'c2', u'1A']), (u'1', [u'1', 'f3', 'c3', u'10']), (u'2', [u'2', 'f1', 'c1', u'B']), (u'2', [u'2', 'f2', 'c2', u'2B']), (u'2', [u'2', 'f3', 'c3', u'9']), . . .
(u'9', [u'9', 'f1', 'c1', u'I']), (u'9', [u'9', 'f2', 'c2', u'3C']), (u'9', [u'9', 'f3', 'c3', u'2']), (u'10', [u'10', 'f1', 'c1', u'J']), (u'10', [u'10', 'f2', 'c2', u'1A']), (u'10', [u'10', 'f3', 'c3', u'1'])] This is a perfect match for my CSV, in the correct order. As far as I understand, in HBase a key is defined by {row, family, timestamp}. Row and family are combination are unique and monotonically increasing for all entries in my data, and I have no control of the timestamp (which is the only problem I can imagine)
Can anybody advise me on how to avoid/prevent such problems?
-4689977 0Just assuming: did you put a ; at the end of the #define ? Remove that, it will be put where you use MAXZOOM.
So instead of
#define MAXZOOM 2.0f; make it
#define MAXZOOM 2.0f
-38774618 0 You're setting a foreign key for cards table with the column user_id. But you haven't created a reference yet. Create a reference and then add foreign key to maintain referential integrity. Rollback and modify your migration with
1 class AddUserIdToCard < ActiveRecord::Migration[5.0] 2 def change 3 add_reference :cards, :users, index:true 4 add_foreign_key :cards, :users 5 end 6 end Line 3 will create, in the cards table, a reference to id in the users table (by creating a user_id column in cards).
Line 4 will add a foreign key constraint to user_id at the database level.
For more, read Add a reference column migration in Rails 4
-37241457 0 Dependency property inside viewmodel in PrismIs there any way to declare dependency property inside viewmodel? I want to declare a dependency property inside viewmodel and change it's value through command.
public class MyViewModel : Prism.Windows.Mvvm.ViewModelBase { public bool IsPaneVisible { get { return (bool)GetValue(IsPaneVisibleProperty); } set { SetValue(IsPaneVisibleProperty, value); } } public static readonly DependencyProperty IsPaneVisibleProperty = DependencyProperty.Register("IsPaneVisible", typeof(bool), typeof(MyViewModel), new PropertyMetadata(0)); public ICommand VisibilityChangeCommand { get; set; } public MyViewModel() { VisibilityChangeCommand = new DelegateCommand(OnVisibilityChange); } private void OnVisibilityChange() { IsPaneVisible = !IsPaneVisible; } } Problem is, I am getting some compilation error in IsPaneVisible' getter/setter : "GetValue does not exist in the current context". Is there any alternative way to do this?
-24278474 0 containsKey check for hashmapI have read multiple posts to understand this, but I can't seem to quite get in on why we do a check if a map does not contain a key before performing a put operation? For eg,
if(!myMap.containsKey(myKey) { myMap.put(myKey,myValue); } Why do we need this check? Either way, map doesn't allow duplicate key, and replaces the key with the new value if the key already exists. So why do we need to check this explicitly? Is this check needed for all implementations of Map? I am sorry if this is a very basic question. I can't seem to find an answer to this exact question. If there are posts that answer this that I may have missed, please point me to them, and feel free to mark mine as duplicate.
-25491882 0Use i18n files at ISO 639-1 representation.
That files allow you have any languages and use each "labels" with Ti.Locale.getString().
Also, you can use a require of file at app.js and put this variable like global.
language.js (for example):
var language = (function() { var self = { currentLanguage: 'en' // by default }; var labels = { msgHello: { en: 'Hello World', es: 'Hola Mundo' } }; self.changeLanguage = function changeLanguage(newLanguage){ self.currentLanguage = newLanguage; }; self.getLabel = function getLabel(key, language){ if(typeof language !== 'undefined') { return labels[key][language]; } else return labels[key][self.currentLanguage]; }; return self; }()); module.exports = language; app.js (for example):
var appLanguage = require('language.js'); (function() { Ti.API.info("Language: "+appLanguage.currentLanguage); Ti.API.info("MSG Hello World (English): "+appLanguage.getLabel(msgHello)); Ti.API.info("MSG Hello World (Spanish): "+appLanguage.getLabel(msgHello, es)); }()); You can use appLanguage variable directly on any file.
-33488666 0 Path.GetFullPath returning wrong path in C#According to the MSDN docs, to get the full file path of a file use
var fileName = Path.GetFullPath("KeywordsAndPhrases.txt"); Which I would assume delivers the full path of that file for the project it is in.
'K:\HeadlineAutoTrader\Autotrader.Infrastructure.HeadlineFeeds\Data\KeywordsAndPhrases.txt'
Which it doesn't, it returns;
'K:\HeadlineAutoTrader\AutotraderTests\bin\Debug\Data\KeywordsAndPhrases.txt'
which somewhat makes sense as the code I'm testing is being run in the test project.
So the question is how does one get the full filepath of a text file in a folder in another class library within the same solution?
This is a WPF based project, obviously it would be easier in a web app as Server.MapPath works great
-19181204 0Hi there this looks quite komplex but if you are willing to use GSON this could be converted to a JAVA Object with just a few lines.
-6363893 0 Separate debug/release output in FlashDevelopI want to have separate output directories for debug and release builds. However, I don't see any proper option in FlashDevelop. Is this thing achievable, and if so, how to do this? If not, how to determine if current build is compiled as debug or release?
-23609178 0As IntelliJ IDEA suggest when extracting constant - make static inner class. This approach works:
@RequiredArgsConstructor public enum MyEnum { BAR1(Constants.BAR_VALUE), FOO("Foo"), BAR2(Constants.BAR_VALUE), ..., BARn(Constants.BAR_VALUE); @Getter private final String value; private static class Constants { public static final String BAR_VALUE = "BAR"; } }
-16117699 0 Unable to obtain JDBC connection from datasource I was trying to run the following command in gradle and it gave me the following error :
c:\gsoc\mifosx\mifosng-provider>gradle migrateTenantListDB -PdbName=mifosplatfor m-tenants Listening for transport dt_socket at address: 8005 :migrateTenantListDB FAILED FAILURE: Build failed with an exception. * Where: Build file 'C:\gsoc\mifosx\mifosng-provider\build.gradle' line: 357 * What went wrong: Execution failed for task ':flywayMigrate'. > Unable to obtain Jdbc connection from DataSource * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. BUILD FAILED Total time: 13.843 secs The script file is here and the line no. of error is shown as 357 but I dont know why it is showing me an error. Is it something about incorrect configuration in mysql server please help me out here: script:
task migrateTenantListDB<<{ description="Migrates a Tenant List DB. Optionally can pass dbName. Defaults to 'mifosplatform-tenants' (Example: -PdbName=someDBname)" def filePath = "filesystem:$projectDir" + System.properties['file.separator'] + '..' + System.properties['file.separator'] + 'mifosng-db' + System.properties['file.separator'] + 'migrations/list_db' def tenantsDbName = 'mifosplatform-tenants'; if (rootProject.hasProperty("dbName")) { tenantsDbName = rootProject.getProperty("dbName") } flyway.url= "jdbc:mysql://localhost:3306/$tenantsDbName" flyway.locations= [filePath] flywayMigrate.execute() }
-26835497 0 If you want to assign the result to a List(Of String) variable then you need a List(Of String) object. You can all ToList on any enumerable list to create a List(Of T).
Also, your AsEnumerable call is pointless because Cast(Of T) already returns an IEnumerable(Of T).
Finally, declaring a variable on one line and then setting its value is so unnecessarily verbose. It's not wrong but it is pointless. In your case, not only are you declaring a variable but you're also creating an object that you never use. Don't create a New object if you don;t actually want a new object, which you don;t because you're getting an object on the very next line.
Dim list As List(Of String) = chkparameter.Items. Cast(Of ListItem). Where(Function(x) x.Selected). Select(Function(x) x.Value). ToList() There's also no need to declare the type of the variable because it will be inferred from the initialising expression, i.e. ToList returns a List(Of String) so the type of the variable can be inferred from that. Not everyone likes to use type inference where it's not completely obvious though, so I'll let you off that one. I'd tend to do this though:
Dim list = chkparameter.Items. Cast(Of ListItem). Where(Function(x) x.Selected). Select(Function(x) x.Value). ToList() By the way, notice how much easier the code is to read with some sensible formatting? If you're going to use chained function syntax like that, it's a very good idea to put each function on a different line once you get more than two or three.
-27788994 0You can download the Visual FoxPro runtime installers here:
http://vfpx.codeplex.com/releases/view/194354
Versions available for downlaod are:
VFP6 SP5 VFP7 SP1 VFP8 SP1 VFP9 SP2
-22923333 0 calling setBackgroundColor on UILabel causes crash Okay so I have been pulling my hair out, TRYING to find the cause of this problem in my code, and I've narrowed it down to a single line. The problem is, it doesn't make any sense. I create a UIViewController and put this code in the init method
- (id)init { [super init]; [self.view setBackgroundColor:[UIColor groupTableViewBackgroundColor]]; iCodeAppDelegate*appDelegate = [[UIApplication sharedApplication] delegate]; UIWindow*window = appDelegate.window; int headerY = appDelegate.rootNavigator.navigationBar.bounds.size.height;// + [UIApplication sharedApplication].statusBarFrame.size.height; //project options table int tableOffsetY = 250; UITableView* projectOptions = [[UITableView alloc] initWithFrame:CGRectMake(0, headerY+tableOffsetY, window.bounds.size.width, window.bounds.size.height-(headerY+tableOffsetY)) style:UITableViewStyleGrouped]; projectOptions.delegate = self; projectOptions.dataSource = self; projectOptions.scrollEnabled = NO; [self.view addSubview:projectOptions]; [projectOptions release]; //xcode logo image int centerX = window.bounds.size.width/2; int logoOffsetY = 8; int logoScale = 200; UIImage* xcodeLogo = [UIImage imageNamed:@"Images/xcode_logo.png"]; UIImageView* xcodeLogoView = [[UIImageView alloc] initWithFrame:CGRectMake(centerX-(logoScale/2), headerY+logoOffsetY, logoScale, logoScale)]; [xcodeLogoView setImage:xcodeLogo]; //[xcodeLogoView setBackgroundColor:[UIColor groupTableViewBackgroundColor]]; [self.view addSubview:xcodeLogoView]; [xcodeLogo release]; [xcodeLogoView release]; //"Welcome to Minicode" text int welcomeLabelHeight = 50; UILabel*welcomeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, headerY+logoScale+8, window.bounds.size.width, welcomeLabelHeight)]; [welcomeLabel setText:@"Welcome to miniCode"]; [welcomeLabel setTextColor:[UIColor darkGrayColor]]; [welcomeLabel setTextAlignment:UITextAlignmentCenter]; [welcomeLabel setBackgroundColor:[UIColor clearColor]]; [welcomeLabel setFont:[UIFont fontWithName: @"Trebuchet MS" size: 24.0f]]; [self.view addSubview:welcomeLabel]; [welcomeLabel release]; return self; } The problem lies in this specific line:
[welcomeLabel setBackgroundColor:[UIColor clearColor]]; if I comment it out, the code works fine, except that the label has a big white box behind it. I've scoured the internet, and it appears only one person has had a similar problem. The solution doesn't seem to have any sort of application to my code, however.
-3202374 0Yes, a class like
public Geo { private double lat; private double lon; } is sufficient to store a geographical location. You might want to add setter method to make sure, that lat, lon are always in a valid range, otherwise a Geo object might have an invalid state.
-1066657 0PageFunction ultimately derives from Page, so I'm fairly certain you can just use <Page.CommandBindings> to define your command bindings. Certainly you can use <Page.Resources> in a PageFunction to define its resources.
Why can't you use <PageFunction.CommandBindings>? I don't know, but I think you're probably right when you say it has to do with the fact that PageFunction is a generic type. You'd need some way in XAML to say what the underlying type is. I think that's possible in the .NET 4.0 version of XAML but not in the current version.
a good solution with ONE sql-query from http://henrik.nyh.se/2008/11/rails-jquery-sortables
# in your model: def self.order(ids) update_all( ['ordinal = FIND_IN_SET(id, ?)', ids.join(',')], { :id => ids } ) end
-34803679 0 You can use WTForms. See example below, pulled from Flask's documentation:
from wtforms import Form, BooleanField, TextField, PasswordField, validators class RegistrationForm(Form): username = TextField('Username', [validators.Length(min=4, max=25)]) email = TextField('Email Address', [validators.Length(min=6, max=35)]) password = PasswordField('New Password', [ validators.Required(), validators.EqualTo('confirm', message='Passwords must match') ]) confirm = PasswordField('Repeat Password') accept_tos = BooleanField('I accept the TOS', [validators.Required()]) See the link for the other snippets (view, template, etc).
-11060872 0Answer from Symform:
Thank you for contacting Symform support. I understand that you are needing the instructions to remove Symform from your Mac.
Here is the information:
Access the Terminal program on your Mac, by going to the search tool in the upper right-hand corner, and entering in Terminal.
Once Terminal is open, enter in the following command, depending on what you want to do:
Normal uninstall will only stop the services and remove the software. It will leave the service configuration and log files in place.
sudo /Library/Application\ Support/Symform/scripts/uninstall
To completely remove all aspects of the Symform software, configuration, and logs, a purging operation is available as well. This will remove any synchronization and contribution supporting files and directories too.
sudo /Library/Application\ Support/Symform/scripts/uninstall --purge
Signals that an end of file or end of stream has been reached unexpectedly during input. This exception is mainly used by data input streams to signal end of stream. Note that many other input operations return a special value on end of stream rather than throwing an exception.
and you can see that as below http://docs.oracle.com/javase/7/docs/api/java/io/EOFException.html
-6214523 0 Parsing URL jQuery AJAX formBasically i'm trying to send a video along with other info through jQuery to PHP to be written to a txt file to be read later.
There is a way of inputting a video url into this. I've got everything working except one thing.
If i put this through: http://www.youtube.com/watch?v=g1lBwbhlPtM it works fine.
but this: http://www.youtube.com/watch?v=g1lBwbhlPtM&feature=feedu doesn't.
I've done some tests and it's because when i send the second url through &feature=feedu gets read as a separate $_POST value.
This is the problem:
var dataString = 'title='+title+'&content='+content+'&date='+date+'&Submit=YES'; because its reading like
var dataString = 'title='+title+'&content='+IMAGES, TEXT AND STUFF+'&feature=feedu OTHER IMAGES AND STUFF&date='+date+'&Submit=YES';
it's out of a textarea that could include images or text and stuff so im looking for something like htmlspecialchars() to sort out that & before sending it through ajax
Any ideas how to solve this?
EDIT: Here's the full code that's the problem:
var title = $('input#title').val(); var content = $('textarea#content').val(); var date = $('input#date').val(); var dataString = 'title='+title+'&content='+content+'&date='+date+'&Submit=YES'; //alert (dataString);return false; $.ajax({ type: "POST", url: "./inc/php/file.php", dataType: "json", data: dataString, success: function(data) { if(data.error == true){ $('.errordiv').show().html(data.message); }else{ $('.errordiv').show().html(data.message); $(':input','#addstuff') .not(':button, :submit, :reset, :hidden') .val('') .removeAttr('checked') .removeAttr('selected'); } }, error: function(data) { $('.errordiv').html(data.message+' --- SCRIPT ERROR'); } }) return false; if content equals:
&content= <br>Text 1<br> <img>http://someimage.com/image.jpg</img> <br> Text2<br> <vid>http://www.youtube.com/watch?v=isDIHIHI&feature=feedu</vid> <br>Text 3<br> the content variable gets put through the ajax call as:
&content= <br>Text 1<br> <img>http://someimage.com/image.jpg</img> <br> Text2<br> <vid>http://www.youtube.com/watch?v=isDIHIHI with an extra variable that is
&feature=feedu</vid> <br>Text 3<br> So how do u stop the ajax reading &feature as a separate $_POST variable?
-37583824 0 How to integrate Citrus payment gateway without asking for login to user in ios?Hope you are doing well.
I am trying to integrate CitrusPay SDK to my iPhone application. How can i integrate CitrusPay Direct payment without asking user to login to citrus pay.
I want to give options to user like :
If user would like to pay using Citrus Wallet then i will ask user to login to citrus using their credentials. If they will go with 2nd or 3rd option like pay using Credit Card/Debit Card or net banking then they don't need to login.
I want to implement this function in my app using CitrusPay SDK. Can you point out me for the code of this?
I already have a demo of the Citrus pay and i already checked it.
https://github.com/citruspay/citruspay-ios-sdk
I downloaded the demo from the above link.
Please help me out for this.
-3691946 0vector<int> v; size_t len = v.size; nth_element( v.begin(), v.begin()+len/2,v.end() ); int median = v[len/2];
-27904177 0 uiimageview animation stops when user touches screen I have a UImageview with animated image. i am adding the uiimageview in code and its a part of a CollectionViewCell When the user touches the cell the animation stops, why does this happen?
code:
var images: [UIImage] = [] for i in 0...10 { images.append(UIImage(named: "image\(i)")) } let i = UIImageView(frame: CGRect(x: xPos, y: yPos, width: 200, height: 200)) i.animationImages = images i.animationDuration = 0.5 i.startAnimating() i.contentMode = UIViewContentMode.Center i.userInteractionEnabled = false self.addSubview(i)
-11655212 0 I think the confusion comes from the idea of normalizing "a value" as opposed to "a vector"; if you just think of a single number as a value, normalization doesn't make any sense. Normalization is only useful when applied to a vector.
A vector is a sequence of numbers; in 3D graphics it is usually a coordinate expressed as v = <x,y,z>.
Every vector has a magnitude or length, which can be found using Pythagora's theorem: |v| = sqrt(x^2 + y^2 + z^2) This is basically the length of a line from the origin <0,0,0> to the point expressed by the vector.
A vector is normal if its length is 1. That's it!
To normalize a vector means to change it so that it points in the same direction (think of that line from the origin) but its length is one.
The main reason we use normal vectors is to represent a direction; for example, if you are modeling a light source that is an infinite distance away, you can't give precise coordinates for it. But you can indicate where to find it from a particular point by using a normal vector.
-33090205 0I'm running ubuntu linux 14.04.
I entered, on the command line,
objdump -d untitled where 'untitled' is an executable file
It ran successfully with out any 'file truncated' message.
I entered, on the command line,
objdump -d untitled.o where 'untitled.o' is an object file
It ran successfully with out any 'file truncated' message.
Therefore, I strongly suspect the 'bufbomb' file is not a valid executable or object file.
-31955993 0 When cant a object be added to an objectTrying to add a value to a object. The object was generated from the start by a database request, containing a number of entires. A sample entry (say number 0) looks as follows:
{ _id: 55c8a069cca746f65c98369d, fulltext: 'Finance', alias: 'Finance', level: 0, fullurl: 'http://v-ghost.port0.org:808/dbfswiki/index.php/FMP', __v: 0, _parrent: [] } Now I want to add an additional array to this object. An empty structure where there will be a number of other listings. I started by using .push, but the object does not have a push function. This one has done a few rounds, so latest version below:
The structure I do want is:
{ _id: 55c8a069cca746f65c98369d, fulltext: 'Finance', alias: 'Finance', level: 0, fullurl: 'http://v-ghost.port0.org:808/dbfswiki/index.php/FMP', __v: 0, _parrent: [] childs: [] } I am not putting anything into childs at this point (childs because children seems to reserved, and while it might work, don't really want to try changing it when the code is already broken), basically just adding an empty slot to put similar objects into as part of later processing. Really weird Changed the code as follows: console.log ("Root record now " + rootRecord); rootRecord.childs = 1; console.log("Alias is " + rootRecord.alias); console.log("Child is " + rootRecord.childs); console.log("The complete structure is: \n"+rootRecord)
And I get the following output
Alias is Finance Child is 1 The complete structure is: { _id: 55c8a069cca746f65c98369d, fulltext: 'Finance', alias: 'Finance', level: 0, fullurl: 'http://v-ghost.port0.org:808/dbfswiki/index.php/FMP', __v: 0, _parrent: [] } So I can read rootRecord.childs, but its not listed, its almost as it is a "hidden" variable somehow.
The offending code
console.log("Creating root structure"); var roots = docs[doc]; console.log("Root from docs: \n" + docs[doc]) console.log("Sealed: " + Object.isSealed(docs[doc])); console.log("Frozen " + + Object.isFrozen(docs[doc])); console.log("Is Extendable: " + isExtendable(docs[doc])); console.log("Is Extensible(es6): " + Object.isExtensible(docs[doc])); for (var root in docs[doc]){ var rootRecord = docs[doc][root]; console.log ("Root record now " + rootRecord); rootRecord.childs = []; console.log("Now its " + rootRecord); returnStructure.push(rootRecord); console.log("returnStructure is now:\n" + returnStructure); console.log("And first id is " + returnStructure[0]['_id']) } Gives the following output:
Creating root structure Root from docs: { _id: 55c8a069cca746f65c98369d, fulltext: 'Finance', alias: 'Finance', level: 0, fullurl: 'http://v-ghost.port0.org:808/dbfswiki/index.php/FMP', __v: 0, _parrent: [] } Sealed: false Frozen 0 Is Extendable: true Is Extensible(es6): true Root record now { _id: 55c8a069cca746f65c98369d, fulltext: 'Finance', alias: 'Finance', level: 0, fullurl: 'http://v-ghost.port0.org:808/dbfswiki/index.php/FMP', __v: 0, _parrent: [] } Now its { _id: 55c8a069cca746f65c98369d, fulltext: 'Finance', alias: 'Finance', level: 0, fullurl: 'http://v-ghost.port0.org:808/dbfswiki/index.php/FMP', __v: 0, _parrent: [] } returnStructure is now: { _id: 55c8a069cca746f65c98369d, fulltext: 'Finance', alias: 'Finance', level: 0, fullurl: 'http://v-ghost.port0.org:808/dbfswiki/index.php/FMP', __v: 0, _parrent: [] } And first id is 55c8a069cca746f65c98369d Full source code
var mongoose = require("mongoose"); var morgan = require('morgan'); // log requests to the console (express4) var methodOverride = require('method-override'); // simulate DELETE and PUT (express4) var async = require('async'); mongoose.connect('mongodb://localhost/ResourceProfiles'); //var ObjectId = require('mongoose').ObjectID; var isExtendable = require('is-extendable'); var Schema = mongoose.Schema, ObjectId = Schema.ObjectId; var Profile = mongoose.model('Profile', { alias: String, img: String, name: String, summary: String, CV: String, keys: String, avail: String, agent: String, __v: {type: Number, select: false}, comp: { type: Number, default: 0 }, comn: { type: Number, default: 0 }, intp: { type: Number, default: 0 }, intn: { type: Number, default: 0 }, orgp: { type: Number, default: 0 }, orgn: { type: Number, default: 0 }, swep: { type: Number, default: 0 }, swen: { type: Number, default: 0 }, pssp: { type: Number, default: 0 }, pssn: { type: Number, default: 0 }, pep: { type: Number, default: 0 }, pen: { type: Number, default: 0 }, gtemp: { type: Number, default: 0 }, gtemn: { type: Number, default: 0 } }); var Skill = mongoose.model('Skill', { alias: String, fulltext: { type: String , required: true , unique: true }, fullurl: String, level: Number, _parrent: [{ type: ObjectId, ref: 'Skill'}], }) console.log("Lets see if we can't figure out this one once and for all"); var queries= []; var maxLevels = 1; [0,1,2,3,4].forEach(function(i){ console.log("Looking for "+ i) queries.push(function (cb) { console.log("Seaching for "+ i) Skill.find({level: i}).exec(function (err, docs) { if (err) { throw cb(err); } // do some stuff with docs & pass or directly pass it cb(null, docs); }); }); }) console.log("All requests generated"); async.parallel(queries, function(err, docs) { // if any query fails if (err) { throw err; } var returnStructure = []; console.log("This is what we got back") for (var doc in docs){ if ( docs[doc].length === 0 ){ console.log("No entries in level " + doc) } else { console.log("Processing " + docs[doc].length + " for level " + doc) if ( doc === "0" ) { console.log("Creating root structure"); var roots = docs[doc]; console.log("Root from docs: \n" + docs[doc]) console.log("Sealed: " + Object.isSealed(docs[doc])); console.log("Frozen " + + Object.isFrozen(docs[doc])); console.log("Is Extendable: " + isExtendable(docs[doc])); console.log("Is Extensible(es6): " + Object.isExtensible(docs[doc])); for (var root in docs[doc]){ var rootRecord = docs[doc][root]; console.log ("Root record now " + rootRecord); rootRecord.childs = []; console.log("Now its " + rootRecord); returnStructure.push(rootRecord); console.log("returnStructure is now:\n" + returnStructure); console.log("And first id is " + returnStructure[0]['_id']) } /*} else if ( doc === "1"){ var skills = docs[doc]; for (var skill in skills){ console.log("Need to find " + skills[skill].alias + " parrent " + skills[skill]._parrent); for (var root in returnStructure) { if ( returnStructure[root]["_id"].toString() === skills[skill]["_parrent"].toString()){ console.log("Found parrent " + returnStructure[root].alias); var newSkill = []; var childs = { childs: {}}; newSkill.push(skills[skill]); newSkill.push(childs); console.log("This is it " + returnStructure); returnStructure[root].childs.push(newSkill); } } console.log(returnStructure); } } else if ( doc === "2"){ var skills = docs[doc]; for (var skill in skills){ console.log("Need to find " + skills[skill].alias + " parrent " + skills[skill]._parrent); for (var root in returnStructure){ //var parrents= returnStructure[root].childs; for (var parrent in returnStructure[root].childs){ console.log("Lets compare \n" + returnStructure[root].childs[parrent]._id + "\n" + skills[skill]._parrent); if( returnStructure[root].childs[parrent]._id.toString() === skills[skill]["_parrent"].toString() ){ console.log("Hello found " + returnStructure[root].childs[parrent].childs); skills[skill].childs = []; console.log(skills[skill]) returnStructure[root].childs[parrent].childs.push(skills[skill]) } } } } */ } // } } } })
-10648709 0 I used RelayCommands and this has a constructor where you can create a canExecute Predicate and then if it returns false the bound button will be disabled automatically.
On the delegate command you should rewrite the CantDoAnything() method to represent your enable and disable logic. And the binding you should simply bind to the Command.
DelegateCommand constructor on MSDN
DelegateCommand CanExecute BugFix
-16838277 0Simple addition would work.
DateTime date = DateTime.Parse(txtStartDate.text) + DateTime.ParseExact(t3, "H:mm tt", CultureInfo.InvariantCulture).TimeOfDay;
-22456693 0 Most likely, the sequence of save and restore was incorrect. The table had attributes that shouldn't have been saved and should have been removed before saving. The restore has resulted in a database catalog on the new system with inconsistent elements.
If not, then the next likelihood (and just about the only other possibility) is that the database catalog had inconsistencies already before the restore was done. Those could have been introduced by improper shutdowns or other actions.
First step should be:
RCLDBXREF OPTION(*CHECK) If problems are reported, run:
RCLDBXREF OPTION(*FIX) If the system is too old for the RCLDBXREF command, use:
RCLSTG SELECT(*DBXREF) No "*CHECK" option is available for the older version.
Depending on size and complexity of your database, number of resynchronizations needed and general performance characteristics of your server, either of those can run from 10 minutes to a few hours. Most unexplained database catalog problems (other than those needing PTFs) can be cleared by either of those.
The RCLDBXREF command is usually preferred, but some problems will require the RCLSTG alternative. Significant restrictions exist for RCLSTG, so be sure to read the command [Help].
-32801656 0 How to run a server side JSI have a little question here. Is there any way to build a server side JS without any use of external software. The reason for this is I am not able to install any software on the webspace but I wanted to experiment with realtime communication with the server and another user for a game or something like this.
If someone knows a way to establish something like this I would be quite happy to hear about it.
EDIT: Guys NOT NodeJS I AM NOT ALLOWED TO INSTALL ANY OTHER SOFTWARE!
-21866826 0 Need Help Understanding Javascript ClosureI am learning about javascript closures and am having difficulty understanding the concept. If someone would be kind enough to guide me through this example, i.e., where inputs and outputs are going, I'd appreciate it.
var hidden = mystery(3); var jumble = mystery3(hidden); var result = jumble(2); function mystery ( input ){ var secret = 4; input+=2; function mystery2 ( multiplier ) { multiplier *= input; return secret * multiplier; } return mystery2; } function mystery3 ( param ){ function mystery4 ( bonus ){ return param(6) + bonus; } return mystery4; } results; Thank you.
-39164795 0Or in a more fashionable way:
string duration = String.Format($"{(int)seconds.TotalHours}:{seconds.Minutes}:{seconds.Seconds}"); *Edit: And also more readable
-25252744 0This code segment
int* ptr_int; *ptr_int = 10; is already wrong. Pointer ptr_int was not initialized. So the program has undefined behaviour.
To test your code you could write for example
int main() { int* ptr_int = new int( 10 ); test_session ( &ptr_int ); std::cout << "Hello, world!\n"; delete ptr_int; }
-22262694 0 How to extend a users session server side? I'm using SimpleMembership with ASP.NEt MVC.
I have a session time out of 30 minutes, on a sliding scale.
There are times that I would like to reset the timer for say user 105, without them clicking on a link, with server side logic. Is there a way I can reset a users session timer with server side code?
-13923097 0 Android Front-Facing Camera Preview SizeI have an app that I am working on that makes use of the front-facing camera on the device. I am trying to set the preview size by getting the list of supported preview sizes and looping through them looking for one that is pretty close. The method that I wrote to do so is basically the same as the one from the OS's own camera app. The method works fine, exactly how I would like it to, that's not why I am here.
I was having problems with the camera preview looking obviously skewed on some devices; either squishing or stretching the preview of the image. I couldn't figure out why it was doing this so I stepped through it and looked at all of the supported preview sizes available to my front-facing camera and found that there were only 2 and neither of them were the correct aspect to be usable. My "surfaceChanged" method in my SurfaceHolder.Callback class is reporting a width and height of 762x480 for the front-facing camera, but of the two supported preview sizes (acquired with cam.getParameters().getSupportedPreviewSizes()) both were in the opposite aspect: 480x800, 320x640.
With these as the only options, it seems impossible to have a preview for my front-facing camera that is not skewed. I know that in versions 2.3 or less, arbitrary values can be used for width and height without regard to supported sizes, but I am trying to make my app work for newer versions of the OS as well. How can I make the preview look correct?
-17567401 0 How to stop when a condition in if statement is satisfied, when debuggingHow to stop when a condition in if statement is satisfied, when debugging? For example:
if (!check()) { int a = 0; } The int a = 0; is dummy code and then I put a breakpoint there. If I put a breakpoint inside an empty if loop the debugger won't stop there, it only stops at instructions it can execute. Even if you do int a; just a declaration it won't stop.
Can I do this in other way rather than writing dummy code?
Thanks
-4030649 0Drupal help you build fast, and it looks like promising but fails to fullfil the needs of client, designer also programmer. You need to write one module page, and some functions.
5th solution you gave has little trouble than others. Write a function that to have "teaser like" behavior, I will return formatted node according to its type. Don't lay on drupal's teaser system. If teasers will have different heights, add height to teaser function.
-2503071 0 How to Implement Loose Coupling with a SOA ArchitectureI've been doing a lot of research lately about SOA and ESB's etc.
I'm working on redesigning some legacy systems at work now and would like to build it with more of a SOA architecture than it currently has. We use these services in about 5 of our websites and one of the biggest problems we have right now with our legacy system is that almost all the time when we make bug fixes or updates we need to re-deploy our 5 websites which can be a quite time consuming process.
My goal is to make the interfaces between services loosely coupled so that changes can be made without having to re-deploy all the dependent services and websites.
I need the ability to extend an already existing service interface without breaking or updating any of its dependencies. Have any of you encountered this problem before? How did you solve it?
-33929762 0I found that the Invoice resource was returning a type which ng-tables doesn't like. ng-tables version 0.4.3 expects a $defer object to be returned, so I had to wrap my query in a defer.resolve. Now it works.
$defer.resolve( Invoice.query params.url(), (data) -> orderedData = (if params.sorting then $filter('orderBy')(data, params.orderBy()) else data) # Sort return orderedData )
-5186492 0 Registering Custom WMI C# class/event I have a project with a class that extend a WMI event and used to publish data through WMI. the class look like this (just few rows of the entire class):
[InstrumentationClass(InstrumentationType.Instance)] public class PointInstrumentation { private bool enabled = true; // static data public string UserName { get; set; } public string EffectiveUserName { get; set; } public string Environment { get; set; } public string Universe { get; set; } public int AppProcessId { get; set; } public string ProcessName { get; set; } public string AppHostName { get; set; } public string Keyword { get; set; } public string Version { get; set; } public string OrbAddress { get; set; } public string ApiVersion { get; set; } ..
public void Publish() { System.Management.Instrumentation.Instrumentation.Publish(this); ..
as you can see, its extends using attribute declation "[InstrumentationClass(InstrumentationType.Instance)]"
my issue is that when i register the dll, i don't see PointInstrumentation class in the WMI explorer, hence, i can't query what is being published.
Can anyone please explain me what am i doing wrong and what the appropriate way to register WMI (c#) classes.
Thanks
-30670329 0The problem is that use paths are absolute, not relative. When you say use A; what you are actually saying is "use the symbol A in the root module of this crate", which would be lib.rs.
What you need to use is use super::A;, that or the full path: use foo::A;.
I wrote up a an article on Rust's module system and how paths work that might help clear this up if the Rust Book chapter on Crates and Modules doesn't.
-20872934 0ASCII code of '2' is 50, and so on.
I have created the certificate and drop to Keychain Access for testing the application in ios device.This worked fine ,but i have one problem ,i am export the certificate from keychain Access for phonegap application.Now the keychain Access showing a warning ("The “System Roots” keychain cannot be modified.") while i am dragging Development Push SSL Certificate to Keychain Access and the old Development Provisioning Profiles do not working now .The ios application with old Development Provisioning Profiles give an error "Command /usr/bin/codesign failed with exit code 1"
How can avoid this issue?
if anybody know please help me.
-27876649 0The error line is the last line of your models.py:
votes = models.IntegerField(default= It should be:
votes = models.IntegerField(default=0)
-15191234 0
- The building is a graph, rooms are vertices, hallways are edges connecting them. Therefore this is an undirected connected graph.
- You can solve this by getting the weight of graph's minimal spanning tree, then doing complete weight minus the weight of MST - the result is sum of weights of hallways that can be removed.
Yes, both of these are correct (modulo the nitpick that the building is not a graph with rooms as vertices and hallways as edges, but can be viewed as such). And if you view it thus, the difference between the total weight of the original graph and the total weight of a minimum spanning tree is the maximal possible reduction of weight without making some rooms unreachable from others (i.e. making the graph disconnected).
So I see two possibilities,
Without any further information, I would consider 1 more likely.
Is there any other way to solve this problem? I would happily try anything with the grading server.
Since you need to find the weight of an MST, I don't see how you could do it without finding an MST. So the other ways are different algorithms to find an MST. Kruskal's algorithm comes to mind.
-29641642 0Does it help when you force the time filter to kick in only after the client filter has run?
FI like in this example:
;WITH ClientData AS ( SELECT [E2].[CompanyId] ,[E2].[Time] ,[E1].[Id] ,[E1].[Status] FROM [dbo].[SplittedSms] AS [E1] INNER JOIN [dbo].[Sms] AS [E2] ON [E1].[SmsId] = [E2].[Id] WHERE [E2].[CompanyId] = 4563 AND ([E1].[NotifiedToClient] IS NULL) ) SELECT TOP 10 [CompanyId] ,[Id] ,[Status] FROM ClientData WHERE [Time] > '2015-04-10'
-29481926 0 Query that joins 3 tables CREATE TABLE User(uid INTEGER AUTO_INCREMENT,address VARCHAR(40),city VARCHAR(20),state VARCHAR(20), What Ive tried so far...
SELECT User.uid, Job.jobid, Protein.pid FROM User JOIN Job ON (Job.uid = User.uid) JOIN Protein ON (Job.pid = Protein.pid) I cant figure out how to find a job that utilizes all proteins.
-40673098 0Probably there is. Probably you can also use another callback on the application model which happens before, there are plenty of them. See Active Record Callbacks
However this is exactly the case, which other people call rails callback hell
The best practice here would be just creating a form object, which creates the data in the order you need and remove the callbacks
class ApplicationCommitmentForm include ActiveModel::Model attr_accessor ... def submit a = Application.create .. a.update_case_code a.commitments.create ... end end Btw you could also wrap the submit code into a transactions ensuring that either all records are created or in case of any errors nothing at all.
-11738876 0If the reader is reporting true from Read(), then your stored procedure is definitely returning a row (or rows).
If you call the SP directly (SSMS etc), that will quickly tell you whether a row is returned. A row with a null in every column is still a row. Two options:
For example. If the first column must be non-null for a "real" row, then simply:
if(!reader.IsDBNull(0)) Count++; Which ignores the row if the first cell is null.
-17246440 0This will capture the two square brackets \K\[\[(?>[^]]++|](?!]))]]*
Input Text
like [[ yes|ja ]] with Matches
[0] => [[ yes|ja ]] [1] => yes|ja I"m not a python programmer, but I think you'll want to modify your script to be like this:
$that = $this; $view = preg_replace_callback('~\K\[\[(?>[^]]++|](?!]))]]*~', function ($m) use ($that) { return $that->__($m[1]); }, $view);
-30188231 0 Just loop over the selections:
Sub Maja() Dim K As Long K = 1 vals = Array("3", "6", "9") For Each a In vals For Each b In vals For Each c In vals For Each d In vals For Each e In vals Cells(K, 1) = a & b & c & d & e K = K + 1 Next e Next d Next c Next b Next a MsgBox K End Sub A snap of the top of the list:

NOTE:
Technically, you would call these permutations rather than combinations because values like 33363 and 33336 both appear in the list as they represent different numerical values.
-12675403 0Because you haven't provided any definite HTML markup, only a generic description of your problem, I provide you a link to http://css-tricks.com/centering-in-the-unknown/ Here you can find various CSS techniques to center content both vertically and horizontally.
jQuery is not necessary to center content, I believe you will manage it with proper HTML markup coupled with some CSS.
Fiddle ( http://jsfiddle.net ) will be helpful, though.
-22209054 0Instead of checking the empty value it's better to check the length of the content
$("td").hover(function(){ var cell = $(this).html(); if(cell.length===0) $(this).css( "background-color", "orange"); else $(this).css( "background-color", "black"); });
-9431116 0 Please try following,
p elements are paragraphs - so they have a default property of display:block. Either use another element, for example a span. Alternatively you can change the display property of the p dom element, for example to display:inline.
Update - the property of vertical align 'vertical-align:middle' should be applied to the images.
Also - your nesting of styles seems wrong, see a working example below.
Example (updated): http://jsfiddle.net/YwV54/2/
-21373683 0On the basis that the else is there, no, it won't work.
For it to work how you wish it to, you'd need to remove the else and just use 2 if statements, such as;
// Set default values; $a = 2; $b = 0; // Check $a if( $a == 2 ) { // Change values $a = 0; $ b = 2; } // Check $b, which is now 2 due to the condition matching above if( $b == 2 ) { echo "Cool?"; } I believe you're slightly missing the point with the else.
It is used for condition matching, to confirm multiple possibilies.
For example, let's imagine a lottery, where the prize money is split into ranges;
Numbers 01 - 10 = $5. Numbers 11 - 20 = $10. Numbers 21 - 30 = $20.
You're code could look something like
<?php $random_result = mt_rand(0, 30); if ($random_number > 20) { $amount = 20; } else if ($random_number > 10) { $amount = 10; } else { $amount = 5; } echo 'The jackpot for today was $' . $amount . '!';
-37627989 0 Use the JavaScript JSON.Stringify() function. Example:
$.ajax({ method: "POST", url: "/yourController/yourAction", data: { name: "John", location: "Boston" } }).done(function( data ) { alert(JSON.Stringify(data)); });
-2595096 0 Since traversing a binary tree requires some kind of state (nodes to return after visiting successors) which could be provided by stack implied by recursion (or explicit by an array).
The answer is no, you can't. (according to the classic definition)
The closest thing to a binary tree traversal in an iterative way is probably using a heap
EDIT: Or as already shown a threaded binary tree ,
-4420170 0Honestly, no or at least not that I've run across. Whether you use your data (EF) models for the MVC model or not in either case you're going to have to decorate a bunch of classes (properties) with the attributes.
Personally I generally insert a business layer between my DAL (EF/NHibernate/etc.) and my UI layer (MVC) so my models in the UI are different from persistence. But I still end up with just as many (if not more) model classes with attributes as I have for the DAL.
This may not help in your situation but you may want to take a look at the new validation features coming with the next version of EF and see if the will help you any.
-19973785 0Ok, lets try to make sure that the image is visible in QWebView at all and you indeed have a problem with PDF conversion. So you need to run this and see if it works:
import sys from PyQt4 import QtGui, QtCore, QtWebKit class MyWin(QtGui.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setLayout(QtGui.QVBoxLayout()) self.view = QtWebKit.QWebView(self) self.layout().addWidget(self.view) self.view.setHtml(''' ... <img src="star.jpg" /> ... ''', QtCore.QUrl.fromLocalFile("/var/www/icons/") ) if __name__ == '__main__': app = QtGui.QApplication(sys.argv) win = MyWin() win.show() sys.exit(app.exec_())
-7795852 0 Don't know if it is steel relevant but here is the solution:
TextBox _textBox; protected override void SetupEditControls() { base.SetupEditControls(); _textBox = (TextBox)EditControl; var value = CustomerTypeBox.Value ?? string.Empty; if (String.IsNullOrEmpty(value.ToString())) { _textBox.Text = "Default text"; } else { _textBox.Text = value.ToString(); } if (_textBox != null) EditControl.Parent.Controls.Add(_textBox); } public override void ApplyEditChanges() { var customerTypeBoxValue = _textBox.Text; if (customerTypeBoxValue != null) { SetValue(customerTypeBoxValue); } } Default value for property is also possible to set in admin mode.
-5097088 0 How to copy MySQL table structure to table in memory?How to create a table in memory which is identical to "regular" table? I want a copy without indexes and constraints. Pure SQL (no external tools).
This works (however indexes are created):
create table t_copy (like t_original) This doesn't:
create table t_copy (like t_original) engine=memory
-22898036 0 You can use angular.bootstrap() directly... the problem is you lose the benefits of directives.
First you need to get a reference to the HTML element in order to bootstrap it, which means your code is now coupled to your HTML.
Secondly the association between the two is not as apparent. With ngApp you can clearly see what HTML is associated with what module and you know where to look for that information. But angular.bootstrap() could be invoked from anywhere in your code.
If you are going to do it at all the best way would be by using a directive. Which is what I did. It's called ngModule. Here is what your code would look like using it:
<!DOCTYPE html> <html> <head> <script src="angular.js"></script> <script src="angular.ng-modules.js"></script> <script> var moduleA = angular.module("MyModuleA", []); moduleA.controller("MyControllerA", function($scope) { $scope.name = "Bob A"; }); var moduleB = angular.module("MyModuleB", []); moduleB.controller("MyControllerB", function($scope) { $scope.name = "Steve B"; }); </script> </head> <body> <div ng-modules="MyModuleA, MyModuleB"> <h1>Module A, B</h1> <div ng-controller="MyControllerA"> {{name}} </div> <div ng-controller="MyControllerB"> {{name}} </div> </div> <div ng-module="MyModuleB"> <h1>Just Module B</h1> <div ng-controller="MyControllerB"> {{name}} </div> </div> </body> </html> You can get the source code for it at:
http://www.simplygoodcode.com/2014/04/angularjs-getting-around-ngapp-limitations-with-ngmodule/
It's implemented in the same way as ngApp. It simply calls angular.bootstrap() behind the scenes.
I am using ehcache to cache data, usually 24h expiration time. I want to take element individual actions at the time an element expires. Therefore i neee the element content. I registered a CacheEventListener in order to get a notification (notifyElementExpired) in case of element expiration. Unfortunately at notification time only the key is known - content is already discarded, which is kind of painful!
Any solution to access element content at expiration time?
-35331518 0This is a non-standard GCC extension. Many other compilers like Visual C++ don't support VLA.
-40807215 0 What is the role of the curly brace in this case in Perl?The following print statements are valid in accessing the 1st element of the array reference
my $aref = [6, 7, 8]; print $aref->[0]; print $$aref[0]; print ${$aref}[0]; What is the reason for allowing/using the curly brace in the 3rd print? Does it work by design or by chance?
-7770242 0If you are happy with SNI SSL support, no further configuration should be necessary. Use this gist to determine whether a request is made with an SSL-encrypted connection.
-21033349 0This is a bit old but I'm trying to find the same myself. The best I can find are:
http://www.mapquestapi.com/search/
Mapquest search has a data set which allows querying for tourist attractions. However I cannot find a way to sort the results by importance. Radius search returns results in order of proximity and I have no idea what order a rectangle search is in.
https://developers.google.com/places/documentation/search
Google places allows sorting by "prominence". This actually returns a list that is reasonably representative of the main places a tourist might want to see. You can filter out certain types to refine this.
http://en.wikipedia.org/wiki/Category:Visitor_attractions_in_Manhattan
Wikipedia has categories of "visitor attractions in__" for many cities. Being crowdsourced, there are lots of issues. For example, the Empire State Building which is one of the main attractions in Manhattan is not on this list, but some random little coffee shop Everyman Espresso is.
http://wikitravel.org/en/New_York_City#See
Wikitravel has a "see" section for most cities. There's no structure to it, but most of the attractions are bold, although this example shows a lot of other things that are bold like various passes.
http://www.geonames.org/export/wikipedia-webservice.html
Geonames has indexed all the geotagged Wikipedia articles and has a service to search it. It has a "rank" parameter, which could somewhat indicate the relative interestingness for tourists.
-31460945 0So, after some chat, here is my solution, hope this help: I made 2 .html files, a.html and b.html.
Content of a.html:
<div></div> <script> $.getScript("main.js", function() { $("div").load("b.html #items"); }); </script> And b.html:
<body> <script src="main.js"></script> </body> Also content of main.js file:
$('<div></div>', { text: 'I am alive !!!', id: '#items' }).appendTo('body'); and when I open the a.html, I can see I am alive !!!.
Edit:
Please note, I didn't add link of main.js to a.html.
UPDATE, same result with this code:
$.getScript("main.js").done(function() { load(); }).fail(function(jqxhr, settings, exception) { alert("Triggered ajaxError handler."); }); function load() { $("#Result").load("b.html #items", function(response, status, xhr) { if (status == "error") { var msg = "error: "; $("#error").html(msg + xhr.status + " " + xhr.statusText); } }); };
-1162850 0 I've had some success in solving this problem of mine. Here are the details, with some explanations, in case anyone having a similar problem finds this page. But if you don't care for details, here's the short answer:
Use PTY.spawn in the following manner (with your own command of course):
require 'pty' cmd = "blender -b mball.blend -o //renders/ -F JPEG -x 1 -f 1" begin PTY.spawn( cmd ) do |stdout, stdin, pid| begin # Do stuff with the output here. Just printing to show it works stdout.each { |line| print line } rescue Errno::EIO puts "Errno:EIO error, but this probably just means " + "that the process has finished giving output" end end rescue PTY::ChildExited puts "The child process exited!" end And here's the long answer, with way too many details:
The real issue seems to be that if a process doesn't explicitly flush its stdout, then anything written to stdout is buffered rather than actually sent, until the process is done, so as to minimize IO (this is apparently an implementation detail of many C libraries, made so that throughput is maximized through less frequent IO). If you can easily modify the process so that it flushes stdout regularly, then that would be your solution. In my case, it was blender, so a bit intimidating for a complete noob such as myself to modify the source.
But when you run these processes from the shell, they display stdout to the shell in real-time, and the stdout doesn't seem to be buffered. It's only buffered when called from another process I believe, but if a shell is being dealt with, the stdout is seen in real time, unbuffered.
This behavior can even be observed with a ruby process as the child process whose output must be collected in real time. Just create a script, random.rb, with the following line:
5.times { |i| sleep( 3*rand ); puts "#{i}" } Then a ruby script to call it and return its output:
IO.popen( "ruby random.rb") do |random| random.each { |line| puts line } end end You'll see that you don't get the result in real-time as you might expect, but all at once afterwards. STDOUT is being buffered, even though if you run random.rb yourself, it isn't buffered. This can be solved by adding a STDOUT.flush statement inside the block in random.rb. But if you can't change the source, you have to work around this. You can't flush it from outside the process.
If the subprocess can print to shell in real-time, then there must be a way to capture this with Ruby in real-time as well. And there is. You have to use the PTY module, included in ruby core I believe (1.8.6 anyways). Sad thing is that it's not documented. But I found some examples of use fortunately.
First, to explain what PTY is, it stands for pseudo terminal. Basically, it allows the ruby script to present itself to the subprocess as if it's a real user who has just typed the command into a shell. So any altered behavior that occurs only when a user has started the process through a shell (such as the STDOUT not being buffered, in this case) will occur. Concealing the fact that another process has started this process allows you to collect the STDOUT in real-time, as it isn't being buffered.
To make this work with the random.rb script as the child, try the following code:
require 'pty' begin PTY.spawn( "ruby random.rb" ) do |stdout, stdin, pid| begin stdout.each { |line| print line } rescue Errno::EIO end end rescue PTY::ChildExited puts "The child process exited!" end
-27015918 0 How about:
lines = out.lines do_something_1(lines.first) lines[1..-2].each do |line| do_something_2(line) end do_something_3(lines.last) This code will do some action on the first line, some other action on all lines except the first and the last, and a third action on the last line.
-35969510 0 Mongo query is slow using C# driver but fast using mongo shellI got very weird problem with MongoDB C# driver. I have a very simple query and I have a correct index for that query. When I run the query using MongoChef (and using the shell) I get the results in 22ms But when my app runs the same query it takes about 2.5mins to return answer (this is not due to network problems).
I have checked in db.currentOp() and I saw that the op is indeed taking about 2.5 mins to finish and the query is the same as the one I ran manually and the execution plan do use the index. Any idea? Thanks
P.S The problem is not with the size of the result set! I have tested with results set that have 0 results, 21 results and 600,000 results and in all of them the results was horrible! (above 2m for only 21 results which in the shell takes no time!)
{ "inprog": [ { "opid" : 53214, "active" : true, "secs_running" : 174, "microsecs_running" : 174085497, "op" : query, "ns" : db.collection, "query" : {{$query : {ParentId: 55, IsDeleted : false}}, {$orderby : {_id : -1}}}, "planSummary": IXSCAN {_id : 1}, "client" : ip:port, "desc" : conn121254, "threadId" : 0x1234567, "connectionId" : 1254651, "locks" : { "Global" : r, "MMAPV1Journal" : r, "Database" : r, "Collection" : R }, "waitingForLock" : false, "numYields" : 46963, "lockStats" : { "Global" : {acquireCount : { r : 93928}}, "MMAPV1Journal" : {acquireCount : { r : 46964} , acquireWaitCount : { r : 2 }, timeAcquiringMicros: { r : 2 } }, "Database" : {acquireCount : { r : 46964}}, "Collection" : {acquireCount : { r : 46964}} } } ] } And the query that is running great on the shell (22ms)
db.collection.find({ParentId : 55, IsDeleted : false}).sort({_id : 1}) C# code example :
MongoClient client = new MongoClient("mongodb://MongosServer01:27017,MongosServer02:27017,MongosServer03:27017,MongosServer04:27017"); var collection = client.GetServer().GetDatabase("db").GetCollection<BsonDocument>("collection"); var cursor = collection.Find(Query.And(Query.EQ("ParentId" , 55),Query.EQ("IsDeleted" , false))).SetSortOrder("_id").SetLimit(20);
-29376047 0 Spring Session does not currently support HttpSessionListener. See spring-session/gh-4
You can listen to SessionDestroyedEvent's
They differ from the HttpSessionDestroyedEvent in that Spring Security will fire the HttpSessionDestroyedEvent based on the HttpSessionEventPublisher (an implementation of HttpSessonListener). Thus HttpSessionDestroyedEvent will not get fired when using Spring Session since there is no support for HttpSessionListener.
-35967181 0 Equivalent to DirectInput for Windows Store Apps?I am building a game for Windows 10 that utilizes input to draw on the screen, but the fidelity is lacking. It is not accurate enough to draw a straight line if you draw fast. That's when I thought of DirectInput, which I've used in C++ games for Windows 7, but that API is not available for Store Apps... is there an equivalent, which will increase my accuracy for the drawing?
-37287933 0 How to bring in string from left of numbers in ExcelI'm trying to format a column based off of another (let's say column B2). The column contains a value like "ABC011" and I need to bring in just the letters "ABC".
For another column I also need to bring in just the numbers "011" but without the trailing zeroes (although I imagine that if I can get the solution for the first question I'll be able to figure out the second).
Thanks in advance.
EDIT: The length of the characters can change but the numbers are USUALLY 2 or more digits as well as the letters.
-28720601 0 Error in Integrated Weblogic 12C in SOA Suite - Derby server start and stop immediatelyI need help to solve this problem:
I've already installed Oracle SOA Suite 12c using the developer pack (from oracle official downloads). When I try to start integrated weblogic server (in Jdeveloper menu Run) it starts and shows listening on the port but immediately stops with following error:
Could: Not find or load main class Stopping Derby Server Derby Server Stopped My config:
I solved my issue by using DIFFBOT Article API and the link of API is https://www.diffbot.com.
-22237593 0Your database should have a method for updating the database
@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // do something to upgrade } But that isn't called by default, but when your app first tries to open the database. At that point, you should be to architect a dialog that instructs your user and either do the upgrade or not.
It's also possible to alter the user's database within that onUpgrade method. For example, a string like this:
private static final String ALTER_TABLE3 = "ALTER TABLE exercises ADD COLUMN exscore REAL DEFAULT 0.0"; could be used in onUpgrade like so:
if (oldVersion == 5) { db.execSQL(ALTER_TABLE3); // now copy all of the values from integer to real setUpMoveRoutine = true; } I did an upgrade from v4 to v5 that needed new elements within a table. And then called a method to move data as needed.
You should be able to manage just about any changes in your database
-39085751 0 Inserting a value into a sequential series and then continuing the seriesExample data series has the sequence seeded with 1 as the initial value, and a step of 1. There is a calculated value that needs to be inserted in the series, in this case it is 3.5
Desired output:
1 2 3 3.5 4 5 I am avoiding VBA, and I am avoiding sorts. I am trying to do this with an IF formula.
So far I have tried the following A2 copied down:
=IF(A1+1<3.5,A1+1,IF(A1<>3.5,3.5,A1+1)) Seed value may be any real number. Step value may be any real number.
-310246 0 Installer for .NET 2.0 application for Windows 98How can an automatic installer for .NET 2.0 application be created for Windows 98?
I mean for application and also for .NET 2.0 if missing.
I tried to do it by creating a setup project for Visual Studio 2008, but I didn't succeed. I installed IE6 SP1 manually, but Installer still crashed. Windows Installer 2.0 is installed. It's impossible to install Installer 3.0 there. I unchecked Installer at Setup Project prerequisites, but still it's not possible to install the application - the error message says that it requires a newer version of Windows.
How can this be resolved?
-14813778 0 MySQLSyntaxErrorException - Invalid Parameters in Prepared StatementI Have a code Like Below. I have Tried the Other Solutions in stack but nothing seems to be Working. The Java code which generates the Error is as Shown Below.
public Connection getConnection() { try { conn = DriverManager.getConnection(CONNSTR, USER, PASS); return conn; } catch (SQLException e) { e.printStackTrace(); return null; } } public boolean AuthenticateUser() { String UserName = "User"; String Password = "Password"; try { PreparedStatement pstmt = null; ResultSet rs = null; conn = getConnection(); String strSQL = "SELECT UserName " + " FROM Users " + " WHERE UserId = ? AND " + " Password = ?"; pstmt = (PreparedStatement) conn.prepareStatement(strSQL); pstmt.setString(1, UserName); pstmt.setString(2, Password); System.out.println(strSQL); rs = pstmt.executeQuery(strSQL); System.out.println(rs.getRow()); rs.last(); int TotalRows = rs.getRow(); System.out.println(TotalRows); if(TotalRows > 0) return true; else return false; } catch (SQLException e) { e.printStackTrace(); return false; } } The Table Structure of the Database is as Given Below
CREATE TABLE Users(Id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, UserName VARCHAR(255), UserId VARCHAR(255), Password VARCHAR(255)) The error is As given Below in Image 
The Exception are as Below
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? AND Password = ?' at line 1 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at com.mysql.jdbc.Util.handleNewInstance(Util.java:411) at com.mysql.jdbc.Util.getInstance(Util.java:386) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3609) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2002) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2163) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2618) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2568) at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1557) at com.apryll.db.util.dbUtil.AuthenticateUser(dbUtil.java:55) at com.apryll.db.Login.doPost(Login.java:42) at javax.servlet.http.HttpServlet.service(HttpServlet.java:641) at javax.servlet.http.HttpServlet.service(HttpServlet.java:722) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source)
-15331724 0 stream context for custom stream wrappers In the code snippet that follows this paragraph I'm creating a stream wrapper called test using the Test_Stream object. I'm trying to use stream context's with it and have a few questions. First here's the code:
<?php class Test_Stream { public $context; public function __construct() { print_r(stream_context_get_options($this->context)); exit; } } $context = array( 'test' => array('key' => 'value'), 'otherwrapper' => array('key' =>'value') ); $context = stream_context_create($context); stream_wrapper_register('test', 'Test_Stream'); $fp = fopen('test://www.domain.tld/whatever', 'r', false, $context); So right now, in that code snippet, Test_Stream is being registered to the 'test' stream wrapper but... what if I didn't know in advance what the wrapper name would be or what if I wanted to leave it up to the developer to decide. How would you know what the wrapper name was in the class? Seems like you'd have to know it in advance to get the appropriate context options (unless you just assume that the first context option array is the correct one) but what if you weren't going to know it in advance?
-30613065 0Looking at your code I think you want to show all marcas related to some articulo it via product.type. For this scenario I think you don't need to make any grouping, you can just find all the marcas you are interested in. Here is what i mean:
#in the view #add .distinct() if you get duplicates marcas = MarcasOpciones.object.filter(Productos_marca__tipo=articulo.Tipos) #in the template {% for sthelse in marcas %} <li><a href="#">{{ sthelse }}</a></li> {% endfor %} There is one possible drawback with this approach - we are not using the |slugify tag to create the match. A possible solution to this is to create slug fields for the both models.
However, if that approach doesn't suit you. I advice you to move all the matching logic in the view and again send only the needed marcas in the template.
#in the view from django.template.defaultfilters import slugify marcas = [] for sth in productos.all(): if slugify(articulo.Tipos) == slugify(sth.tipo): for sthelse in sth.marca.all(): if sthelse not in marcas: marcas.append(sthelse) #if you need the product that match that marca #you can add it here #sthelse.product = sth
-28480298 0 JavaScript Pure:
<script type="text/javascript"> document.getElementById("modal").click(); </script> JQuery:
<script type="text/javascript"> $(document).ready(function(){ $("#modal").trigger('click'); }); </script> or
<script type="text/javascript"> $(document).ready(function(){ $("#modal").click(); }); </script>
-39404570 0 Understanding lexical scoping of "use open ..." of Perl use open qw( :encoding(UTF-8) :std ); Above statement seems to be effective in its lexical scope only and should not affect outside of it's scope. But I have observed the following.
$ cat data € #1 $ perl -e ' open (my $fh, "<encoding(UTF-8)", "data"); print($_) while <$fh>;' Wide character in print at -e line 1, <$fh> line 1. € The Wide character ... warning is perfect here. But
$ perl my ($fh, $row); { use open qw( :encoding(UTF-8) :std ); open ($fh, "<", "data"); } $row = <$fh>; chomp($row); printf("%s (0x%X)", $row, ord($row)); € (0x20AC) Does not show the wide character warning!! Here is whats going on here imo
Now look at the following, a little variation
#3my ($fh, $row); { use open qw( :encoding(UTF-8) :std ); } open ($fh, "<", "data"); $row = <$fh>; chomp($row); printf("%s (0x%X)", $row, ord($row)); ⬠(0xE2) Now this time since the open statement is out of the lexical scope, the open opened the file in non utf-8 mode.
Does this mean use open qw( :encoding(UTF-8) :std ); statement changes the STDOUT globally but STDIN within lexical scope?
b & 1 tests if b is odd. If it is, result is set to tmp * power.
b >>= 1 divides b by 2. If the result is non-zero, tmp is set to power, and power is set to tmp * tmp.
Eventually, b is divided by 2 so much that it reaches zero, which ends the while loop.
The algorithm is a generalization of so-called "Russian Peasant multiplication" called "Exponentiation by squaring". The same basic process can be used for exponentiation instead of multiplication, by squaring the intermediate result (which we see in the second if test) rather than doubling.
Time complexity proportional to the highest set bit in b; if the highest set bit in b is bit K then the loop will iterate K times. That is, time complexity is proportional to the base 2 logarithm of b.
For a single-server LAMP site (which is usually under quite high load), what is best way to use memcache?
Does it make sense to run the memcache daemon on the same server as the application, or is that just going to take valuable memory away from MySQL, giving a net performance loss. Does it even make sense to use memcache in this scenario- or is the best solution to always have dedicated servers for memcache?
I appreciate that profiling the site before and after would be required to really answer this question, but I would rather not do that at this stage on the live site. Especially as someone out there certainly knows the answer off the top of their head.
-24032406 0Some like that:
(function ($) { "use strict"; $(document).ready(function () { if ($.fn.plot) { var dataPie = [{ label: "Samsung", data: <?php echo $data1 ?> }]; } }); });
-18251594 0 You need to add a column, e.g. "label" to the node import file, and give numbers according to how you want to "group the nodes into one color". And then you can select to color the nodes via your new column.
-11147440 0In the C++ code you are translating to C#, look for a macro definition or inline function definition for SIGN. The definition should spell out exactly how you should implement it in C#.
If I had to guess from the name, SIGN(x,y) returns true if x and y have the same sign, and false otherwise.
In a multiple thread situation, is it possible to get the call stack at the current moment inside some thread t1 from another thread t2 running outside of t1? If so, how?
I tried:
def a; b end def b; c end def c; d end def d; sleep(1) end t1 = Thread.new do 100.times{a} end p t1.backtrace but it always returns an empty array [].
Following suggestions by Stefan, the following parameters worked for my computer:
def a; b end def b; c end def c; d end def d; end t1 = Thread.new do 1000.times{a} end sleep(0.0001) p t1.backtrace It returns a random call stack with the top-most method varying around a to d.
Here's my error message when I do a DB rake:
Could not find gem 'sqlite3 (>= 0)' in any of the gem sources listed in your Gemfile.
I've tried Installing xCode 4.0.2
Commands:
sudo gem install sqlite3-ruby sudo gem update --system sudo gem update rails sudo gem update sqlite3-ruby Gem list produces:
abstract (1.0.0) actionmailer (3.0.8, 2.2.2) actionpack (3.0.8, 2.2.2) activemodel (3.0.8) activerecord (3.0.8, 2.2.2) activeresource (3.0.8, 2.2.2) activesupport (3.0.8, 3.0.6, 2.2.2) arel (2.0.10) builder (2.1.2) bundler (1.0.14) erubis (2.6.6) i18n (0.5.0) mail (2.2.19) mime-types (1.16) polyglot (0.3.1) rack (1.2.3) rack-mount (0.6.14) rack-test (0.5.7) rails (3.0.8, 2.2.2) railties (3.0.8) rake (0.9.2, 0.8.3) rubygems-update (1.8.5, 1.8.4, 1.3.1) thor (0.14.6) treetop (1.4.9) tzinfo (0.3.27) Any suggestions? I'm on Max OS X 10.6
-11371468 0 Bug using UISplitViewController in a UITabController in iPad interfaceI am a new IOS developer working on my first app. I'm quite a way in to it, and have managed to get pretty much everything working how I want, but I'm chasing an odd bug.
Here's the basic app design (yes, I understand it may not confirm to Apple UI guidelines) as best I can describe it:
It's a universal app written in the latest X Code fully using storyboarding. I have a working iPhone and iPad interface, but it's in the iPad interface where my issue exists. The root controller is a UITabView. On one of the tabs, I have a split view controller which implements the typical master detail pattern. In portrait mode, the master table is hidden and content renders. A navigation bar button brings forth the master table view. You select an item and the master table view vanishes and the right side updates the content via a segue. So far so good. You rotate the device, everything keeps working. The split view master table stays on the left, and the content renders on the right. This all works great even within the tab controller.
Here are the two use cases that demonstrate the bug not happening and happening, in that order
1- Bug does not happen a) Launch app in Portrait. b) Select Nav button to bring up master table c) Select item from table (item renders, master table vanishes) d) Rotate device to lanscape (master/detail rotates properly) e) Pick a different view from tab controller f) Pick original view containing split view g) Everything is great
2- Bug happens in this use case a) Launch app in Portrait b) Select Nav button to bring up master table c) Select item from table (item renders, master table vanishes) d) Pick a different view from the tab controller e) Rotate device to landscape whilst in the other tab view f) Pick original view with the split controller from the tab bar g) View comes back, detail is rendered, master/view is completely missing.
So, it seems to be that if the master/detail rendered in landscape before the other tab view was selected, everything is fine. But if the master/detail view doesn't render in landscape at least once before you pick another view in the tab, it doesn't work right.
In my viewWillAppear method for the master/table controller, I check self.masterPopoverController.isPopoverVisible and sure enough it returns false.
I'm wondering if this is a bug, or maybe one of the reasons Apple doesn't recommend putting a split view in another controller?
-14214077 0 c# LINQ DataTable substractioni have two DataTables which has different columns but one column is same.
i want to get new DataTable which contains row from dt1 which are not exist in dt2.
how can i do it using LINQ?
that's is my current code, but it work only for Datatables with same columns:
private void Delete_HPM_Deleted_Points(int YellowCard_Request_ID) { DataTable dt_hpm_points_DB = DataAccessLayer.Get_YellowCard_Request_HPM_Points(YellowCard_Request_ID); //dt_hpm_points_DB.Columns.Remove("HPM_Tool_ID"); //dt_hpm_points_DB.Columns.Remove("HPM_Point_Message"); //dt_hpm_points_DB.Columns.Remove("HPM_Point_isDisabled"); //dt_hpm_points_DB.Columns.Remove("HPM_Point_Comments"); DataTable dt_hpm_points_Local = UserSession.Get_User_YC_HPM_Added_Points_DATATABLE(); //dt_hpm_points_Local.Columns.Remove("HPM_Tool_ID"); //dt_hpm_points_Local.Columns.Remove("HPM_Point_Message"); //var rowsInFirstNotInSecond = dt_hpm_points_DB.Rows.Where(r1 => !dt_hpm_points_Local.Rows.Any(r2 => r1.ID == r2.ID)); DataTable dt_points_to_remove = dt_hpm_points_DB.AsEnumerable().Except(dt_hpm_points_Local.AsEnumerable(), DataRowComparer.Default).CopyToDataTable(); foreach (DataRow dr in dt_points_to_remove.Rows) { DataAccessLayer.Delete_YellowCard_Request_HPM_Point(YellowCard_Request_ID, dr["HPM_Point_ID"].ToString()); } }
-31135595 0 Adding Message.framework to your project and Get IMEI Number,
NetworkController *ntc = [NetworkController sharedInstance]; NSString *imeistring = [ntc IMEI]; Apple allow some of the details of device, Not give IMEI, serial Number. in UIDevice class provide details.
class UIDevice : NSObject { class func currentDevice() -> UIDevice var name: String { get } // e.g. "My iPhone" var model: String { get } // e.g. @"iPhone", @"iPod touch" var localizedModel: String { get } // localized version of model var systemName: String { get } // e.g. @"iOS" var systemVersion: String { get } // e.g. @"4.0" var orientation: UIDeviceOrientation { get } // return current device orientation. this will return UIDeviceOrientationUnknown unless device orientation notifications are being generated. @availability(iOS, introduced=6.0) var identifierForVendor: NSUUID! { get } // a UUID that may be used to uniquely identify the device, same across apps from a single vendor. var generatesDeviceOrientationNotifications: Bool { get } func beginGeneratingDeviceOrientationNotifications() // nestable func endGeneratingDeviceOrientationNotifications() @availability(iOS, introduced=3.0) var batteryMonitoringEnabled: Bool // default is NO @availability(iOS, introduced=3.0) var batteryState: UIDeviceBatteryState { get } // UIDeviceBatteryStateUnknown if monitoring disabled @availability(iOS, introduced=3.0) var batteryLevel: Float { get } // 0 .. 1.0. -1.0 if UIDeviceBatteryStateUnknown @availability(iOS, introduced=3.0) var proximityMonitoringEnabled: Bool // default is NO @availability(iOS, introduced=3.0) var proximityState: Bool { get } // always returns NO if no proximity detector @availability(iOS, introduced=4.0) var multitaskingSupported: Bool { get } @availability(iOS, introduced=3.2) var userInterfaceIdiom: UIUserInterfaceIdiom { get } @availability(iOS, introduced=4.2) func playInputClick() // Plays a click only if an enabling input view is on-screen and user has enabled input clicks. } example : [[UIDevice currentDevice] name];
Figured it out, think I have been multiplying by 1000 when I shouldn't have, the following works
var offset = (int)Math.Floor(buffer.WaveFormat.SampleRate * barDuration / 128) * 128 * bar;
-28640500 0 Problem solved.
It turned out that additional permission is needed for the report on the report server. After the DBA granted the account access to the report folder, the problem is solved.
-32247075 0You can use String.Replace Method:-
filename = filename.Replace(" ","").Replace("(","").Replace(")","").Replace(".",""); You can wrap this inside an extension method like this:-
public static class StringExtention { public static string RemoveUnwantedCharacters(this string s) { StringBuilder sb = new StringBuilder(s); sb.Replace("(", ""); sb.Replace(")", ""); sb.Replace(" ", ""); sb.Replace(".", ""); return sb.ToString(); } } You can use this as: filename = filename.RemoveUnwantedCharacters();
But, since there is a possiblity of whitespaces too and not just space, I guess Regex is the best answer here as answered by @JonSkeet :)
-16467473 0Yes, use the async library. It's awesome for doing this sort of thing.
If you need to do one map and then pass the results to the next function then you need to look at async.waterfall.
-35174852 0 How to get rows and count of rows simultaneouslyI have a stored procedure that returns rows and count simultaneously.
I tried following ADO.net code but I get IndexOutOfRange Exception on ItemCount(ItemCount contains count of rows)
public List<Product> GetProductDetails(Product p) { List<Product> products = new List<Product>(); using (SqlConnection con = new SqlConnection(_connectionString)) { SqlCommand cmd = new SqlCommand("[usp_Get_ServerPagedProducts]", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@rvcName", System.Data.SqlDbType.VarChar).Value = p.Name; cmd.Parameters.AddWithValue("@rvcCode", System.Data.SqlDbType.VarChar).Value = p.Code; cmd.Parameters.AddWithValue("@riProductTypeID", System.Data.SqlDbType.Int).Value = p.ProductTypeID; cmd.Parameters.AddWithValue("@ristartIndex", System.Data.SqlDbType.Int).Value = p.RowIndex; cmd.Parameters.AddWithValue("@rimaxRows", System.Data.SqlDbType.Int).Value = p.PageSize; con.Open(); using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { Product product = new Product(reader["Name"].ToString(), reader["Code"].ToString(), reader["Description"].ToString(), (DateTime)reader["DateCreated"], Convert.ToInt32(reader["ProductID"]), Convert.ToInt32(reader["ProductTypeID"]), reader["ProductTypeName"].ToString(), Convert.ToInt32(reader["ItemCount"])); products.Add(product); } } } return products; } The Stored Procedure:
SELECT ProductID, Name, [Description], Code, DateCreated, ProductTypeID, ProductTypeName FROM ( SELECT P.pkProductID AS ProductID, P.Name AS Name, P.[Description] AS [Description], P.Code AS Code, P.DateCreated AS DateCreated, P.fkProductTypeID AS ProductTypeID, PT.Name AS ProductTypeName, ROW_NUMBER() OVER (ORDER BY P.pkProductID) AS RowNumber FROM Product P INNER JOIN ProductType PT ON PT.pkProductTypeID = P.fkProductTypeID WHERE P.Name LIKE '%' + @rvcName + '%' AND P.Code LIKE '%' + @rvcCode + '%' AND (@riProductTypeID = 0 OR P.fkProductTypeID = @riProductTypeID) ) AS tblProduct WHERE RowNumber >= @ristartIndex AND RowNumber < (@ristartIndex + @rimaxRows) SELECT COUNT(*) AS ItemCount FROM ( SELECT P.pkProductID, P.Name, P.[Description], P.Code, P.DateCreated, P.fkProductTypeID AS 'ProductTypeID', PT.Name AS 'ProductTypeName', ROW_NUMBER() OVER (ORDER BY P.Name DESC) AS RowNumber FROM Product P INNER JOIN ProductType PT ON PT.pkProductTypeID = P.fkProductTypeID WHERE P.Name LIKE '%' + @rvcName + '%' AND P.Code LIKE '%' + @rvcCode + '%' AND (@riProductTypeID = 0 OR P.fkProductTypeID = @riProductTypeID) ) AS TotalCount Is it because its returning two tables? What's the solution?
-33004857 0Try this out, it seems to not complain about it, but don't have the full setup to test it out.
void ShowTableInDataGrid(System.Data.Entity.Core.Metadata.Edm.EntityType myEntityType) { var tableName = myEntityType.GetType(); var result = _context.Database. SqlQuery<myEntityType.GetType()> ("SELECT * FROM dbo." + tableName).ToList(); DataGridMain.ItemsSource = result; }
-26134796 1 Python will not understand List Sorry I have a very basic python question. In the following program I'm trying to duplicate a list and then sort it in ascending order. The code I've written is:
def lesser_than(thelist): duplicate = thelist[:] duplicate = duplicate.sort() return duplicate The error it gives me is that it cannot sort something of the type None. Does anyone know why this is happening?
-20961224 0Check out Open Graph- Twitter & Facebook both use this architecture to retrieve "stories" posted by users. It's a version of the semantic web idea. https://developers.facebook.com/docs/opengraph/ The days of SQL calls are over (thank god). FQL- the Facebook Query Language still works, but is largely being deprecated. It's not SQL but a version of a query language against the graph (was databases).
-29934384 0You have a spurious semicolon between the for loop and what you think is the body. Eliminate that and it should work as expected.
for(x = 0; x < 3 ; x++); { ^ | eliminate this What's happening now is that the for loop is looping three times and each time it is executing the empty statement formed by the semicolon. Then the block statement that you want executed three times is being executed once.
Array hydration is not the best way for achieve this kind of situations. The same scenario here:
Person - id_person - name - child //self refering Array hydration only select the first level. I resolving it taking one of these two options:
Use left join association
$query = $entityManager->createQueryBuilder() ->select('p1, p2, p3, p4, p5, p6') ->from('Entity\Person', 'p1') ->leftJoin('p1.child', 'p2') ->leftJoin('p2.child', 'p3') ->leftJoin('p3.child', 'p4') ->leftJoin('p4.child', 'p5') ->leftJoin('p5.child', 'p6') ->createQuery(); and then, use array hydration.
Create your own recursive function in order to add manually each element in an array.
this is my colletion:
{ "_id" : "Kan6btPXwNiF84j8e", "title" : "Chapter Title 1", "businessId" : "qmWJ3HtZrpka8dpbM", "createdBy" : "GfdPfoPTiSwLv8TBR", "sections" : [ { "id" : "T5KAfTcCb7pCudT3a", "type" : "TEXT", "data" : { "text" : "<h1>2</h1><h1>asd</h1>" }, "createdAt" : ISODate("2016-12-03T10:35:59.023Z"), "updatedAt" : ISODate("2016-12-03T10:35:59.023Z") } ], "createdAt" : ISODate("2016-12-02T12:15:16.577Z"), "updatedAt" : ISODate("2016-12-03T12:54:50.591Z") } this is the meteor method I am calling from client side
deleteSection: function (section_id, chapter_id) { chaptersCollection.update( {$and: [{_id: chapter_id}, {'sections.id': section_id}]}, {$pull: {'sections': {'id': section_id}}}, function (err, numAffected) { if (err) { console.log(err); return err; }else{ console.log(numAffected); } }); return 'Section Successfully Deleted'; } in callback function of meteor method, it returns 1 as affected rows. But on server document is not updating.
Any suggestion where am I wrong?
-13753208 0The answer to your question is that Objective-C does not have a direct equivalent of annotations as found in Java/C#, and though as some have suggested you might be able to engineer something along the same lines it probably is either far too much work or won't pass muster.
To address your particular need see this answer which shows how to construct an array which holds objects of only one type; enforcement is dynamic and not static as with parametric types/generics, but that is what you'd be getting with your annotation so it probably matches your particular need in this case. HTH.
-3837890 0Here's my go at it... basically an unrolled loop. The JIT would probably have recognized that a loop would have gone from 0 to 3 and unrolled it itself anyway, but who knows...
public static int max(int[] a) { int max = a[0] > a[1] ? a[0] : a[1]; max = a[2] > max ? a[2] : max; return a[3] > max ? a[3] : max; } Sum would obviously just be a[0] + a[1] + a[2] + a[3].
You could also try packing the four 0-255 values in an int, and do some bit-operations instead.
-22626811 0In the order by clause we can add two thing:
Column names
Select * from TTT order by age; Coulmn number to filter
Select * from TTT order by 2;//if age is the second column in the table or Select name,age from TTT order by 2; // this will order by age In the following case the inner query
SELECT AGE FROM TTT WHERE NAME='TANDEL' will return 5
and the parent query
SELECT * FROM TT ORDER BY 5
-1685199 0 What would be the best way to send NSData through PHP into MySQL? Ok I believe this must be a pretty common scenario. I need to send a NSData variable over a HTTP request through a PHP page which then subsequently stores it in MySQL. This will be retrieved later by some other HTTP call which then downloads it into a NSData again. What is the best way to do this?
Should I convert the NSData into some sort of string representation (base64 etc)? Should I store the data in MySQL as VARCHAR or Blob? The data length will not exceed the MySQL/HTTP limit.
-25766005 0} catch (InputMismatchException e) { correctInput = false; System.out.println("Please enter int value"); inputScanner.next(); } consume one token and continue
-13935454 1 split python string on multiple string delimiters efficientlySuppose I have a string such as "Let's split this string into many small ones" and I want to split it on this, into and ones
such that the output looks something like this:
["Let's split", "this string", "into many small", "ones"] What is the most efficient way to do it?
-3595562 0I just went through the process of installing and trying several carts for a project that I was working on. As Pierre says above, "There is no best shopping cart, however there is one best for your specific need" That is a very truthful statement.
My project was for an on line soap company that has 5 different categories with 5 or so variations each. Not a big store and not one that changes inventory often.
I tried the following carts: PrestaShop, Zen Cart, Magento, getshopped and phpurchase.
My findings were that for a small store, PrestaShop, Zen Cart and Magento are a bit overkill. For a small shop, getshopped and phpurchase are better fits.
Out of the 3 big shop solutions, I felt that Zen Cart is really hard to make look nice. It has a 90's vibe about the template that it comes with and takes a lot of work to get around that. Magento and PrestaShop were really cool. PrestaShop seems very UK specific. It did not take Authorize.net and I think that there may be a plugin that you can get. Magento seems like a great solution for a larger store and I liked the backend admin interface.
I purchased getshopped plugin and integrated it into my Wordpress site (I purchased the Authroize.net integration gold cart level) I had such trouble dealing with the multiple bugs that I found riddled through the code base. I looked at their forum and many people who had similar issues were not responded to. Alot of people were as frustrated as me. I tried customer support - no response. I asked for a refund, no response. Basically, Get Shopped was a complete waste of time and money.
I then found Phpurchase. The customer support person, Lee Blue was really nice - Lee answered my emails morning, noon and night. Lee is literally the nicest customer support person I've ever worked with! - so helpful. The code worked just as specced - no troubles and no complaints. I'm a very happy customer with phpurchase. If I need a small ecommerce site in the future, I will use that solution again, for sure.
Note, I'm not an affiliate of Phpurchase or have any type of financial gain by recommending them, I just had such a rough time with getShopped and such a wonderful experience with Phpurchase!
-16815615 0You can also write getters for your different formats:
public function getGeoAsString() { // Create the string from your DB value. For example: return implode(',', json_decode($this->geom)); } Then you can use the geoAsString like a regular (read-only) attribute. You can also add a setter method, if you want to make it writeable.
record.x_sum_stored_taxes_exclude_withholding =\ sum(line.amount for line in record.x_sum_stored_taxes_exclude_withholding) You should use `tax_line_ids ?
record.x_sum_stored_taxes_exclude_withholding =\ sum([line.amount for line in record.tax_line_ids]) And ofcourse you need only positive values:
record.x_sum_stored_taxes_exclude_withholding =\ sum([line.amount for line in record.tax_line_ids if line.amount >= 0.0])
-35324331 0 Okay, let's break it down. replace(/[\W_]/g, "") means replace every non-word character and underscore with an empty string. So in the string $1.00, it would come out as 100 ($ and . are non-word characters).
Then .replace(",","") removes commas.
And .replace(".","") removes periods.
Assume I have a point at the following location:
Latitude: 47°36′N Longitude: 122°19′W
Around the above point, I draw a 35Km radius. I have another point now or several and I want to see if they fall within the 35Km radius? How can I do this? Is it possible with Linq given the coordinates (lat, long) of both points?
-32742920 0 adding different data-id to PHP / HTML loopI have created a loop to call posts so I can display posts easily on my website, however... I'm using animate.css to add animations, and a problem I'm now facing is all of these elements have the same data-id so they scroll in at the same time...
I'm very new to PHP and so I don't know if there's a way that I can give each of the divs a different data-id so they scroll in one by one?
Here's my code thus far;
<div class="animatedParent animateOnce" data-appear-top-offset='-525' data-sequence='500' style="margin: 40px 0; text-align: center;"> <h2 class="animated bounceInUp" data-id='14' style="text-transform: uppercase;">Recent Events at Pontins!</h2> <div class="past-events"> <?php query_posts('cat=#&posts_per_page=4'); ?> <?php while (have_posts()) : the_post(); ?> <div class="one-fourth animated bounceInLeft" data-id='15'> <a href="<?php echo get_permalink(); ?>"> <?php the_post_thumbnail('large_wide'); ?> </a> <h4><a href="<?php echo get_permalink(); ?>"><?php the_title(); ?></a></h4> <?php the_excerpt(); ?> </div> <?php endwhile; ?> <?php wp_reset_query(); ?> </div> <div style="clear:both;"></div> </div> http://www.stuartgreen.me.uk/pontins-events/wp-content/themes/genesis-sample/js/css3-animations.js here's a link to the JS (I'm using 'Jack McCourt - Animate It')
-36617616 0Have you tried on your php file , that?:
header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: POST/GET'); header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept"); As i read your error message above ,the error seems to be on the response, so i show you a screenshot of my request to the server(from my live web-app where i use CORS on the php), you need these headers on the response ,please see my response from the server:
Hope helps, good luck.
-2843006 0You'll want to use the FlashWindowEx function. Basically, get a handle to the window, create a FLASHWINFO structure with the handle and how you want the window to flash (continuously, until it's opened, etc), and pass it into FlashWindowEx.
edit: Here's an example of how to do it in C#.
-32576015 0pv = function(fv, d, t) fv/(1+d)^t pv(1.05^2, 0.05, c(1, 2)) Here's an explanation. Basically, in R, algebraic functions are applied automatically over numeric data, such that looping is often unnecessary.
-32637640 0Your procedure takes two parameters. You are calling it without any parameters. Oracle thus looks for a procedure named spfirst that takes no parameters, finds no such procedure, and throws an error.
Something like
DECLARE l_location nilesh.location%type; l_salary nilesh.monthly_salary%type; BEGIN spfirst( l_location, l_salary ); END; should work. Of course, you'd generally want to do something with the variables that are returned. If you've enabled dbms_output, you could print them out
DECLARE l_location nilesh.location%type; l_salary nilesh.monthly_salary%type; BEGIN spfirst( l_location, l_salary ); dbms_output.put_line( 'Location = ' || l_location ); dbms_output.put_line( 'Salary = ' || l_salary ); END; Be aware that your procedure will throw an error unless the nilesh table has exactly one row. It seems likely that you either want the procedure to take an additional parameter that is the key to the table so that the select into always returns a single row or that you want a function that returns a sys_refcursor rather than a procedure that has multiple out parameters.
No - it's not a prerequisite, even if you have a client app that consumes them - but imho it's a good idea.
Microservices architecture is really nothing new as far as concept. Break up your monolithic app into many components that can iterate quickly at their own pace of development. Cloud native tooling and best practices have brought on this new notion of "microservices" with technology like containers and best practices like code as config.
For client consumption across a broad spectrum of client capabilities, microservices are more easily and practically managed with a gateway because the gateway is a piece of infrastructure that acts as a control point for QoS concerns such as security, throttling, caching, payload pagination, lightweight transformation, tracebacks through header injection, etc.
It's not necessary, but practically speaking if you have one already baked into your microservices development process as part of a cloud ready infrastructure - you address these things during development consideration and not in "big bang" fashion after the fact - a huge burden in the past for devop/ops folks to get their head around. It's such a burden, that that's why we've started our own solution that marries microservices development integration with management under ones cloud native platform and have a market for it
-16610374 0 Error in an example from book - "Unexpected token {"I was reading a book on JavaScript (recently started to learn). While running one of the examples from a book, I get an error. I'm using Chromium browser on Ubuntu, 14.0.835.202.
Since I'm a newbie, I can't understand why there is an error. Thanks in advance.
Function.prototype.method = function (name, fn) { this.prototype[name] = fn; return this; }; var Person { this.name = name; this.age = age; }; Person. method ("getName", function { // error here - "Uncaught SyntaxError: Unexpected token {" return this.name; }). method ("getAge", function { return this.age; }); var alice = new Person ("Alice", 93); var bill = new Person ("Bill", 30); Person. method ("getGreeting", function { return "Hi" + this.getName() + "!"; }); alert (alice.getGreeting()); EDIT:
The solution gave me another question that I wanted to ask. For object declaration:
var Object = function (...) // line 1 { // code here }; if the number of variables is so big that I don't want to list them in line 1, what can I do?
-33931108 0You have a number of issues you need to overcome...
The first could be done in a number of ways, assuming we can change the data. You could make the first token meaningful (human, pet); you could use JSON or XML instead. But lets assume for the moment, you can't change the format.
The key difference between the two types of data is the number of tokens they contain, 7 for people, 5 for pets.
while (input.hasNext()) { String text = input.nextLine(); String[] parts = text.split(","); if (parts.length == 7) { // Parse owner } else if (parts.length == 5) { // Parse pet } // else invalid data For the second problem you could use arrays, but you would need to know in advance the number of elements you will need, the number of people and for each person, the number of pets
Oddly enough, I just noticed that the last element is an int and seems to represent the number of pets!!
Morely,Robert,123 Anywhere Street,15396,4,234.56,2 ------------^ But that doesn't help us for the owners.
For the owners, you could use a List of some kind and when ever you create a new Human, you would simply add them to the List, for example...
List<Human> humans = new ArrayList<>(25); //... if (parts.length == 7) { // Parse the properties human = new Human(...); humans.add(human); } else if (parts.length == 5) { Thirdly, for the pets, each Pet should associated directly with the owner, for example:
Human human = null; while (input.hasNext()) { String text = input.nextLine(); String[] parts = text.split(","); if (parts.length == 7) { //... } else if (parts.length == 5) { if (human != null) { // Parse pet properties Pet pet = new Pet(name, type, age, date1, date2); human.add(pet); } else { throw new NullPointerException("Found pet without human"); } } Okay, so all this does, is each time we create a Human, we keep a reference to the "current" or "last" owner created. For each "pet" line we parse, we add it to the owner.
Now, the Human class could use either a array or List to manage the pets, either will work, as we know the expected number of pets. You would then provide getters in the Human class to get a reference to the pets.
Because out-of-context code can be hard to read, this is an example of what you might be able to do...
Scanner input = new Scanner(new File("data.txt")); List<Human> humans = new ArrayList<>(25); Human human = null; while (input.hasNext()) { String text = input.nextLine(); String[] parts = text.split(","); if (parts.length == 7) { String firstName = parts[0]; String lastName = parts[1]; String address = parts[2]; int cid = Integer.parseInt(parts[3]); int vists = Integer.parseInt(parts[4]); double balance = Double.parseDouble(parts[5]); int other = Integer.parseInt(parts[6]); human = new Human(firstName, lastName, address, cid, vists, balance, other); humans.add(human); } else if (parts.length == 5) { if (human != null) { String name = parts[0]; String type = parts[1]; int age = Integer.parseInt(parts[2]); String date1 = parts[3]; String date2 = parts[4]; Pet pet = new Pet(name, type, age, date1, date2); human.add(pet); } else { throw new NullPointerException("Found pet without human"); } } }
-29047126 0 The callback in findOne happens in the future, it is async. You must render inside said callback for the data to exist.
User.findOne({'username' : following_user }, function(err,user) { following_users_details.push({ username: user.username, profilepic : user.photo, userbio : user.bio }); res.render('users/userAccount',{user:req.user, following_users_details:following_users_details }); }); }
-17329320 0 <header> is also good for the page header or for a <section>'s header not just for articles. You can use both your examples without a problem. I recommend you use <header> for easier readability.
try to re-size function all the script also put in to the
$(window).resize(function(){
}) it's call on
-40435037 0Replace that line with this and it would definitely work.
'com.android.support:design:25.0.0'
-13010430 0 The textarea should already be hidden since it will only be used as a fallback. The editor itself is contained in an iframe with class wysihtml5-sandbox. So this should toggle the editor
$(".wysihtml5-sandbox").hide()
-26759750 0 Your update is a separate statement from the select. If you want to do this in an update, try:
WITH CTE AS ( SELECT rownum = ROW_NUMBER() OVER (ORDER BY p.BusinessEntityID), p.FirstName FROM Person.Person p ) UPDATE p SET FirstName = prev.FirstName FROM CTE p JOIN CTE prev ON prev.rownum = CTE.rownum - 1 WHERE CTE.FirstName IS NULL; The left join isn't important here, because you are only changing rows where FirstName IS NULL. The left join would set the NULL value to itself.
Well, the fibonacci series grows (approximately) exponentially with a ratio of 1.618 (the golden ratio).
If you take the log base 1.618 of Integer.MAX_VALUE it will therefore tell you approximately how many iterations you can go before overflowing....
Alternatively, you can determine empirically when it overflows just by doing the calculations....
-37746464 0_load_frames is a member function of the struct DataSet.
I would presume that given the leading underscore it is a private method.
struct DataSet { private: //function declaration std::vector<Frame> _load_frames(const std::string& basepath); }; I would recommend reading a book or taking some classes on c++ as this is a fairly fundamental concept.
http://www.tutorialspoint.com/cplusplus/cpp_class_member_functions.htm https://www.amazon.co.uk/Jumping-into-C-Alex-Allain-ebook/dp/B00F9311YC https://www.amazon.co.uk/C-Programming-Language-Bjarne-Stroustrup-ebook/dp/B00DUW4BMS
-38386746 0 C# - ComboBox control of ASP.NET AJAX control is not editable in ChromeWe dynamically create a web page with an editable dropdown list. But it can't be edited in Chrome, it did work in IE. Following are the dynamically creating code and result on page.
AjaxControlToolkit.ComboBox comboBox = GetComboBox(i); sControlID = comboBox.ID; comboBox.TabIndex = (short)(i + 100); if (ca.List != null) { string[] sList = ca.List; Array.Sort(sList); for (int j = 0; j < sList.Length; j++) comboBox.Items.Add(sList[j]); } ListItem li = comboBox.Items.FindByText(sVal); if (li != null) li.Selected = true; else { li = new ListItem(sVal); comboBox.Items.Add(li); li.Selected = true; } tc.Controls.Add(comboBox); } I found following snippet at the bottom oft the page within script tag,
Sys.Application.add_init(function() { $create(Sys.Extended.UI.ComboBox, {"autoCompleteMode":3,"autoPostBack":true,"buttonControl":$get("comboBox2_comboBox2_Button"),"comboTableControl":$get("comboBox2_comboBox2_Table"),"dropDownStyle":1,"hiddenFieldControl":$get("comboBox2_comboBox2_HiddenField"),"optionListControl":$get("comboBox2_comboBox2_OptionList"),"selectedIndex":4,"textBoxControl":$get("comboBox2_comboBox2_TextBox")}, null, null, $get("comboBox2")); }); As you can see, the textBoxControl in the snippet is the text filed for this editable dropdown list. If I remove it("textBoxControl":$get("comboBox2_comboBox2_TextBox")) from the snippet, it can be edited but the button behind is not working, it means the dropdown list doesn't work.
Any ideas what's going on here? Thanks in advance.
UPDATE:
I figured that it's the Ajax Control Toolkit, I think that the snippet I posted is the key for this issue. When the page loads, it changes and overrides the original element. I checked the document about this control and found that the dropDownStyle is for controlling the permission to allow user to edit or not. But as the document says, there are three values which are 'DropDownList', 'DropDown' and 'Simple'. But it didn't work when I changed this value.
-24295090 1 Python RQ: pattern for callbackI have now a big number of documents to process and am using Python RQ to parallelize the task.
I would like a pipeline of work to be done as different operations is performed on each document. For example: A -> B -> C means pass the document to function A, after A is done, proceed to B and last C.
However, Python RQ does not seem to support the pipeline stuff very nicely.
Here is a simple but somewhat dirty of doing this. In one word, each function along the pipeline call its next function in a nesting way.
For example, for a pipeline A->B->C.
At the top level, some code is written like this:
q.enqueue(A, the_doc)
where q is the Queue instance and in function A there are code like:
q.enqueue(B, the_doc)
And in B, there are something like this:
q.enqueue(C, the_doc)
Is there any other way more elegant than this? For example some code in ONE function:
q.enqueue(A, the_doc) q.enqueue(B, the_doc, after = A) q.enqueue(C, the_doc, after= B)
depends_on parameter is the closest one to my requirement, however, running something like:
A_job = q.enqueue(A, the_doc) q.enqueue(B, depends_on=A_job )
won't work. As q.enqueue(B, depends_on=A_job ) is executed immediately after A_job = q.enqueue(A, the_doc) is executed. By the time B is enqueued, the result from A might not be ready as it takes time to process.
PS:
If Python RQ is not really good at this, what else tool in Python can I use to achieve the same purpose:
You're missing the block for while. – Ashwin Mukhija Dec 30 '13 at 19:45
that fixed it.
-1029609 0 A WPF App fails when coming out of hibernate modeI have a WPF application that fails to come out of the timed sleep, followed by hibernate. The render thread seems to be failing during initialization. I tried removing hardware acceleration to check that it's not graphics card related, but that did not help.
Here is an exception along with the stacktrace:
ERROR An unspecified error occurred on the render thread. Stack trace: at System.Windows.Media.MediaContext.NotifyPartitionIsZombie(Int32 failureCode) at System.Windows.Media.MediaContext.NotifyChannelMessage() at System.Windows.Interop.HwndTarget.HandleMessage(Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Interop.HwndSource.HwndTargetFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter) at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg) at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg) at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame) at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame) at System.Windows.Threading.Dispatcher.Run() at System.Windows.Application.RunDispatcher(Object ignore) at System.Windows.Application.RunInternal(Window window) at System.Windows.Application.Run(Window window) at System.Windows.Application.Run()
I googled around, and people suggest that it might have something to do with AllowsTransparency property being set to true; however, i did not see this issue when running a simple test app.
Any ideas about the exception and possible causes/solutions are highly appreciated.
-22249363 0Append this in your code. this might help.
$("object param[name=flashvars]").attr("value", $("object").attr("data"));
-39445025 0 SonarQube Plugin for Jenkins does not find SonarQube Scanner executable I am trying to run the SonarQube Scanner within Jenkins as a post-build step. However, I keep getting the error message below:
------------------------------------------------------------------------ SONAR ANALYSIS FAILED ------------------------------------------------------------------------ FATAL: SonarQube Scanner executable was not found for SonarQube Build step 'Execute SonarQube Scanner' marked build as failure From similar questions on stackoverflow I read that one should choose "Install automatically" for the SonarQube Scanner, which I have done.
My configurations is as follows:
There's a few bits here and there that are a little more advanced than you need to delve into right now but the most of it is basic HTML.
You can change the templates but unfortunately the post ID has to stay ..it's built in.
You can find more info here; http://webapps.stackexchange.com/questions/28049/changing-messy-tumblr-url
Good luck with the template.
-9904728 0 Backbone: special encoding during saveNote: I know this is wrong, but this is a technical requirement by the server team.
I have a User object that extends Backbone.Model. It receives it's data using normal, mostly good, JSON from the server.
HOWEVER there is a requirement when saving THE SAME INFORMATION to encode emails with url encoding.
When receiving the data it is possible to pre-process it with the Backbone.Model.parse method, is there an equivalent way to pre-process the data before sending it? (without overriding the sync method)
-17338065 0 Android BitmapFactory.decodeFile skia errorI'm designing an activity that shows some images. The code below gets image files and places them into the screen.
for(int i=0;i<photoPaths.size();i++){ BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 4; //Bitmap bm= BitmapFactory.decodeFile(new File(photoPaths.get(i)).getAbsolutePath()); Bitmap bm= BitmapFactory.decodeFile(new File(photoPaths.get(i)).getAbsolutePath()); int imageH=bm.getHeight(); int imageW=bm.getWidth(); ImageView image=new ImageView(this); image.setImageBitmap(bm); int padding=10; image.setPadding(0, padding, padding, 0); } The code is running well while placing 5 photos. After them when 6th is placing code fails.
Here is the LogCat messages:
06-27 11:13:13.202: D/skia(17373): --- decoder->decode returned false 06-27 11:13:13.202: D/AndroidRuntime(17373): Shutting down VM 06-27 11:13:13.202: W/dalvikvm(17373): threadid=1: thread exiting with uncaught exception (group=0x4142c2a0) 06-27 11:13:13.202: E/AndroidRuntime(17373): FATAL EXCEPTION: main 06-27 11:13:13.202: E/AndroidRuntime(17373): java.lang.OutOfMemoryError 06-27 11:13:13.202: E/AndroidRuntime(17373): at android.graphics.BitmapFactory.nativeDecodeStream(Native Method) 06-27 11:13:13.202: E/AndroidRuntime(17373): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:652) 06-27 11:13:13.202: E/AndroidRuntime(17373): at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:391) 06-27 11:13:13.202: E/AndroidRuntime(17373): at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:451) 06-27 11:13:13.202: E/AndroidRuntime(17373): at com.artechin.mbtkatalog.PhotoGallery.onCreate(PhotoGallery.java:94) 06-27 11:13:13.202: E/AndroidRuntime(17373): at android.app.Activity.performCreate(Activity.java:5188) 06-27 11:13:13.202: E/AndroidRuntime(17373): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094) 06-27 11:13:13.202: E/AndroidRuntime(17373): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074) 06-27 11:13:13.202: E/AndroidRuntime(17373): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135) 06-27 11:13:13.202: E/AndroidRuntime(17373): at android.app.ActivityThread.access$700(ActivityThread.java:140) 06-27 11:13:13.202: E/AndroidRuntime(17373): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237) 06-27 11:13:13.202: E/AndroidRuntime(17373): at android.os.Handler.dispatchMessage(Handler.java:99) 06-27 11:13:13.202: E/AndroidRuntime(17373): at android.os.Looper.loop(Looper.java:137) 06-27 11:13:13.202: E/AndroidRuntime(17373): at android.app.ActivityThread.main(ActivityThread.java:4921) 06-27 11:13:13.202: E/AndroidRuntime(17373): at java.lang.reflect.Method.invokeNative(Native Method) 06-27 11:13:13.202: E/AndroidRuntime(17373): at java.lang.reflect.Method.invoke(Method.java:511) 06-27 11:13:13.202: E/AndroidRuntime(17373): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038) 06-27 11:13:13.202: E/AndroidRuntime(17373): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805) 06-27 11:13:13.202: E/AndroidRuntime(17373): at dalvik.system.NativeStart.main(Native Method) How can I solve the problem?
-9994343 0 Javascript call a c function at the server sideIs there a way i can call c functions from JavaScript at server side . and if possible back from c to javascript.
-12706480 0With the extern clause you are telling the compiler to resolve that symbol when it links. After linking, in the binary file there will be just one symbol with the name ptr_to_var. You, of course, must assure that it gets initialised somewhere. In the code you pasted, we cannot know whether it's been initialised or not. Though it seems you didn't.
By the way, try to make an nm to the libraries. You will see the symbols that you specified as extern as undefined (capital u), except in that library or object file where is it indeed defined (i.e., declared without the extern clause).
I started out with Qiulang answer, but it didn't work for me. What worked for me is to call the setAssetsFilter 3 times in a row with all filter combinations, before starting the enumeration.
[group setAssetsFilter:[ALAssetsFilter allPhotos]]; [group setAssetsFilter:[ALAssetsFilter allVideos]]; [group setAssetsFilter:[ALAssetsFilter allAssets]];
-16404142 0 If your level class has non primitive members they should also implement serializable.
-33055575 0 Java: Call a main method from a main method in another classI have a set of Java files in the same package, each having main methods. I now want the main methods of each of the classes to be invoked from another class step by step. One such class file is Splitter.java. Here is its code.
public static void main(String[] args) throws IOException { InputStream modelIn = new FileInputStream("C:\\Program Files\\Java\\jre7\\bin\\en-sent.bin"); FileInputStream fin = new FileInputStream("C:\\Users\\dell\\Desktop\\input.txt"); DataInputStream in = new DataInputStream(fin); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine = br.readLine(); System.out.println(strLine); try { SentenceModel model = new SentenceModel(modelIn); SentenceDetectorME sentenceDetector = new SentenceDetectorME(model); String sentences[] = sentenceDetector.sentDetect(strLine); System.out.println(sentences.length); for (int i = 0; i < sentences.length; i++) { System.out.println(sentences[i]); } } catch (IOException e) { e.printStackTrace(); } finally { if (modelIn != null) { try { modelIn.close(); } catch (IOException e) { } } fin.close(); } } I now want this to be invoked in AllMethods.java inside a main method. So how can I do this? There are several other class files having main methods with IOException which have to be invoked in AllMethods.java file.
Update -
I have main methods having IOException as well as main methods not having IOEXception that has to be invoked in AllMethods.java.
Overview:
Our application extends a UIApplication and has a SMS Listener class that is registered on boot. When a message is received that fits our criteria we process the message and then we want to save it to a local SQLite database as well as upload it to a Web Server. It is important that this happens as soon as possible after the SMS is received, even if the UI Application is not open at that stage.
Problem:
When the SMSListener Instance is running in the background, with no UIApplication instance active, and wants to access the SQLite database or tries to create a HTTP Connection a “No Application Instance” exception is thrown.
Desired outcome:
We want to process, save and upload all the messages from the SMSListener background thread even if the UIApplication is not active. Currently the SMSListener background thread would store the messages in the RuntimeStore; when the UI Application is started it reads the messages from the RuntimeStore and saves it to the database. This is not an optimal solution though, because the synchronisation with the Web Server would also then only happen when the UI Application is next opened. It is important that it rather syncs when the message is received.
Application Pseudo Code:
Main Class, checks for startup and creates a SMSListener instance or gets the instance from the RuntimeStore.
public class OurAppUi extends UiApplication { public static void main(String[] args) { if (args != null && args.length > 0 && args[0].endsWith("gui")) { // Create a new instance of the application and make the currently // running thread the application's event dispatch thread. OurAppUi theApp = new OurAppUi(); theApp.enterEventDispatcher(); } else { // Entered through the alternate application entry point SmsListener.waitForSingleton(); } } } The SMSListener Class listens for any incoming messages, makes use of the RuntimeStore Singleton Model. This is working as expected.
public class SmsListener implements javax.wireless.messaging.MessageListener { public static SmsListener waitForSingleton() { //Ensure this is a singleton instance. //Open RuntimeStore and obtain the reference of BackgroundListener RuntimeStore store = RuntimeStore.getRuntimeStore(); Object obj = store.get(ID_BACKGROUND_LISTENER); //If obj is null, there is no current reference to BackgroundListener //Start a new instance of BackgroundLIstener if one is not running if(obj == null) { store.put(ID_BACKGROUND_LISTENER, new SmsListener()); return (SmsListener)store.get(ID_BACKGROUND_LISTENER); } else { return(SmsListener)obj; } } public void notifyIncomingMessage(MessageConnection conn) { new Thread() { MessageConnection connection; Thread set (MessageConnection con) { this.connection = con; return (this); } public void run() { try { Message m = connection.receive(); String msg = null; if (m instanceof TextMessage) { TextMessage tm = (TextMessage)m; msg = tm.getPayloadText(); } // Process the SMS SMSObject sms = processSMS(msg); // Save to DataBase { Exception is Thrown Here } SQLManager.getInstance().save(sms); // Upload to Web Server { Exception is Thrown Here } WebServer.upload(sms); } catch(Exception error) { } } }.set(conn).start(); } } When the SmsListener Instance wants to access the SQLite database or tries to create a HTTP Connection a “No Application Instance” exception is thrown.
public final class SQLManager { private SQLManager() { try { db = OpenOrCreateDatabase(); } catch (MalformedURIException e) { Debug.log(TAG, "Get connection: URI: " + e.getMessage()); } catch (ControlledAccessException e) { Debug.log(TAG, "Get connection: Controlled Access: " + e.getMessage()); } catch (DatabasePathException e) { Debug.log(TAG, "Get connection: Database Path: " + e.getMessage()); } catch (DatabaseIOException e) { Debug.log(TAG, "Get connection: Database IO: " + e.getMessage()); } catch (Exception e) { Debug.log(TAG, e); } } public static synchronized SQLManager getInstance() { if (instance == null) { instance = new SQLManager(); } return instance; } } We’ve tried store the SQLite instances in the RuntimeStore, using the same Singleton Model as the SMSListener but received errors when the UI Application tried to access the stored DB Instance.
-7865583 0 Core Location and Core Motion device headingI've noticed one problem with Coree Motion. When I'm using the
[_mMotionManager startDeviceMotionUpdatesUsingReferenceFrame: CMAttitudeReferenceFrameXTrueNorthZVertical toQueue: [[[NSOperationQueue alloc] init] autorelease] withHandler: ^(CMDeviceMotion* motion, NSError* error) { //my code here }]; to get device motion it gives me wrong device heading. I mean if I start processing motion updates holding device towards the north the heading is OK. But if I start not towards the north the bias is very big.
Is there any way to get correct values of heading?
-27145931 0Just use pixelOffset property:
var infoWindow = new google.maps.InfoWindow({pixelOffset:new google.maps.Size(0, -100)});
-11123221 0 Apache CXF via TLS Update on 06/21/2012 A little update. Today I finally caught the exception which is preventing me from connecting to the server. Here is what I get after calling getInputStream():
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target ===========================================================
Original message:
I'm trying to make my client (the client is not written entirely by me) work with a published web service over TLS (the client works over http). I'm new to this area I've never worked with web services closely before. I've checked with soapUI that the web service is correctly published and accessible. The address is https://:9080/SOAOICCT/services/SessionService?wsdl. I can send a request and receive a reply. But my client throws a lot of exceptions. Here are the most important:
javax.xml.ws.WebServiceException: org.apache.cxf.service.factory.ServiceConstructionException: Failed to create service. at <My class.my method>(SessionServiceDAO.java:548) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) ...... Caused by: javax.xml.ws.WebServiceException: org.apache.cxf.service.factory.ServiceConstructionException: Failed to create service. at org.apache.cxf.jaxws.ServiceImpl.<init>(ServiceImpl.java:150) at org.apache.cxf.jaxws.spi.ProviderImpl.createServiceDelegate(ProviderImpl.java:65) at javax.xml.ws.Service.<init>(Service.java:56) ......... Caused by: javax.wsdl.WSDLException: WSDLException: faultCode=PARSER_ERROR: java.lang.IllegalArgumentException: InputSource must have a ByteStream or CharacterStream at org.apache.cxf.wsdl11.WSDLManagerImpl.loadDefinition(WSDLManagerImpl.java:226) at org.apache.cxf.wsdl11.WSDLManagerImpl.getDefinition(WSDLManagerImpl.java:179) at org.apache.cxf.wsdl11.WSDLServiceFactory.<init>(WSDLServiceFactory.java:91) ... 70 more Caused by: java.lang.IllegalArgumentException: InputSource must have a ByteStream or CharacterStream at org.apache.cxf.staxutils.StaxUtils.createXMLStreamReader(StaxUtils.java:983) at org.apache.cxf.wsdl11.WSDLManagerImpl.loadDefinition(WSDLManagerImpl.java:217) ... 72 more I've tracked this issue to the method java.net.HttpURLConnection.getResponseCode(). Here it is:
public int getResponseCode() throws IOException { /* * We're got the response code already */ if (responseCode != -1) { return responseCode; } /* * Ensure that we have connected to the server. Record * exception as we need to re-throw it if there isn't * a status line. */ Exception exc = null; try { getInputStream(); } catch (Exception e) { exc = e; } I get an exception at getInputStream() and never actually connect to the server. This exception is later swallowed in org.apache.cxf.transport.TransportURIResolver.resolve(String, String) here
} catch (Exception e) { //ignore } The issue seems to be something very simple like authentication or a parameter. Are there any obvious reasons why I cannot connect to the web service? I'm a newbie I can make even a very simple mistake.
Here is my http:conduit:
<http:conduit name="*.http-conduit"> <http:tlsClientParameters secureSocketProtocol="TLS"> <sec:trustManagers> <sec:keyStore type="JKS" password="123123" file="config.soa.client/trustedCA.keystore"/> </sec:trustManagers> <sec:cipherSuitesFilter> <sec:include>SSL_RSA_WITH_RC4_128_MD5</sec:include> <sec:include>SSL_RSA_WITH_RC4 _128_SHA</sec:include> <sec:include>SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA</sec:include> <sec:include>.*_EXPORT_.*</sec:include> <sec:include>.*_EXPORT1024_.*</sec:include> <sec:include>.*_WITH_DES_.*</sec:include> <sec:include>.*_WITH_NULL_.*</sec:include> <sec:exclude>.*_DH_anon_.*</sec:exclude> </sec:cipherSuitesFilter> </http:tlsClientParameters> </http:conduit> A little update. Today I finally caught the exception which is preventing me from connecting to the server. Here is what I get after calling getInputStream():
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
-9263742 0 Perhaps:
select a.name, a.uniqueCustID, a.info1, b.info2, c.info3 from table1 a left outer join table1 b on b.pk = a.pk and b.info1 is not null left outer join table1 c on c.pk = a.pk and c.info2 is not null The left outer joins are needed because you don't know in advance if a user will have 1, 2 or 3 records with data. This way, if there is no data, a null will be inserted in the corresponding field.
-24301363 0In fact, there are two commands to use :
hdfs namenodehdfs datanodeI'm trying to execute a LFTP command using the system() PHP method in a IIS 7.0 site.
$command = 'cmd /c lftp -c "open -u name,password -p 22 sftp://server.mylife.com ; cd test/portal/template ; put /cygdrive/c/inetpub/uploads/cata/exports/tpl_1421946484/cata.csv;"'; system($command); I put it in a PHP file. If if run it directly by the command line php sendFile.php it works fine. But if I access this same php file throught a IIS 7.0 website, I got nothing and no error.
I can't understand where it comes from...!
Any help ?
-19228104 0It seems that it´s a documented service now: https://developer.here.com/rest-apis/documentation/enterprise-map-tile
-31791365 0 Cocoapod 0.38.0 and AFNetworking 2.5 AF_APP_EXTENSIONS compilation errorMy project has 9 targets :
- Prod - Prod_app_extension_1 - Prod_app_extension_2 - Beta - Beta_app_extension_1 - Beta_app_extension_2 - Dev - Dev_app_extension_2 - Dev_app_extension_2 I'm using 0.38.2 cocoapod version and 2.5.4 AFNetworking.
I'm trying to use AFNetworking with cocoapod but I get the AF_APP_EXTENSIONS error while compiling. After searching for the solution on the web, I understand the problem and found that defining the 'preprocessor macros' AF_APP_EXTENSIONS can fix the problem.
But here is the struggle : By default, AF_APP_EXTENSIONS is correctly added into my 6 app_extensions. In the other hand, when I navigate through my Pods target, each Pods are separated :
- NSDate+TimeAgo - AFNetworking - iRate - AppUtils - Prod - Prod_app_extension_1 - Prod_app_extension_2 - Beta - Beta_app_extension_1 - Beta_app_extension_2 - Dev - Dev_app_extension_2 - Dev_app_extension_2 In another project I made, all pods are generated this way :
- Prod - Pods-Prod-NSDate+TimeAgo - Pods-Prod-AFNetworking - Pods-Prod-iRate - Pods-Prod-AppUtils - Prod_app_extension_1 - Pods-Prod_app_extension_1-NSDate+TimeAgo - Pods-Prod_app_extension_1-AFNetworking - Pods-Prod_app_extension_1-iRate - Prod_app_extension_2 - Pods-Prod_app_extension_2-NSDate+TimeAgo - Pods-Prod_app_extension_2-AFNetworking - Pods-Prod_app_extension_2-iRate - Beta - Pods-Beta-NSDate+TimeAgo - Pods-Beta-AFNetworking - Pods-Beta-iRate - Pods-Beta-AppUtils - Beta_app_extension_1 - Pods-Beta_app_extension_1-NSDate+TimeAgo - Pods-Beta_app_extension_1-AFNetworking - Pods-Beta_app_extension_1-iRate - Beta_app_extension_2 - Pods-Beta_app_extension_2-NSDate+TimeAgo - Pods-Beta_app_extension_2-AFNetworking - Pods-Beta_app_extension_2-iRate - Dev - Pods-Dev-NSDate+TimeAgo - Pods-Dev-AFNetworking - Pods-Dev-iRate - Pods-Dev-AppUtils - Dev_app_extension_1 - Pods-Dev_app_extension_1-NSDate+TimeAgo - Pods-Dev_app_extension_1-AFNetworking - Pods-Dev_app_extension_1-iRate - Dev_app_extension_2 - Pods-Dev_app_extension_2-NSDate+TimeAgo - Pods-Dev_app_extension_2-AFNetworking - Pods-Dev_app_extension_2-iRate I think this is why my 'preprocessor macros' AF_APP_EXTENSIONS isn't define into the 'AFNetworking' Pods target.
Here is my Podfile :
platform :ios, '7.0' xcodeproj 'myProj.xcodeproj' def generic_pods pod 'NSDate+TimeAgo' pod 'AFNetworking', '~> 2.0' end def app_pods pod 'iRate' pod 'AppUtils', end target "Prod" do generic_pods app_pods end target "Prod_app_extension_1" do generic_pods end target "Prod_app_extension_2" do generic_pods end target "Beta" do generic_pods app_pods end target "Beta_app_extension_1" do generic_pods end target "Beta_app_extension_2" do generic_pods end target "Dev" do generic_pods app_pods end target "Dev_app_extension_1" do generic_pods end target "Dev_app_extension_2" do generic_pods end I don't know what the problem is, and it's driving me crazy.
-31157713 0 how to create row in angular js?I am trying to make a row which is displayed in image .Actually my circle is not on right side and my “P” is not getting background color.Here is my code http://plnkr.co/edit/qIz2rFgW8n3J92evCRTd?p=preview
can we give row height in percentage ? actually I need my row should look like as shown in image

How would I, for instance, find the forward-most corner of the cube given its Forward, Right, and Up vectors (as well as its coordinates, obviously) assuming that the colored axis is the 'real' axis.
The best I could come up with is:
x=cube.x+pointToFind.x*(forward.x+right.x+up.x) y=cube.y+pointToFind.y*(forward.y+right.y+up.y) z=cube.z+pointToFind.z*(forward.z+right.z+up.z) This worked sometimes, but failed when one of the coordinates for the point was 0 for obvious reasons.
In short, I don't know what do to, or really how to accurately describe what I'm trying to do... This is less of a programming questions and more of a general math question.
-39919539 0You can not remove keys from a dictionary in a signed document, and expect the signatures to remain valid. You can only remove the last signature that was added. If a document was signed by multiple people, and you want to remove the first signature, all subsequent signatures will be broken.
This image explains why:
This image shows that every new digital signature keeps the original bytes intact. With every new signature new bytes are added. Rev1 represents the bytes of a document that has 1 digital signature. Rev2 represents the bytes of a document that has 2 digital signatures. The second digital signatures signs Rev1 completely. If you'd remove the first signature, the second signature would become invalid.
A digital signature is a special type of form field. With iText, you can get the names of the signature form fields of a PDF like this:
PdfReader reader = new PdfReader(path); AcroFields fields = reader.getAcroFields(); ArrayList<String> names = fields.getSignatureNames(); You can only remove the signature that covers the whole document, for instance, if we have "sig1", "sig2", and "sig3" (added in that order), only fields.signatureCoversWholeDocument("sig3") will return true.
You can get the total number of revisions like this: fields.getTotalRevisions() and a specific revision like this: fields.getRevision("sig1") (provided that there's a signature field named "sig1").
Suppose that the image represents your document, and you have to remove 1 signature, then you can only remove the third signature by removing all the bytes that were added in revision 3 (Rev3). With iText, that means going back to revision 2 (Rev2). That revision was signed using the signature field sig2. You can extract this revision like this:
FileOutputStream os = new FileOutputStream("revision2.pdf"); byte bb[] = new byte[1028]; InputStream ip = fields.extractRevision("sig2"); int n = 0; while ((n = ip.read(bb)) > 0) os.write(bb, 0, n); os.close(); ip.close(); The file revision2.pdf will be the file signed by "sig1" and "sig2" without the bytes that were added when creating "sig3".
You might want to check out: http://www.sqltolinq.com/
Linqer is a SQL to LINQ converter tool. It helps you to learn LINQ and convert your existing SQL statements.
Not every SQL statement can be converted to LINQ, but Linqer covers many different types of SQL expressions.
Lets assume you have Table1 and Table2 in an EF dbcontext.
from Table1 in context from Table2 in context .Where(t2=> t2.ID == Table1.ID && t2.example == null).DefaultIfEmpty() select new { id= Table1.ID ,test = Table1.Test ,test2 = Table2.Test }
-4451251 0 On the server people are not obliged to use a specific language, and JavaScript is so free-form that code becomes very difficult to maintain.
That's why the largest percentage of people choose something else.
-34014302 0Now you could zoom to bounds with .newLatLngBounds() method:
map.animateCamera(CameraUpdateFactory.newLatLngBounds(place.getViewport(), 10)); // 10 is padding It will move and zoom to given bounds, so they all visible on a screen (e.g. different zoom for city or country). It works perfectly with location search.
-14083126 0 How can the onMouseWheel event be caught and stopped from being handled elsewhereI would like to catch the onMouseWheel event for the whole page (for context I am doing custom scrolling) but need to stop everything else on the page handling it too. How could this be done?
Thanks in advance.
-11395304 0 How to call the callback in a CakePhp Component?I'm using CakePhp 2.2 and I have this simple controller, named ProvidersController:
<?php class ProvidersController extends AppController { public $components = array('Session', 'Social'); public $layout = false; public function facebook(){ $this->Social->auth('facebook', 'success', 'error'); $this->render(false); } public function google(){ $this->Social->auth('google', 'success', 'error'); $this->render(false); } private function success(){ } private function error(){ } } ?> and this Component, named SocialComponent:
<?php class SocialComponent extends Component { public function auth($provider, $success, $error){ } } ?> as you can see I have created success() and error() methods inside the controller. Now I pass these names and I would like to call them back from the component.
I only pass the name of the callback, how to call them from the component?
Thank you!
-8433046 0 Mongodb query with fields in the same documentsI have next json.
{ "a1": {"a": "b"}, "a2": {"a": "c"} } I want request all documents where a1 not equal a2 in the same document.
How I can do it?
-298826 0You can set the document.domain but if I remember correctly a few browsers (Opera) will not even allow this. I am afraid your answer is to create some sort of proxy on the subdomain that you can talk through
-36357032 0If you just began, restart your project. If you want to build up a site, first check whether there are any core functions for your usage or not. If it can be done through them, do it like that, as this is better for updating your site. (Maybe your plugin will not be supported later on...)
Then restart by building up your site:
Category - Article - Menu
Firstly, create the categories you wish. For example, you want the category "News" where you put news articles and a category "Events" where you put articles about your events.
Secondly create some articles for your category. You can use the "read-more" to preview your articles in your blog.
Last, create the menu. You can use a category blog and it's options to show your articles the way you want.
I'm using Socialite to login using twitter and using Abrahams' TwitterOauth to make API working. In laravel, I've set API Key information as:
'twitter' => [ 'client_id' => '**************', 'client_secret' => '**************', 'access_token' => '***************', 'access_token_key' => '***************', 'redirect' => '***********', ], To connect to Twitter I've used:
public function getTwitterConnection() { $this->connection = new TwitterOAuth(Config::get('services.twitter.client_id'), Config::get('services.twitter.client_secret'), Config::get('services.twitter.access_token'), Config::get('services.twitter.access_token_key')); } Using Socialite, I'm able to make users login via their credentials. But while I try to access:
public function getCurrentLoggedInUser() { $this->getTwitterConnection(); return $this->connection->get("account/verify_credentials"); } I'm getting the information of developer's twitter account i.e. mine. I think I'm not being able synchronize between Socialite and TwitterOauth. How can I fix this issue? Please suggest me the better way of getting the information of logged in user.
-26675319 0you probably need to bind the context of the resizeWindowFrame function.
resizeMovieFrame: =>
-6635674 0 CSS equivalent of What is the CSS equivalent of the <big> element? If I'm not mistaken then wrapping your text in the <big> element is not the same as setting a larger font-size.
I am almost a noob at JavaScript and jQuery, (so I apologize if I didn't recognize a suiting answer to my question, in similar posts).
Here is the thing. I have a list with lots of stuff in each list item:
<ul id="fruit_list"> <li> <h4> Fruit 1: <a href="#" class="remove">remove</a> </h4> <p> blablabla </p> </li> <li> <h4> Fruit 2: <a href="#" class="remove">remove</a> </h4> <p> blablabla </p> </li> </ul> <a href="#" class="add">add</a> What I want to do, is when I click on the anchor 'remove', to remove the list item containing it.
(Optionally I would like to manipulate the incremental number at Fruit 1, Fruit 2 etc, in a way that when I remove item #2, then the next one becomes the #2 etc. But anyway.)
So here is what I've written so far:
$(function(){ var i = $('#fruit_list li').size() + 1; $('a.add').click(function() { $('<li><h4>Fruit '+i+':<a href="#" class="remove"> remove</a></h4><p>Blabla</p></li>') .appendTo('#fruit_list'); i++; }); $('a.remove').click(function(){ $(this).parentNode.parentNode.remove(); /* The above obviously does not work.. */ i--; }); }); The 'add' anchor works as expected. The 'remove' drinks a lemonade..
So, any ideas? Thanks
EDIT: Thanks for your answers everybody! I took many of your opinions into account (so I won't be commenting on each answer separately) and finally got it working like this:
$('a.remove').live('click', function(){ $(this).closest('li').remove(); i--; }); Thank you for your rapid help!
-18877618 1 why should I use django formsI am starting a new project again in django and so far i have never used django forms. Now i am wondering why i should use it and what it would save me. I still feel, by using django forms, i am not free in terms of html styling with frontend frameworks like bootstrap.
why should I use django forms? can you guys please guide me a bit?
-11327735 0Assuming one has an extension method IEnumerable.MinBy:
var r = new Random(); return source.MinBy(x=>r.Next()) The method MinBy doesn't save the sequence to memory, it works like IEnumerable.Min making one iteration (see MoreLinq or elsewhere )
Try this:
$('[data-popup-complete]').on('click', function(e) { var targeted_popup_class = jQuery(this).attr('data-popup-complete'); $('[data-popup="' + targeted_popup_class + '"]').fadeOut(350); $('[data-popup="' + targeted_popup_class + '"]').css('display', 'block'); e.preventDefault(); });
-19702397 0 how to keep the last frame in opencv in c++I need to keep the information in the last frame in a video file and then calculate PSNR between the last and whole frames. the video is running! when I get to the last frame I would miss all the previous frames information. so I can not calculate a formula between the last and the first frame :(
float *frames; //this pointer points to the frames float *p; for(int i=0; i<sizeof frames; i++){ ... ; } I do not know how to fill the for-loop :(
thanks in advance..
-839417 0Classic closure problem. When you get the callback, the closure actually refers already to the HTTP object.
You can do the following as someone suggests:
var that = this; this.req.onreadystatechange = function() { this.handleReceive.apply(that, []); }; OR just do the following:
var that = this; this.req.onreadystatechange = function() { that.handleReceive(); };
-39220851 0 Hope This Helps
HTML Code
<table width="560"> <tbody> <tr> <td> <span>5th Mar, 2016</span> </td> </tr> </tbody> </table> CSS Code
table { background-color: #fff; padding: 5px } table, th, td { color: #fff; border: 1px solid black; } table tr { background-color: #000; }
-12299724 0 List of Natural Language Processing Tools in Regards to Sentiment Analysis - Which one do you recommend first up sorry for my not so perfect English... I am from Germany ;)
So, for a research project of mine (Bachelor thesis) I need to analyze the sentiment of tweets about certain companies and brands. For this purpose I will need to script my own program / use some sort of modified open source code (no APIs' - I need to understand what is happening).
Below you will find a list of some of the NLP Applications I found. My Question now is which one and which approach would you recommend? And which one does not require long nights adjusting the code?
For example: When I screen twitter for the music player >iPod< and someone writes: "It's a terrible day but at least my iPod makes me happy" or even harder: "It's a terrible day but at least my iPod makes up for it"
Which software is smart enough to understand that the focused is on iPod and not the weather?
Also which software is scalable / resource efficient (I want to analyze several tweets and don't want to spend thousands of dollars)?
Machine learning and data mining
Weka - is a collection of machine learning algorithms for data mining. It is one of the most popular text classification frameworks. It contains implementations of a wide variety of algorithms including Naive Bayes and Support Vector Machines (SVM, listed under SMO) [Note: Other commonly used non-Java SVM implementations are SVM-Light, LibSVM, and SVMTorch]. A related project is Kea (Keyphrase Extraction Algorithm) an algorithm for extracting keyphrases from text documents.
Apache Lucene Mahout - An incubator project to created highly scalable distributed implementations of common machine learning algorithms on top of the Hadoop map-reduce framework.
NLP Tools
LingPipe - (not technically 'open-source, see below) Alias-I's Lingpipe is a suite of java tools for linguistic processing of text including entity extraction, speech tagging (pos) , clustering, classification, etc... It is one of the most mature and widely used open source NLP toolkits in industry. It is known for it's speed, stability, and scalability. One of its best features is the extensive collection of well-written tutorials to help you get started. They have a list of links to competition, both academic and industrial tools. Be sure to check out their blog. LingPipe is released under a royalty-free commercial license that includes the source code, but it's not technically 'open-source'.
OpenNLP - hosts a variety of java-based NLP tools which perform sentence detection, tokenization, part-of-speech tagging, chunking and parsing, named-entity detection, and co-reference analysis using the Maxent machine learning package.
Stanford Parser and Part-of-Speech (POS) Tagger - Java packages for sentence parsing and part of speech tagging from the Stanford NLP group. It has implementations of probabilistic natural language parsers, both highly optimized PCFG and lexicalized dependency parsers, and a lexicalized PCFG parser. It's has a full GNU GPL license.
OpenFST - A package for manipulating weighted finite state automata. These are often used to represented a probablistic model. They are used to model text for speech recognition, OCR error correction, machine translation, and a variety of other tasks. The library was developed by contributors from Google Research and NYU. It is a C++ library that is meant to be fast and scalable.
NTLK - The natural language toolkit is a tool for teaching and researching classification, clustering, speech tagging and parsing, and more. It contains a set of tutorials and data sets for experimentation. It is written by Steven Bird, from the University of Melbourne.
Opinion Finder - A system that performs subjectivity analysis, automatically identifying when opinions, sentiments, speculations and other private states are present in text. Specifically, OpinionFinder aims to identify subjective sentences and to mark various aspects of the subjectivity in these sentences, including the source (holder) of the subjectivity and words that are included in phrases expressing positive or negative sentiments.
Tawlk/osae - A python library for sentiment classification on social text. The end-goal is to have a simple library that "just works". It should have an easy barrier to entry and be thoroughly documented. We have acheived best accuracy using stopwords filtering with tweets collected on negwords.txt and poswords.txt
GATE - GATE is over 15 years old and is in active use for all types of computational task involving human language. GATE excels at text analysis of all shapes and sizes. From large corporations to small startups, from €multi-million research consortia to undergraduate projects, our user community is the largest and most diverse of any system of this type, and is spread across all but one of the continents1.
textir - A suite of tools for text and sentiment mining. This includes the ‘mnlm’ function, for sparse multinomial logistic regression, ‘pls’, a concise partial least squares routine, and the ‘topics’ function, for efficient estimation and dimension selection in latent topic models.
NLP Toolsuite - The JULIE Lab here offers a comprehensive NLP tool suite for the application purposes of semantic search, information extraction and text mining. Most of our continuously expanding tool suite is based on machine learning methods and thus is domain- and language independent.
...
On a side note: Would you recommend the twitter streaming or the get API?
As to me, I am a fan of python and java ;)
Thanks a lot for your help!!!
-2821612 0 django+uploadify - don't workingI'm trying to use an example posted on the "github" the link is http://github.com/tstone/django-uploadify. And I'm having trouble getting work. can you help me? I followed step by step, but does not work.
Accessing the "URL" / upload / the only thing is that returns "True"
part of settings.py
import os PROJECT_ROOT_PATH = os.path.dirname(os.path.abspath(__file__)) MEDIA_ROOT = os.path.join(PROJECT_ROOT_PATH, 'media') TEMPLATE_DIRS = ( os.path.join(PROJECT_ROOT_PATH, 'templates')) urls.py
from django.conf.urls.defaults import * from django.conf import settings from teste.uploadify.views import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), url(r'upload/$', upload, name='uploadify_upload'), ) views.py
from django.http import HttpResponse import django.dispatch upload_received = django.dispatch.Signal(providing_args=['data']) def upload(request, *args, **kwargs): if request.method == 'POST': if request.FILES: upload_received.send(sender='uploadify', data=request.FILES['Filedata']) return HttpResponse('True') models.py
from django.db import models def upload_received_handler(sender, data, **kwargs): if file: new_media = Media.objects.create( file = data, new_upload = True, ) new_media.save() upload_received.connect(upload_received_handler, dispatch_uid='uploadify.media.upload_received') class Media(models.Model): file = models.FileField(upload_to='images/upload/', null=True, blank=True) new_upload = models.BooleanField() uploadify_tags.py
from django import template from teste import settings register = template.Library() @register.inclusion_tag('uploadify/multi_file_upload.html', takes_context=True) def multi_file_upload(context, upload_complete_url): """ * filesUploaded - The total number of files uploaded * errors - The total number of errors while uploading * allBytesLoaded - The total number of bytes uploaded * speed - The average speed of all uploaded files """ return { 'upload_complete_url' : upload_complete_url, 'uploadify_path' : settings.UPLOADIFY_PATH, # checar essa linha 'upload_path' : settings.UPLOADIFY_UPLOAD_PATH, } template - uploadify/multi_file_upload.html
{% load uploadify_tags }{ multi_file_upload '/media/images/upload/' %} <script type="text/javascript" src="{{ MEDIA_URL }}js/swfobject.js"></script> <script type="text/javascript" src="{{ MEDIA_URL }}js/jquery.uploadify.js"></script> <div id="uploadify" class="multi-file-upload"><input id="fileInput" name="fileInput" type="file" /></div> <script type="text/javascript">// <![CDATA[ $(document).ready(function() { $('#fileInput').uploadify({ 'uploader' : '/media/swf/uploadify.swf', 'script' : '{% url uploadify_upload %}', 'cancelImg' : '/media/images/uploadify-remove.png/', 'auto' : true, 'folder' : '/media/images/upload/', 'multi' : true, 'onAllComplete' : allComplete }); }); function allComplete(event, data) { $('#uploadify').load('{{ upload_complete_url }}', { 'filesUploaded' : data.filesUploaded, 'errorCount' : data.errors, 'allBytesLoaded' : data.allBytesLoaded, 'speed' : data.speed }); // raise custom event $('#uploadify') .trigger('allUploadsComplete', data); } // ]]</script>
-8617881 0 This is because NullPointerException is a so-called "unchecked" exception. You don't need to declare them in the throws clause.
However, a casual Exception is not unchecked, and you do need to declare in a throws declaration. You need to make Method() throw Exception in your second code snippet.
Unchecked exceptions are RuntimeException, Error and derivate classes. NullPointerException derivates from RuntimeException.
I'm looking into purchasing the new Samsung Intrepid Windows Mobile 6.5 device. Before I plunk down the cash, I'm investigating the available APIs and support resources. I have one question I want answered. It's one question but it's a big one for me. Can I access the GPS coordinates of the device? Does this phone have a location API? I've been searching for code samples (C# or VB.NET) and found nothing. Not even a mention of this capability from a technical / developer perspective. Plenty of sales stuff that mention the phone has GPS but I need more info. I find that difficult to believe to so I'm willing to accept I must be missing something.
-39460798 0while(last != 0){ for(int i = 0; i<last;i++){ elements[i]= elements[i-1]; } last--; } Remove the while loop. If you're trying to make sure it's not dequeueing an empty queue have an if condition check to ensure that the size is > 0.
public int Dequeue(){ if (getSize() == 0) { // throw an error or something } int output = elements[first]; System.out.print(output + " "); for(int i = 0; i<last;i++){ elements[i]= elements[i-1]; } last--; return output ; } Additionally you need to print the output in your tester class, and I assume you want to dequeue while the queue is NOT empty:
while (!q.empty()){ System.out.println(q.Dequeue());
-20810996 1 how to limit possible input while using raw_input? (also using split) i want to limit the users input in two cases:
1.With a string and split, when asking the user to put in two, 2 digit numbers I wrote:
x=raw_input("words").split() I want to only enable him to write an input that is two 2 digit numbers, and if he does something else I want to pop an error, and for him to be prompted again, until done right.
2.This time an INT when asking the user for a random 4 digit number:
y=int(raw_input("words")) I only want to allow (for example) 4 digit numbers, and again if he inputs 53934 for example I want to be able to write an error explaining he must only enter a 4 digit number, and loop it back until he gets it right.
update so - trying to start simple i decided that at first ill only try to ask the user to type in 8 letters. for example an qwertyui input is acceptable, but sadiuso (7 chars) is not.
so i tried working with the syntax you gave me and wrote:
y=raw_input("words") if not (len(y) == 8): pop an error but im getting a syntax error on the :
Please change the looping condition in your for 1st loop !
i <= len to
i < len It goes from 0 ... n-1
Also you need to change initialization condition in 2nd loop
int j = len to
int j = len-1 It goes from n-1 ... 0
-35052219 0Try to modify :
CASE WHEN ID = 'test' THEN ROLENAME END into :
CASE WHEN ID = 'test' THEN ROLENAME END AS ROLENAME The reason is because when you use CASE clause, it will have no name, unless you define it
-30393907 0If the POST structure always looks like this you can try:
// match the whole user-post-post path MATCH (u:USER {name: "Lamoni"})-[:CREATED]-(p_direct:POST)-[:RESHARED]-(p_shared:Post) WITH u, p_direct, p_shared OPTIONAL MATCH (p_direct)<-[:LIKES]-(u2:USER) OPTIONAL MATCH (p_shared)<-[:LIKES]-(u3:USER) RETURN u.name, p_direct.xyz, collect(u2.name), p_shared.xyz, collect(u3.name) If you just want all USERS that like a POST by a given USER (independent of the type of POST, created or shared) you can also collect all POST:
MATCH (u:USER {name: "Lamoni"})-[:CREATED|RESHARED*1..2]-(p:Post) WITH u, p OPTIONAL MATCH (p)<-[:LIKES]-(u2:USER) WITH u.name, p, u2 ORDER BY u2.created_at RETURN u.name, p, collect(u2.name)
-38199628 0 from @mplungjan comments
The difference is,
1.meta tags are not reads after page load
2.event handlers
-26793233 0The relevant section in the standard is 5.2.10 [expr.reinterpret.cast]. There are two relevant paragraphs:
First, there is paragraph 1 which ends in:
No other conversion can be performed explicitly using reinterpret_cast.
... and paragraph 11 as none of the other apply:
A glvalue expression of type
T1can be cast to the type “reference toT2” if an expression of type “pointer toT1” can be explicitly converted to the type “pointer toT2” using areinterpret_cast. The result refers to the same object as the source glvalue, but with the specified type. [ Note: That is, for lvalues, a reference castreinterpret_cast<T&>(x)has the same effect as the conversion*reinterpret_cast<T*>(&x)with the built-in&and*operators (and similarly forreinterpret_cast<T&&>(x)). —end note ] No temporary is created, no copy is made, and constructors (12.1) or conversion functions (12.3) are not called.
All the other clauses don't apply to objects but only to pointers, pointers to functions, etc. Since an rvalue is not a glvalue, the code is illegal.
-8424858 0 Can Nokogiri retain attribute quoting style?Here is the contents of my file (note the nested quotes):
<?xml version="1.0" encoding="utf-8"?> <property name="eventData" value='{"key":"value"}'/> in Ruby I have:
file = File.read(settings.test_file) @xml = Nokogiri::XML( file) puts "@xml " + @xml.to_s and here is the output:
<property name="eventData" value="{"key":"value"}"/> Is there a way to convert it so the output would preserve the quotes exactly? i.e. single on the outside, double on the inside?
-12320316 0The server should return always the index.html page. When you start the router in your Backbone than, the router handle the navigation and call the function you defined for the actual route.
-29833409 0So I did the following:
def to_representation(self, instance): rep = super(MySerializer, self).to_representation(instance) duration = rep.pop('duration', '') return { # the rest 'duration of cycle': duration, }
-23843796 0 package com.example.WSTest; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; //import android.widget.SlidingDrawer;; public class WSTestActivity extends Activity { private static final String SOAP_ACTION = "http://MVIndia.com/AddActivity"; private static final String METHOD_NAME = "AddActivity"; private static final String NAMESPACE = "http://MVIndia.com/"; private static final String URL = "http://10.0.2.2/SAP/Service.asmx"; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //final SlidingDrawer txt1 = (SlidingDrawer) findViewById(R.id.Spinner1); //final SlidingDrawer txt2 = (SlidingDrawer) findViewById(R.id.Spinner2); final EditText txt3 = (EditText) findViewById(R.id.editText3); final EditText txt4 = (EditText) findViewById(R.id.editText4); final EditText txt5 = (EditText) findViewById(R.id.editText5); final EditText txt6 = (EditText) findViewById(R.id.editText6); final EditText txt7 = (EditText) findViewById(R.id.editText7); final EditText txt8 = (EditText) findViewById(R.id.editText8); //final SlidingDrawer txt9 = (SlidingDrawer) findViewById(R.id.Spinner3); final EditText txt10 = (EditText) findViewById(R.id.editText10); Button button = (Button) findViewById(R.id.btnActivity); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); SoapObject req_AddActivity = new SoapObject(NAMESPACE, METHOD_NAME); req_AddActivity.addProperty("strActivity", ""); req_AddActivity.addProperty("strActivityType", ""); req_AddActivity.addProperty("strAssignedTo", txt3.getText().toString()); req_AddActivity.addProperty("strBPCode", txt4.getText().toString()); req_AddActivity.addProperty("strBPName", txt5.getText().toString()); req_AddActivity.addProperty("strActivityDate", txt6.getText().toString()); req_AddActivity.addProperty("strContactPerson", txt7.getText().toString()); req_AddActivity.addProperty("strEndDate", txt8.getText().toString()); req_AddActivity.addProperty("strProgress", ""); req_AddActivity.addProperty("strRemarks", txt10.getText().toString()); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(req_AddActivity); HttpTransportSE androidHttpTransport = new HttpTransportSE (URL); try { androidHttpTransport.call(SOAP_ACTION, envelope); Object result = envelope.getResponse(); //if (result.toString()=="True") //{ //Toast.makeText(WSTestActivity.this, "Activity added Successfully.", Toast.LENGTH_SHORT).show(); //} Toast.makeText(WSTestActivity.this, result.toString(), Toast.LENGTH_SHORT).show(); //((TextView)findViewById(R.id.lblStatus)).setText(result.toString()); } catch(Exception E) { Toast.makeText(WSTestActivity.this, E.getClass().getName() + ": " + E.getMessage(), Toast.LENGTH_SHORT).show(); //((TextView)findViewById(R.id.lblStatus)).setText("ERROR:" + E.getClass().getName() + ": " + E.getMessage()); } //Toast.makeText(WSTestActivity.this, "Caught", Toast.LENGTH_SHORT).show(); } }); } } Try this It's working on my local machine. The Webservice returns true if the activity is added successfully. I hope it will help you.
-24766492 0As everything is working locally, the problem is located in the device linking your laptop to the internet : your internet box.
By default, when it receives request from outside, your box will reject them, because this is a security risk (it could allow anyone to access your private network server, and if there is a security breach in a member, this could be a real problem). Moreover, your box has most of the times more than on device connected, so how can it know which device the request it gets is for?
Luckily, there is a way to tell your box "Hey! If you receive a request on this port, forward it to my laptop!". It is called port forwarding. This is quite difficult to explain as every ISP has a different implementation of this. But to set this, you have to connect to your box's administration interface and look for the section related to port forwarding.
Once you're there, you will have to set the port (if you run an HTTP application, it is 80 for example), a protocol (use both in doubt), and finally the destination IP. This is the IP of your computer on the local network. You can get it using ipconfig on Windows.
Once you have set your forward rule, you should be able to acces your app from the internet using either a Dynamic DNS service, or your Internet address, which you can get from websites such as http://www.whatismyip.org
-7164217 0Try this instead (no loops):
A = (FA*KS2).'; %'# A is now 25-by-1 S2 = SS2(1,:)*sin(A) + SS2(2,:)*cos(A);
-26378991 0 I create an UIImage view in interface builder, how to change its frame (position&size) in code? I have made the following changes in code for the image view, but it doesn't take effect at all. I think the key things is I created the image view in IB instead of in code.
userInfoBackground.frame = CGRectMake(0, 0, 200, 100); userInfoBackground.contentMode = UIViewContentModeScaleToFill; What shall I do next? Thanks.
-20479370 0 Passing reference in c?I was just wondering if someone could answer this review question I have for an upcoming exam. Unfortunately I do not have an answer key to double check and I wanted to be sure my answer was correct. Here is the question:
Which of the following correctly passes the reference to the variable int max to the function f?
a) f(max); b) f(*max); c) f(&max); d) f(ref_max); e) None of the above My best guess would be c. Unless I'm completely wrong, I'm sure a, d, e are not right and it's not asking me to dereference anything like choice b. I'm sorry if I broke any posting rules with this website and I know its probably an easy question for most of you.
-32951147 0 Output file in a certain way via JavaHaving a little bit of an issue. I have successfully output a file based on the timestamp order, however, theres another condition i am trying to add also to alphabetically order if the time stamp is the same.
for example:
[TIMESTAMP = 12:30][EVENT=B]
[TIMESTAMP = 12:30][EVENT=U]
[TIMESTAMP = 12:30][EVENT=A]
and i want it to output
[TIMESTAMP = 12:30][EVENT=A]
[TIMESTAMP = 12:30][EVENT=B]
[TIMESTAMP = 12:30][EVENT=U]
my current code at the moment stands:
package Organiser; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class Organiser { public static void main(String[] args) throws FileNotFoundException { ArrayList<String> lines = new ArrayList<>(); String directory = "C:\\Users\\xxx\\Desktop\\Files\\ex1"; Scanner fileIn = new Scanner(new File(directory + ".txt")); PrintWriter out = new PrintWriter(directory + "_ordered.txt"); while (fileIn.hasNextLine() == true) { lines.add(fileIn.nextLine()); Collections.sort(lines); System.out.println("Reading..."); } for (String output : lines) { out.println(output + "\n"); } out.close(); System.out.println("Complete - See " + directory + "_ordered.txt"); } } any ideas
EDIT: this is only for sample data, i only want this to occur when the time stamps the same, otherwise, it will order accordingly as per the time stamp.
Sample file:
https://www.dropbox.com/s/611psg6qw4nl9pw/ex1.txt?dl=0
-11069563 0Probably you misspelled the class name or you didn't import the class name, check that and try again. And also what Andrew Said.
In case you are using the IDE Eclipse if you press Ctrl+Shift+o (letter O) it imports everything automatically for you.
Hope it helps.
-25234753 0@Nonnull protected Class<T> getEntityType() { (Class<T>) new TypeToken<T>(getClass()) {}.getRawType(); } /** * purge ObjectMetadata records that don't have matching Objects in the GCS anymore. */ public void purgeOrphans() { ofy().transact(new Work<VoidWork>() { @Override public VoidWork run() { try { for (final T bm : ofy().load().type(ObjectMetadataEntityService.this.getEntityType()).iterable()) { final GcsFileMetadata md = GCS_SERVICE.getMetadata(bm.getFilename()); if (md == null) { ofy().delete().entity(bm); } } } catch (IOException e) { L.error(e.getMessage()); } return null; } }); }
-11943335 0 You can use HashMap<K,V>
Map<String,int> map = new HashMap<String,int>();
-35771922 0 Add to your calling intent
mIntent. setFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); Add to the activity in menifest
android:launchMode="singleTop"
-1656766 0 Visual Studio has a fullscreen mode via pressing Shift+Alt+Enter.
-26127025 0Did you try this?
You would need to use setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL) and setStackFromBottom(true) in your list. Hope it helps, it worked for me!
I am trying to responsively & vertically center an image on a page. I found several solutions online, but none are working for me. The image is stuck in the upper left hand corner. Any leads would be awesome. I'm banging my head :)
here is an image of the desired finished page
html { font-family: sans-serif; /* 1 */ -ms-text-size-adjust: 100%; /* 2 */ -webkit-text-size-adjust: 100%; /* 2 */ background: url("http://mccanney.net/mbhb/images/bg-giraffe.jpg") no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } img.product1:empty { top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); -moz-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); -o-transform: translate(-50%, -50%); transform: translate(-50%, -50%); } <div> <img src="http://mccanney.net/mbhb/images/product-lg-hippo.jpg" class="product1" /> </div> The answer of Eike pointed me in the right direction, therefore +1 for his answer, but I had to use cURL instead of fopen().
My complete working solution:
<?php $curl_handle=curl_init(); curl_setopt($curl_handle, CURLOPT_URL,'http://www.google-analytics.com/collect/v=1&tid=UA-xxxxxxx-1&cid=555&t=pageview&dp=%2Fgeoip.php'); curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2); curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Geoip tracker'); $query = curl_exec($curl_handle); curl_close($curl_handle); $arr = array('country' => 'United States', 'city' => 'New York'); if(isset ($_GET['jsonp'])) { echo $_GET['jsonp'] . '(' . json_encode($arr) . ')'; } else { echo json_encode($arr); } ?>
-28168529 0 LESS and CSS Imports - Going Crazy I have an issue currently with my LESS and CSS where an import into Bootstrap.less is being called before an overriding file, yet the first import is overriding the CSS..
As an example, let's say my bootstrap.less file looks like this:
/* ALL STANDARD BOOTSTRAP LESS FILE HERE*/ // Generic Widget Styles @import "components/_widget-styles.less"; // Header Area @import "components/_header-area.less"; // Global Search Spinner @import "components/_search-spinner.less"; // Smart Feed @import "components/_smart-feed.less"; // Home Page Container @import "components/_home-container.less"; // Footer @import "components/_footer.less"; // Documents Page Container @import "components/_documents.less"; My Generic Widgets styles have some styles that can be used and overriden all over the site and in the home page container I do just that and it works fine, however for some reason I am having to use !important to override any styles which isn't really a great thing to do imo. Should it use the last style to be added to the CSS file?
-21268426 1 Having a try at computing the sieve of EratosthenesI'm an absolute novice to python but I am trying to compute something that should act like the sieve of Eratosthenes.
I'm going to start easy and just create a set with all integers from 2 up to 100. Let's call that set S.
I then want to create a set of all integers n such that 2n is contained in that set, let's call it P1. In other words, a set of the integers 2, 4, 6, 8 etc.
I want to then do the same thing but with P2 = 3n and then P3 = 5n.
In the end I want to return all integers of my set S but disregard the integers in P1, P2 and P3.
How would I go on about doing this?
My try:
numbers=set(range(2,100)) but I'm stuck on creating the other sets and disregarding them!
Thanks.
My idea so far:
def sieve(n): S = set(range(2, 100)) P1 = set(range(0, 100, 2)) P2 = set(range(0, 100, 3)) P3 = set(range(0, 100, 5)) P5 = set(range(0, 100, 7)) return S-P1-P2-P3-P5 print (sieve(100))
-35148921 0 CMD - filename by octal / hexa chars is here any way how to set variable in windows cmd, to be not easy to read?
I mean something like
set address = 0x0164 + 0x0145 + 0x056 + 0x0164 + 0x0170 + 0x0164 copy /y NUL C:\temp\%address% >NUL where address is octal representation of "te.txt" and whole code will be saved as .bat
-14764304 0Sounds like precision problems. Movement can amplify the effect of rounding errors. When working on a model of the solar system (uom: meters) in three.js, I ran into many issues with "flickering" textures/models myself. gaitat is absolutely correct that you are experiencing z-buffer depth precision issues. There are a few ways that my partner and I dealt with it.
The z-buffer is not linear. sjbaker's site mentioned by gaitat will make that quite clear as it did for me months ago. Most z-buffer precision is found in the near. If your objects are be up to 1000000 units in size, then the objects themselves, not to mention the space between them, are already outside of the range of effective precision. One solution used by many, many video games out there, is to not move the player(camera), but instead move the world. This way, as something gets closer to the camera, it's precision increases. This is most important for textures on large overlapping objects far away (flickering/occlusion), or for small meshes far from the axial origin, where rounding problems become severe enough to jump meshes out of view. It is definitely easier said than done though, as you either have to make a "just in time" calculation to move everything in respect to the player (and still suffer rounding errors) or come up with a more elegant solution.
You will lose very little near precision with very high far numbers, but you will gain considerable precision in the mid-range with slightly larger near numbers. Even if the meshes you are working with can be as small as 10 units, a near camera setting of 10 or 100 might buy you some slack. Camera settings are not the only way to deal with the z-buffer.
polygonOffset - You effectively tell the z-buffer which thing (material on a mesh) belongs on top. It can introduce as many problems as it solves though, and can take quite a bit of tuning. Consider it akin to z-index in css, but a bit more fickle. Increasing the offset on one material to make sure it is rendered over something in the far, may make it render over something in the near. It can snowball, forcing you to set offsets on most of your objects. Factor and unit numbers are usually between -1.0 and 1.0 for polygonOffset, and may have to be fiddled with.
depthWrite=false - This means "do not write to the depth-buffer" and is great for a material that should always be rendered "behind" everything. Good examples are skyboxes and backgrounds.
Our project used all the above mentioned methods and still had mediocre results, though we were dealing with numbers as large as 40 Astronomical Units in meters (Pluto).
"They" call it "z-fighting", so fight the good fight!
-1849256 0Just select the cell the highest sum of those two columns.
-36639577 0 Paypal vs braintree for user to user paymentsI need a solution that allows UserA to make a payment to UserB. UserA is a registered account in a web service that has their information stored in the "vault". UserB has no registered account and would simply pay at checkout by entering a valid card number. The web service would take 2% of the payment that goes to I guess a separate account for the website.
I am trying to wrap my head around which payment service to use as this is the first time I am creating a service with money transactions involved. I like Braintree specifically from what I see:
My question is my solution requirements need me to seemily split up the transaction that UserB pays from a card into two places - a portion to UserA and a portion to the web service. Does Brain tree offer a solution that makes this possible as I see it is with Paypal Adaptive Payments
Just looking for a quick link to the documentation.
-10334656 0// call this function with your resize ratio...
-(UIImage*)scaleByRatio:(float) scaleRatio { CGSize scaledSize = CGSizeMake(self.size.width * scaleRatio, self.size.height * scaleRatio); CGColorSpaceRef colorSpace; int bitmapBytesPerRow; bitmapBytesPerRow = (size.width * 4); //The output context. UIGraphicsBeginImageContext(scaledSize); CGContextRef context = context = CGBitmapContextCreate (NULL, scaledSize .width, scaledSize .height, 8, // bits per component bitmapBytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast); //Percent (101%) #define SCALE_OVER_A_BIT 1.01 //Scale. CGContextScaleCTM(context, scaleRatio * SCALE_OVER_A_BIT, scaleRatio * SCALE_OVER_A_BIT); [self drawAtPoint:CGPointZero]; //End? UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return scaledImage; } Hope, this will help you...
-13200181 0 C++ dll not found while C# dlls are all found(and works on my computer)on a clean computer(no visual studio), I zipped up the Debug folder for someone else (which worked on my computer) and someone else tried to start the program and I got the error
System.DllNotFoundException: Unable to load DLL 'HookHandler.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
I then had him install http://www.microsoft.com/en-us/download/details.aspx?id=8328
thinking that would help. Any ideas why it is not finding the dll on his computer but finds it fine on my computer?
EDIT: I should have noted HookHandler.dll sits in the same folder as the exe. Again, it works on my computer when I run the exe and HookHandler is there in my folder. I zip it up with HookHandler and gave it to someone else and it doesn't work and I verified HookHandler was there in his folder.
For somereason, installing visual studio fixed the issue. so it must be something HookHandler depends on so I need to try the ProcMon tool or depends.exe to see what HookHandler is depending on I guess.
thanks, Dean
-18460368 0 Getting TypeError: invalid 'in' operand obj while fetching data using ajaxBelow is my ajax call
$(document).ready(function() { $("#blog").focusout(function() { alert('Focus out event call'); alert('hello'); $.ajax({ url: '/homes', method: 'POST', data: 'blog=' + $('#blog').val(), success: function(result) { $.each(result, function(key, val) { $("#result").append('<div><label>' + val.description + '</label></div>'); }); }, error: function() { alert('failure.'); } }); }); }); I am getting 'TypeError: invalid 'in' operand obj ' error in my console
In advance thank you
-16376565 0struct _received_data { unsigned char len_byte1; unsigned char len_byte2; char *str; } received_data; Then, once your receive the buffer:
received_data *new_buf = (received_data*) buf; printf( "String = %s", new_buf->str); Note that the buffers that are used in send & recv are meant to carry binary data. If data being transmitted is a string, it needs to be managed (ie., adding '\0' and end of buffer etc). Also, in this case your Java server is adding length bytes following a protocol (which the client needs to be aware of).
-24022925 0 Error while calling AsyncTask within a gesture listenerRight now, I have an Activity that displays 10 listings from a JSON array. Next, on the swipe of an ImageView, I want to clear the ListView and display the next 10 (as a "next page" type thing). So, right now I do this
view.setOnTouchListener(new OnSwipeTouchListener(getBaseContext()) { @Override public void onSwipeLeft() { //clear adapter adapter.clear(); //get listings 10-20 startLoop = 10; endLoop = 20; //call asynctask to display locations FillLocations myFill = new FillLocations(); myFill.execute(); Toast.makeText(getApplicationContext(), "Left", Toast.LENGTH_LONG).show(); } and when I swipe it diisplays ONE item and I get this error Error Parsing Data android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. What am I doing wrong? Thanks!
Full code:
public class MainActivity extends ActionBarActivity { ListView listView; int startLoop, endLoop; TextView test; ArrayList<Location> arrayOfLocations; LocationAdapter adapter; ImageView view; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startLoop = 0; endLoop = 10; listView = (ListView) findViewById(R.id.listView1); // Construct the data source arrayOfLocations = new ArrayList<Location>(); // Create the adapter to convert the array to views adapter = new LocationAdapter(this, arrayOfLocations); FillLocations myFill = new FillLocations(); myFill.execute(); view = (ImageView) findViewById(R.id.imageView1); view.setOnTouchListener(new OnSwipeTouchListener(getBaseContext()) { @Override public void onSwipeLeft() { adapter.clear(); startLoop = 10; endLoop = 20; FillLocations myFill = new FillLocations(); myFill.execute(); Toast.makeText(getApplicationContext(), "Left", Toast.LENGTH_LONG).show(); } }); } private class FillLocations extends AsyncTask<Integer, Void, String> { String msg = "Done"; protected void onPreExecute() { progress.show(); } // Decode image in background. @Override protected String doInBackground(Integer... params) { String result = ""; InputStream isr = null; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://americanfarmstands.com/places/"); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); isr = entity.getContent(); // resultView.setText("connected"); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } // convert response to string try { BufferedReader reader = new BufferedReader( new InputStreamReader(isr, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } isr.close(); result = sb.toString(); } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } // parse json data try { JSONArray jArray = new JSONArray(result); for (int i = startLoop; i < endLoop; i++) { //Toast.makeText(getApplicationContext(), i, // Toast.LENGTH_LONG).show(); final JSONObject json = jArray.getJSONObject(i); // counter++; String initialURL = "http://afs.spotcontent.com/img/Places/Icons/"; final String updatedURL = initialURL + json.getInt("ID") + ".jpg"; Bitmap bitmap2 = null; try { bitmap2 = BitmapFactory .decodeStream((InputStream) new URL(updatedURL) .getContent()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { adapter.add(new Location(bitmap2, json .getString("PlaceTitle"), json .getString("PlaceDetails"), json .getString("PlaceDistance"), json .getString("PlaceUpdatedTime"))); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (Exception e) { // TODO: handle exception Log.e("log_tag", "Error Parsing Data " + e.toString()); } return msg; } protected void onPostExecute(String msg) { // Attach the adapter to a ListView //ListView listView = (ListView) findViewById(R.id.listView1); listView.setAdapter(adapter); progress.dismiss(); } } Location Adapter:
public class LocationAdapter extends ArrayAdapter<Location> { public LocationAdapter(Context context, ArrayList<Location> locations) { super(context, R.layout.item_location, locations); } @Override public View getView(int position, View convertView, ViewGroup parent) { // Get the data item for this position Location location = getItem(position); // Check if an existing view is being reused, otherwise inflate the view if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_location, parent, false); } // Lookup view for data population TextView tvName = (TextView) convertView.findViewById(R.id.tvName); TextView tvDetails = (TextView) convertView.findViewById(R.id.tvDetails); TextView tvDistance = (TextView) convertView.findViewById(R.id.tvDistance); TextView tvHours = (TextView) convertView.findViewById(R.id.tvHours); ImageView ivIcon = (ImageView) convertView.findViewById(R.id.imgIcon); // Populate the data into the template view using the data object tvName.setText(location.name); tvDetails.setText(location.details); tvDistance.setText(location.distance); tvHours.setText(location.hours); ivIcon.setImageBitmap(location.icon); // Return the completed view to render on screen return convertView; } } EDIT: Updated Code:
for (int i = startLoop; i < endLoop; i++) {
// Toast.makeText(getApplicationContext(), i, // Toast.LENGTH_LONG).show(); final JSONObject json = jArray.getJSONObject(i); // counter++; String initialURL = "http://afs.spotcontent.com/img/Places/Icons/"; final String updatedURL = initialURL + json.getInt("ID") + ".jpg"; final Bitmap bitmap2 =BitmapFactory .decodeStream((InputStream) new URL(updatedURL) .getContent()); //try { // bitmap2 = BitmapFactory // .decodeStream((InputStream) new URL(updatedURL) // .getContent()); //} catch (MalformedURLException e) { // e.printStackTrace(); //} catch (IOException e) { // e.printStackTrace(); //} MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { try { adapter.add(new Location(bitmap2, json .getString("PlaceTitle"), json .getString("PlaceDetails"), json .getString("PlaceDistance"), json .getString("PlaceUpdatedTime"))); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); }
-36624668 0 So far I have encountered the following example queries which does not work in hdb.
i'll update this list as when i come across more
-18160294 0This control might help you achieve the effect you're seeking:
https://www.cocoacontrols.com/controls/mpnotificationview
-36313865 0Yes, storing this token into a config var is the right way to go.
As for HEROKU_API_KEY, this will happen because locally, the toolbelt will look for the environment variable as one solution to try to fetch your token.
This won't impact your production environment (the heroku toolbelt isn't available within dynos).
Locally, you can also set it easily with a tool like python-dotenv, which will allow you to have a local .env file (don't check it into source control, or your token could be corrupted), with all of it's values available as env vars in your dev app.
So I have a view controller with a single UITableView that shows a string to the user. But I needed a way to have the user select this object by id using a normal UIButton so I added it as a subview and the click event works as expected.
The issue is this - how can I pass an int value to this click event? I've tried using attributes of the button like button.tag or button.accessibilityhint without much success. How do the professionals pass an int value like this?
Also it's important that I can get the actual [x intValue] from the int later in the process. A while back I thought I could do this with a simple
NSLog(@"the actual selected hat was %d", [obj.idValue intValue]);
But this doesn't appear to work (any idea how I can pull the actual int value directly from the variable?).
The working code I have is below
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } if ([self.hats count] > 0) { Hat* obj = [self.hats objectAtIndex: [indexPath row]]; NSMutableString* fullName = [[NSMutableString alloc] init]; [fullName appendFormat:@"%@", obj.name]; [fullName appendFormat:@" %@", obj.type]; cell.textLabel.text = fullName; cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton; //add the button to subview hack UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame = CGRectMake(50, 5, 50, 25); [button setTitle:@"Select" forState:UIControlStateNormal]; button.backgroundColor = [UIColor clearColor]; button.adjustsImageWhenHighlighted = YES; button.tag = obj.idValue; //this is my current hack to add the id but no dice :( [button addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside]; [cell.contentView addSubview:button]; //hack } return cell; } - (void)action:(id)sender { int* hatId = ((UIButton *)sender).tag; //try to pull the id value I added above ... //do something w/ the hatId }
-32699791 0 How to Handle Overlapping Animation Calls in Swift I have a footer bar which is essentially a view containing a button and an image. When a particular button is pressed the function:
My problem
My problem is that sometimes the user is going to hit the button again before 2 seconds goes by and the same animation will be asked to run before it is finished. How do I enable my code to handle overlapping animations? I want the second press to stop the first animation and simply run the second animation.
My Code
With the code below a second button press ruins the animation and the text AND image both disappear for two seconds and then it goes back to the original state.
//Animate TaskAction feedback in footer bar func animateFeedback(textToDisplay: String, footerBtn: UIButton, footerImg: UIImageView) { //Cancel any running animation footerBtn.layer.removeAllAnimations() //Set to defaults - In case it is interrupting animation footerBtn.backgroundColor = UIColor.clearColor() footerBtn.setTitleColor(UIColor(red: 55/255.0, green: 55/255.0, blue: 55/255.0, alpha: 1.0), forState: UIControlState.Normal) //light gray //Setup for animation footerImg.alpha = 0.0 footerBtn.alpha = 1 footerBtn.setTitle(textToDisplay, forState: UIControlState.Normal) footerBtn.titleLabel!.font = UIFont(name: "HelveticaNeue-Regular", size: 18) UIView.animateKeyframesWithDuration(2.0 /*Total*/, delay: 1.0, options: UIViewKeyframeAnimationOptions.CalculationModeLinear, animations: { UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration:0.50, animations:{ footerBtn.alpha = 0.01 //Text fades out }) UIView.addKeyframeWithRelativeStartTime(0.50, relativeDuration:0.50, animations:{ footerImg.alpha = 1 //Starting image reappears }) }, completion: { finished in footerBtn.setTitle("", forState: UIControlState.Normal) footerBtn.alpha = 1 })//End of animation }//End of animateFeedback
-20795457 0 Spelling check please!
double hypo**te**nuse(double leg1, double leg2); cout << "The value of hypothesis is: " << hypo**te**nuse(leg1,leg2) << endl; double hypo**the**nuse(double leg1, double leg2) { return ((leg1 * leg1) + (leg2 * leg2)); }
-4564567 0 All of them. The intention of the feature is for something like a TIMESTAMP field, which the user cannot assign directly.
Been stuck on this issue for a while now finally narrowed it down to the fact that AllowSorting is True. When I try to run the excel export With sorting, excel opens up into a blank document without any gridlines. Turned it off and the data appears as expected. I thought that if i turned off the sorting in the excel export button click event, then turn it back on afterwards, this would fix the issue, however this has not seemed to be the case.
I have also tried shifting where I turn off page sorting just to make sure I didn't place it in the wrong spot but still does not seem to change the result of the blank page.
Below is the coding I am using. I did read some talk about using a BindingSource but that also did not seem to work for me.
Am I missing a step or doing something wrong?
Dim tw As New StringWriter() Dim hw As New HtmlTextWriter(tw) Dim frm As HtmlForm = New HtmlForm() Response.ContentType = "application/vnd.ms-excel" Response.AddHeader("content-disposition", "attachment;filename=" & "Facility Detail Report" & ".xls") Response.Charset = "" EnableViewState = False dgCustomers.AllowPaging = False dgCustomers.AllowSorting = False 'Dim BindingSource As New BindingSource 'BindingSource.DataSource = dgCustomers.DataSource() 'dgCustomers.DataSource = BindingSource.DataSource dgCustomers.DataBind() Controls.Add(frm) frm.Controls.Add(dgCustomers) frm.RenderControl(hw) Response.Write(tw.ToString()) Response.End() dgCustomers.AllowPaging = True dgCustomers.AllowSorting = True dgCustomers.DataBind()
-1383672 0 If you declare virtual functions you should also declare your destructor virtual ;-).
B has a virtual table, because it has a virtual function, namely func0(). If you declare a function (including a destructor) virtual in a base class, all its derived classes will have the function with same signature virtual as well. And it will cause them to have a vtable. Moreover, B would have the vtable even if you didn't declare func0 in it explicitly.
Non-virtual functions are not referenced through vtables.
See 2.
No. Classes' vtables are constructed based on class declarations. The bodies of class' functions (let alone other functions) are not taken into account. Therefore, B has a vtable, because its function func0() is virtual.
There also is a tricky detail, although it's not the gist of your question. You declared your function B::func0() as inline. In gcc compiler, if a virtual function is declared inline, it retains its slot in virtual table, the slot pointing to a special function emitted for that inline one (that counts as taking its address, which makes the inline emitted). That means, whether the funciton is inline doesn't influence amount of slots in vtable and its necessity for a class.
Yes, you can use CKEditor, but when I implemented the CKEditor on a form, it turns out it is quite limited in the functionality in provides. Also, the HTML it generates leaves much to be desired. So, I tried a similar idea to Pavel's but using a backing field to store the actual HTML using TinyMCE. You can find the code here:
I have package my solution as a managed and unmanaged CRM solution that can be imported and utilised on any form. Moreover, it works on both CRM 2013 and CRM 2015
-13647385 0You are looking for software that allows you to do bytecode manipulation, there are several frameworks to achieve this, but the two most known currently are:
When performing bytecode modifications at runtime in Java classes keep in mind the following:
If you change a class's bytecode after a class has been loaded by a classloader, you'll have to find a way to reload it's class definition (either through classloading tricks, or using hotswap functionalities)
If you change the classes interface (example add new methods or fields) you will be able only to reach them through reflection.
the module: test-define.rkt
#lang racket (provide test) (provide (contract-out [add-test! (-> void)])) (define test 0) (define (add-test!) (set! test (add1 test))) the main program:act.rkt
#lang racket (require "test-define.rkt") (printf "~a~%" test) (add-test!) (printf "~a~%" test) run the act.rkt, I get:
0 1 this is what I want.
But if I change the contract in test-define.rkt:
(provide test) change to
(provide (contract-out [test integer?])) then I run the act.rkt again, I get:
0 0 Why? I can't change the test value.
If I provide a get func, it turns normal again.
(provide (contract-out [get-test (-> integer?)])) (define (get-test) test) If test's type change to hash map, it's always normal.
What I missed?
-11433366 0 The relative virtual path "WebSite3" is not allowed hereConfiguration rootWebConfig = WebConfigurationManager.OpenWebConfiguration("/WebSite3"); My project name is WebSite3, however when i try running the code, i get the relative virtual path "WebSite3"is not allowed here.
-7970853 0 Does a row take up memory based on the size of its declared columns, even if the fields are null?I'm curious if I declare a column to be, say, varchar(5000) and then start creating rows, but leaving that column with null values, how is memory allocated? Is the DB growing by 5000 bytes for every row? Or does it wait to allocate memory until a value actually is set?
-26341982 0 Connecting hover rules for two separate anchors?The fiddle below displays an image link and a text link for each corresponding page. Each image when hovered over shows the coloured version by using css. The text links simply have a border on the bottom when hovered.
I need to make the image coloured when the corresponding text link is hovered, and also the text link to have its border shown when the corresponding image is hovered? How can I link these functions together?
see this fiddle http://jsfiddle.net/rabelais/sLq28jb4/
#chorus { background: url('../images/work-icons/icon-chorus to size BW.jpg'); height: 85px; left: 30px; position: fixed; top: 78px; width: 113px; display: block; } #chorus:hover { background: url('../images/work-icons/chorus-icon to size.jpg'); border-bottom: none; } #chorus-text-link { left: 180px; position: fixed; top: 111px; }
-39651450 0 How to add dictionary when we long press a word in android webview. I wish to implement dictionary option in android webview text when webview is showing article from any online publication. When we long press on any word, it shows the option for 'search', 'copy' etc. I wish if I can add one option for dictionary there so that user can access dictionary either installed in phone or online one. Also if option for adding specific dictionary within the application will do even better. I tried to search a lot but stuck there and couldnt get an implementation strategy.
-664151 0To answer the question in your title, I would wrap the SocketOutputStream in a BufferedOutputStream in a DataOutputStream and use the latter's writeInt() method repeatedly. Or you could use ObjectOutputStream in place of DataOutputStream, and serialize the array: objOutStream.writeObject(theArray). To read it in again on the other end, just wrap the SocketInputStream in (1) a DataInputStream and use readInt() repeatedly, or (2) a ObjectInputStream and use readObject().
(If you don't have to interoperate with other languages, Object*Stream is easier on you)
Better to cache $('html, 'body') before scrolling and use event delegation.
var $htmlBody = $('html, body'); $htmlBody.on('click', '.services-nav li a', function() { var target = $(this).attr('href') var offsetTop = $(target).offset().top || 0; $htmlBody.animate({scrollTop: offsetTop}, 1500); return false; });
-19317676 0 How to fetch all the variants, of each products, with out fetching product name multiple time I have 3 tables.
"table_products"
product_id product_name 1 A 2 B 3 C 4 D 5 E "table_varients"
variant_id variant_name 1 v1 2 v2 3 v3 4 v4 5 v5 "table_product_varients"
product_id variant_id 1 1 1 2 1 3 2 3 2 4 3 1 3 4 4 1 5 1 5 2 And i want result from select Query like this:
A - V1, V2, V3 B - V3, V4 C - V1, V4 D - V1 E - V1, V2 Devesh
-35155904 0The simplest and pretty much idiomatic way to do it would be:
QMap<QString, QVector<QString>> devices; // Get the vector constructed in the map itself. auto & commands = devices[RadioID]; // Fill commands with lots of data here - a bit faster commands.resize(2); commands[0] = "Foo"; commands[1] = "Bar"; // Fill commands with lots of data here - a bit slower commands.append("Baz"); commands.append("Fan"); You'll see this pattern often in Qt and other code, and it's the simplest way to do it that works equally well on C++98 and C++11 :)
This way you're working on the vector that's already in the map. The vector itself is never copied. The members of the vector are copied, but they are implicitly shared, so copying is literally a pointer copy and an atomic reference count increment.
-738931 0In case anyone ends up running into a similar situation, here was my solution:
First to explain my datasets:
public Foo { string a; List<Bar> subInfo; } public Bar { string b; string c; } List<Foo> allFoos; Basically instead of having the allFoos object that I passed to a master report, and then trying to pass the corresponding Bar object to the subReport, I created a new object:
Public FooBar { string a; string b; string c; } List<FooBar> allFooBars; So basically I flattened the data. From there I created a single report. I added one table that had "FooBar" as it's DataSet, and passed in the collection of "allFooBars." I also created a footer on the report, so that I would have consistent paging across all pages. I then used grouping to keep "Foo" objects together. On the groups I set the "Page Break at start" and "Include Group Header" and "Repeat Group Header" options to true. Then I just set up the Group Headers to fake being my Page Headers along with group headers (basically just 5 lines of Group Headers, one of which was blank to provide some space).
And that was basically it.
-18657018 0Marquee and Blink are not standard, and are no longer supported in newer browsers. Sorry.
-9281971 0The issue is in the fact that by default images are vertically aligned with the baseline. You can see this if you put an image next to some text. The image aligns to the baseline of the text, while letters like g and y go below the baseline. The space you are getting is the space below the baseline which is for the letters to go below. If you change the vertical-align to top the space will disappear.
.artwork img { height: 100%; vertical-align: top; }
-13177767 0 I think even with --ignore-unmatch you still need the -- disambiguator. Like:
git rm --cached --ignore-unmatch -- Rakefile ^^-this two dashes here
-1685340 0 Even if you won't be uploading it, build your application like a CPAN module.
That basically means you have a Makefile.PL that describes the dependencies formally, and your application is in the script/ directory as myapplication (assuming it's a command line/desktop app).
Then, someone can use the CPAN client to install your module and it's dependencies directly, but untarring the tarball and then running
cpan .
Alternatively, the pip tool will let people install your application from a remote URL directly.
-19978197 0 Gcdasynsocket did read data delegate dosent give correct tag value
I am using gcdasynsocket to establish socket communication. Below shown is the method that i am using to write the data
-(void)writeData:(NSData*)data withTag:(int)tag { [asyncSocket writeData:data withTimeout:-1.0 tag:tag]; [asyncSocket readDataWithTimeout:-1.0 tag:tag]; } - (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag { if (tag == 18) { NSLog(@"First request sent"); [asyncSocket readDataWithTimeout:-1.0 tag:18]; } else if (tag == 125) { NSLog(@"Second request sent"); [asyncSocket readDataWithTimeout:-1.0 tag:125]; } } //reading the data
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag { NSLog(@"tag---%ld",tag); } In my did read data delegate i am not getting the tag value what i have passed. Since i am not getting the correct tag value. i couldnt read my another data. I am not sure what is going wrong here. Please help me to fix this issue
-12746471 0I believe this does what you want:
SlopeInterceptDemonstration[{mmin_, mmax_}, {bmin_, bmax_}] := Manipulate[ Plot[m*x + b, {x, xmin, xmax}, AspectRatio -> 1, PlotRange -> {xmin, xmax}], {{m, mmin, "m"}, mmin, mmax, 0.1}, {{b, bmin, "b"}, bmin, bmax, 0.1}, {xmax, None}, {xmin, None}, Initialization :> {xmax = Max[Abs[bmin + mmin], Abs[bmax + mmax]]*1.2, xmin = -xmax} ] {xmax, None} is used to localize xmax in the Module. The method with DynamicModule shown in the other answer is standard and more flexible.
gpg -c ... -u [signing user id or key hex id] ...
-32196880 1 Copying a list of lists into part of another one in the most pythonic wayI have a large list of lists, for now containing only zeros. I have another, smaller list of lists which I want to copy to certain positions in the bigger list of lists. I want to replace the original values. The only way I've found so far is this:
start = (startrow, startcol) for i in range( start[0], start[0] + len(shortlist) ): for j in range( start[1], start[1] + len(shortlist[0]) ): longlist[i][j] = shortlist[i-start[0]][j-start[1]] However, this doesn't feel very pythonic - as far as I know, list comprehensions are in general prefered to loops, and even though I didn't find it in few hours of searching, there might be some function doing this more elegantly. So is there some better solution than mine?
EDIT: I'm interested in NumPy solutions as well, or perhaps even more than in plain Python ones.
-18523387 0No you won't able to see the console of the iOS simulator.
You must build it for iOS device and use xcode to see the Corona SDK print.
-17967296 0You haven't specified the IE version you're testing with, but your code appears to work fine in IE9 and higher, so I'm going to assume you're testing in IE8.
Given that, there are is one main problem I can see that will be breaking your site:
<nav> and other new HTML5 elements are not supported as standard by IE8 or earlier. Using them will break your layout and cause other glitches.
You have two options: Either replace the <nav> and any other HTML5 elements with old-style <div> elements, or use a polyfill like html5shiv or Modernizr, both of which will fix the problem in IE8 and make these elements work as normal.
Hope that helps.
[EDIT after OP clarified his IE version as IE10]
The other possibility is that it's displaying the page in compatibility mode or quirks mode.
You can check the browser mode by pressing F12 to bring up the Dev Tools window; the mode information will be shown at the top of the window. If it's in either Quirks mode or compatibility mode (ie if it's in anything other than IE10 Standards mode) then there's a strong probability that this is the cause.
If it's in quirks mode, it's because your HTML isn't standards compliant. Most of the time, adding a valid doctype to the top of the page will fix this (you can use <!DOCTYPE html> as the easiest valid doctype). You should also check for other errors in your HTML by running it through the W3C Validator and fixing the errors it reports. (if the code you've posted is your whole code, then you're missing the <html> and <body> tags for starters, which is definitely not good).
If it's in compatibility mode (eg "IE7 Standards"), then you can fix this by adding an X-UA-Compatible meta tag to your <head> section. (see my answer here for more info on why this might be happening and what to do to fix it).
This is the first thing I'd try:

Wait until it doesn't say "Getting" anywhere anymore before doing anything documentation related.
-30330734 0When you load in a File in the open JButton ActionListener, the code creates a new TableModel and sets the JTable model:
MyModel NewModel = new MyModel(); table.setModel(NewModel); The NewModel instance is local to this method, thus any changes to the instance variable model will not be reflected in the JTable (in other words, model != table.getModel()). Instead of creating a local variable, set the instance variable to the new model. For example:
model = new MyModel();//sets the instance variable to the new model table.setModel(NewModel); In this way, whenever code refers to model, it is acting on the current TableModel of the JTable. Alternatively, when making changes to the TableModel, you can get the model directly from the JTable, casting if necessary:
remove.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int row = table.getSelectedRow(); MyModel myModel = (MyModel)table.getModel();//get the model directly if (row!=-1) myModel .deleteRow(row); } });
-9958894 0 Use an array:
String files[] = new String[]{"Hello", "Hola", "Bonjour"}; for (String file : files) { System.out.println(file); }
-39573916 0 $(function() { var xingHref = $(".contact-sm > a").attr("href"); $(".contact-img > a").attr("href", xingHref); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="contact-img"> <a href="https://test.de" class="evcms-open-contacts"> <img src="https://cdn-cache.envivo-connect.com/license/Tw3sZjz8v/p/xckYV8bESwsZ/80x80c/xckYV8bESwsZ.png?v=2.4.84-z3p37YEER-1467970717-yZUA33Hxn" alt="F. Alexander Kep" /> </a> </div> <div class="contact-sm"> <a href="https://www.xing.com/profile/FfAlexander" /> </div> I'm making a calculator program, and I got everything setup and it was working earlier, but after I added a method, when I run in debug mode, Eclipse says I have an error in my main method. I don't know why it won't run.
The error I get: Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at com.molotuff.main.Calculator.main(Calculator.java:13) Here is my code:
package com.molotuff.main; import java.util.ArrayList; import java.util.Scanner; public class Calculator { private static Scanner reader = new Scanner(System.in); private static boolean running = true; private static boolean calcRunning = true; private static String command; private static ArrayList<Integer> nums = new ArrayList<Integer>(); public static void main(String[] args) { System.out.println("*****************************"); System.out.println("* Welcome to The Calculator *"); System.out.println("*****************************"); menu("help"); while(running) { System.out.println("Enter a command:"); command = reader.nextLine(); menu(command); if(command.equalsIgnoreCase("quit")) { running = false; } if(command.equalsIgnoreCase("add")) { getNums(); int answer = Calculations.sum(nums); System.out.println("The sum is: " + answer); } } } public static void menu(String command) { if(command.equalsIgnoreCase("help")) { System.out.println("Commands: "); System.out.println("Quit"); System.out.println("Help"); System.out.println("Add"); System.out.println("Subtract"); System.out.println("Divide"); System.out.println("Multiply"); System.out.println("Type help [command] for more info on that command"); } if(command.equalsIgnoreCase("help quit")) { System.out.println("Quit: quits the program."); } if(command.equalsIgnoreCase("help help")) { System.out.println("Help: prints the help menu."); } if(command.equalsIgnoreCase("help add")) { System.out.println("Add: takes numbers inputed and adds them together."); } if(command.equalsIgnoreCase("help Subtract")) { System.out.println("Subtract: takes a set of numbers and subtracts them \n (note: " + "subtracts in this order [first num entered] - [second num entered] " + "etc.)"); } if(command.equalsIgnoreCase("help multiply")) { System.out.println("Add: takes numbers inputed and multiplies them together."); } if(command.equalsIgnoreCase("help divide")) { System.out.println("Subtract: takes a set of numbers and divides them \n (note: " + "divides in this order [first num entered] / [second num entered] " + "etc.)"); } } } public static void getNums() { while(calcRunning) { String userInput = reader.nextLine(); int userNums; if(userInput.isEmpty()) { calcRunning = false; } else { userNums = Integer.parseInt(userInput); nums.add(userNums); } } } }
-30503870 0 What if you click on the arrow icon (near minimize/maximize), on the bar view and deselect Show Tests in Hierarchy ? Or play with different layout under Layout (same icon)
import java.util.Scanner; public class ThreadClass{ public static void main(String[] args) { System.out.println("Enter the characters, Press Enter to begin"); System.out.println("The quick brown fox jumps over the lazy dog"); Scanner sc=new Scanner(System.in); String scr= sc.nextLine(); MyThread tr=new MyThread(); try { tr.sleep(11000); System.out.println("Time Over"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public class MyThread extends Thread{ public void run() { System.out.println("Time over"); ThreadClass tc=new ThreadClass(); String str=tc.scr; if(str.equals("The quick brown fox jumps over the lazy dog")) { System.out.println("Successfully completed"); } else { System.out.println("The typed Words do not match"); } } } I am trying to make an application that prompts the user to type a string within 11 seconds. To accomplish this I have two classes namely ThreadClass and MyThread. In Thread class I have defined methods to take input from the user and to set the timer to 10 seconds. In MyThread class I have defined methods for post thread completion i.e. what the program will do after the time is over. I want to add a feature in MyThread class so that it compares the user input with the string provided. The problem is that when I try to access the String variable scr, defined in ThreadClass from MyThread class by creating an it gives me an error. Even if I try to extend ThreadClass from MyThread class it gives me an error. Also declaring scr as static gives me the same result. Is there any possible way to use scr variable in MyThread?
-19254220 0 RestEasy GET method accepts HEAD requestsI have the merhod annotated with @GET. But when here comes HEAD request, it is handled with this method. And in the body of the method I get request type HEAD from HttpRequest object. Why does GET method responces for HEAD requesrs?
-40597128 0You should really be storing those names on an object stored in a global and not as global variables. But you asked how to do it and so here is how:
Using Getting corresponding module from function with a for loop and setattr as modules do not support dictionary operations and it is possible to write the function as:
import sys def load_inmemory(): module = sys.modules[load_inmemory.__module__] for k, v in load237(fpath)[0].items(): setattr(module, k, v) load_inmemory() print x I tested the following:
import sys def func(): module = sys.modules[func.__module__] for k,v in {'x':4}.items(): setattr(module, k, v) func() print x Prints 4. Tested in Python 2.7.3.
I would like show navigation arrow when items not visible in the component TableView at the screen. I don't know if there is an event when, visually, the TableView is full, and show arrow to scroll in the TableView.
Thanks.
-37868817 1 Retrieve Django ManyToMany results outside of the current modelHi I'm brand new to Django.
Here are my models (simplified):
class Store(models.Model): company = models.CharField(max_length=256) brands = models.ManyToManyField('Brand',related_name='brand') class Brand(models.Model): company = models.CharField(max_length=256) Here is my view for the template:
def brand_detail_slug(request, slug): brand = Brand.objects.get(slug=slug) return render(request, 'storefinder/brand_detail.html', {'brand': brand}) I can retrieve info for the brands successfully in my view:
{% for p in brand.product_types.all %} <li>{{ p }}</li> {% endfor %} But I don't know how to do this for stores, since it's not really defined in the Brands. It's a separate model.... this is where I get confused.
Thanks!
-19475643 0 Prolog Time Overlap WoesSay I have this Knowledge Base:
free(ann,slot(time(8,0),time(9,0))). free(ann,slot(time(10,0),time(11,0))). free(bob,slot(time(7,0),time(8,30))). free(bob,slot(time(10,0),time(11,0))). free(carla,slot(time(8,0),time(9,0))). free(carla,slot(time(10,0),time(10,15))). So, after a lot of effort, I managed to write something that prints the first person who has availability during a specific slot with the following code:
meetone(Person, slot(time(BeginHour, BeginMinute), time(EndHour, EndMinute))) :- free(Person, slot(time(BH, BM), time(EH, EM))), BH*60 + BM =< EndHour*60 + EndMinute, EH*60 + EM >= BeginHour*60 + BeginMinute. main :- (meetone(Person,slot(time(7,15),time(7,20))); halt), write(Person), nl, halt. :- initialization(main). This prints bob, the expected result.
Here's where it gets complicated (at least for me). Let's say I want to find out all the time slots everyone in the Knowledge Base has in common. The following code demonstrates how I ultimately want to call this:
people([ann,bob,carla]). meet :- ??? main :- (setof(Slot,meet(Slot),Slots); halt), write(Slots), nl, halt. :- initialization(main). Here's some vague pseudocode that I think might accomplish what I'm looking for, but I'm not experienced enough to get it working.
The final output would show slots of 8:00 - 8:30 and 10:00 - 10:15. Any help in accomplishing this would be greatly appreciated.
-1319998 0I would think that the proper answer to this, given that you don't want the hardware load measure (CPU, memory, IO utilization), is that heavy load is the amount of requests per time unit at or over the required maximum amount of requests per time unit.
The required maximum amount of requests is what has been defined with the customer or with whomever is in charge of the overall architecture.
Say X is that required maximum load for the application. I think something like this would approximate the answer:
0 < Light Load < X/2 < Regular Load < 2X/3 < High Load < X <= Heavy Load
The thing with a single number out of thin air is that it has no relation whatsoever with your application. And what heavy load is is totally, absolutely, ineludibly tied to what the application is supposed to do.
Although 200 requests per second is a load that would keep small webservers busy (~12000 a minute).
-32492439 0try this (Pure JS Solution)
<p> Date: <input type="date" name="currentDate" id="currentDate" /> </p> <script> var today = new Date(); var dd = today.getDate(); var mm = today.getMonth() + 1; //January is 0! var yyyy = today.getFullYear(); if (dd < 10) { dd = '0' + dd } if (mm < 10) { mm = '0' + mm } var today = dd + '/' + mm + '/' + yyyy; document.getElementById('currentDate').value = today; </script> Well some basic hints :
A lot more to be said. But try to do simple things first :) Then you can begin to read advanced article about loop unrolling and the rest.
EDIT:
As said in some comments, your compiler should optimize out some or all things I have pointed out. One can even argues that doing too many specific optimizations can be counter produtive as it might impair the compiler optimization capabilities.
So one basic advice : - mesure the perfs of your initial algorithm - do one possible optimization - mesure the gain
This way you will learn a lot about your compiler automatic optimization :)
EDIT 2:
As said in comments, my ubuntu 64bit with 4Gbytes RAM refuse to allocate the vector :) With a more reasonable billion limit, time give about 14 seconds. removing cout just gain about a second.
As andreas said, the problem is the storage of the result. you have to store the inner loop result on disk !
my 2 cents
-13449446 0Enum compareTo seems to be final and cant be overriden Why is compareTo on an Enum final in Java?
Just do Collections.sort() which will order the list in enum order as you need
-5481452 0You are already inside a code block; Razor does not parse within code blocks for other code blocks. The style part of the line should look something like this:
style = "width: 20px; background-color: " + Model.BackgroundColor + ";"
-5831887 0 There are no APIs for "decoding" video in the Android SDK, other than to play it back (e.g., MediaPlayer). You are welcome to try to find some third-party library that offers you whatever functionality it is that you seek.
but learning a language that helps my resume is still a benefit.
You should try using VB6 or COBOL, then, as there is a lot of billing work out there for it.
-21062436 0The below mentioned link solution helps:
https://github.com/evrone/quiet_assets
Also as below it's working fine for me
3.1 (only) (3.2 breaks before_dipatch)
app\config\initializers\quiet_assets.rb Rails.application.assets.logger = Logger.new('/dev/null') Rails::Rack::Logger.class_eval do def before_dispatch_with_quiet_assets(env) before_dispatch_without_quiet_assets(env) unless env['PATH_INFO'].index("/assets/") == 0 end alias_method_chain :before_dispatch, :quiet_assets end 3.2 Rails - Rack root tap approach app\config\initializers\quiet_assets.rb Rails.application.assets.logger = Logger.new('/dev/null') Rails::Rack::Logger.class_eval do def call_with_quiet_assets(env) previous_level = Rails.logger.level Rails.logger.level = Logger::ERROR if env['PATH_INFO'].index("/assets/") == 0 call_without_quiet_assets(env).tap do Rails.logger.level = previous_level end end alias_method_chain :call, :quiet_assets end
-38138883 0 Try this:
Picasso .with(context) .load(message.getMediaUrl()) .fit() // call .centerInside() or .centerCrop() to avoid a stretched image .into(messageImage);
-30333390 0 IMO it seems like the ::create array is confusing the basics. Also, I'm not clear what you are doing with $result and $marks - I am assuming they are columns on your Qualification table.
I recommend doing something like this:
$r = $input::get('result'); if($r){ $q = new Qualification; $q->level_of_education = Input::get('level_education'); // do the same thing with the rest of your fields if($r == 1) { $q->result = 'First'; $q->marks = Input::get('marks'); } // rest of your elseif statements would follow $q->save(); } This site has a great CRUD tutorial (this is addressed about 1/2 way through): https://scotch.io/tutorials/simple-laravel-crud-with-resource-controllers
Good luck
-16209348 0it means 2*10^4
and try it in your console 2e4 the output will be 20000
the e is the scientific notation
the code is equivilant to
... e.animate({along: 1}, 20000, function () { ....
-26009265 0 How to do a validation to find duplicate entries ? knockout I have a scenario when i dynamically add multiple rows using template way i need to write down a validation if CountryCode (which should be unique) having same value in two or more dynamically generated rows .
working fiddle : http://jsfiddle.net/JL26Z/73/
Well i am thinking can this be possible using custom validation code but i am not sure how to proceed i mean how to compare in validator function inside validation .
And the same can be done on click of submit in save function like we run a foreach each aganist every row code and do it but is it a good practice .
My view model:
function Phone() { var self = this; self.Code = ko.observable(""); // this should be unique self.Date = ko.observable(""); self.PhoneNumber = ko.observable(""); self.Validation = ko.validatedObservable([ self.Code.extend({ required: true }), self.Date.extend({ required: true }), self.PhoneNumber.extend({ required: true }) ]); } function PhoneViewModel() { var self = this; self.PhoneList = ko.observableArray([new Phone()]); self.remove = function () { self.PhoneList.remove(this); }; self.add = function () { self.PhoneList.push(new Phone()); // i add on click of add button }; } ko.applyBindings(new PhoneViewModel()); Any suggestions are appreciated .
-34557091 1 ImportError: cannot import name RemovedInDjango19WarningI'm on Django 1.8.7 and I've just installed Django-Allauth by cloning the repo and running pip install in the app's directory in my webapp on the terminal. Now when I run manage.py migrate, I get this error:
➜src git:(master) ✗ python manage.py migrate Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 10, in <module> from django.apps import apps File "/Library/Python/2.7/site-packages/django/apps/__init__.py", line 1, in <module> from .config import AppConfig File "/Library/Python/2.7/site-packages/django/apps/config.py", line 6, in <module> from django.utils.module_loading import module_has_submodule File "/Library/Python/2.7/site-packages/django/utils/module_loading.py", line 4, in <module> from importlib import import_module File "/Library/Python/2.7/site-packages/django/utils/importlib.py", line 6, in <module> from django.utils.deprecation import RemovedInDjango19Warning ImportError: cannot import name RemovedInDjango19Warning ➜ src git:(master) ✗ I've checked and I'm still on django 1.8.7 so it wasn't accidently upgraded.
-20691705 0If you use the filterable widget on a table, the widget will filter table rows, so to make it work with any kind of table cell content (text, input) you should use the **data-filtertext**-attribute and set the text to be queried on the table row like so:
<tr data-filtertext="foo_from_cell_1, bar_from_cell_2, baz_from_cell_3..."> <td>foo</td> <td><div><p><span>bar</span></p></div></td> <td><input type="text" value="baz"/></td> </tr> This way it will work.
Also check the example provided in the JQM demos
-9279278 0It looks like you need to add script by calling ScriptManager.RegisterStartupScript method to show elements on page:
ScriptManager.RegisterStartupScript(this, this.GetType(), this.ID, "$('#back_drop, #login_container').css('display', 'block');", true);
-5791568 0 A recursive solution:
public void addToEnd(Object data){ if (next==null) next = new Node(data, null); else next.addToEnd(data); }
-36719299 0 CSS icon using :before keep text from wrapping under I have an icon placed using :before and the text following it sometimes wraps to two or three lines. When it wraps the text goes under the icon.
I am looking for CSS help to keep the text from wrapping under the icon.
Here is an image showing what I am referring to:

Current CSS:
a[href $='.pdf']:before, a[href $='.PDF']:before, a[href $='.pdf#']:before, a[href $='.PDF#']:before, a[href $='.pdf?']:before, a[href $='.PDF?']:before { content: "\f1c1"; font-family: 'FontAwesome'; color: #999; display: inline-block; margin: 0px 10px 0 0; font-size: 24px; vertical-align: middle; } .form-title:before { float: left; } Here is a fiddle with my code: fiddle
-23120626 0 Word VBA: How to reference a chart in a tableIn a Word document, I have several tables into which I have placed charts within cells. Now I need to access these charts through VBA, to update data values and other properties. The logic driving the updates to the charts is linked to the table the charts are embedded in, so I need to know something about the table context when accessing the charts.
Originally, I had planned to bookmark the tables, and then iterate through the charts associated with each table. However, I now realise that the Word "Table" object doesn't have a "Shapes", or "Inlineshapes", or "Charts" collection.
So my question is: what is the best way to access/reference charts embedded in a table?
-32042151 0 mapPartitions returns empty arrayI have the following RDD which has 4 partitions:-
val rdd=sc.parallelize(1 to 20,4) Now I try to call mapPartitions on this:-
scala> rdd.mapPartitions(x=> { println(x.size); x }).collect 5 5 5 5 res98: Array[Int] = Array() Why does it return empty array? The anonymoys function is simply returning the same iterator it received, then how is it returning empty array? The interesting part is that if I remove println statement, it indeed returns non empty array:-
scala> rdd.mapPartitions(x=> { x }).collect res101: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20) This I don't understand. How come the presence of println (which is simply printing size of iterator) affecting the final outcome of the function?
-21441777 0 JS. How to get list of div's with similar class name?I have html, like this:
<div id="c0" class="bz_comment bz_first_comment"></div> <div id="c1" class="bz_comment"></div> <div id="c2" class="bz_comment"></div> <div class="bz_add_comment"></div> How can I get array of all the div's (3 div in example) by class that's starts with "bz_comment[anysymbols]" in JavaScript (not using JQuery)?
Or can i get array of div's by id that's starts with "c[numeric_value]"?
[numeric_value_can_consist_of_some_numbers] It's the similar question like stackoverflow.com/questions/1225611/ (but i don't have reputation to ask in that question). Thanks in advance.
-681266 0You can use template arguments to program against 'general' enum types. Much like this:
// enum.h struct MyClass1 { enum e { cE1, cE2, cELast }; }; // algo.h // precondition: tEnum contains enumerate type e template< typename tEnum > typename tEnum::e get_second() { return static_cast<typename tEnum::e>(1); } // myclass1.h // myclass.h template< typename tClass1 > class MyClass2 { tClass1 * ptr; void func( tClass1::e e ); }; // main.cpp #include "enum.h" #include "algo.h" int main(){ return get_second<Enum>(); }
-8674210 0 One thing you can do is to use the interface (i.e. the header files) and provide an implementation of your own, at least for those functions you care about. To switch between both versions essentially amounts to linking with different libraries: yours for testing, theirs for the real implementation.
There are a few issues with that which can be addressed e.g. by only retaining the public interface and changing the private interface (on this case compilation needs to be directed at the different declarations, e.g. using different search pathes for the headers):
[root@study ~]# rpm -qa | wc -l 777 [root@study ~]# yum list installed | wc -l 1054 i want to know why different,shoud i get correct number of installed packages?
-12854294 0Yes, it is possible. If there was problem with HttpPostAttribute, you would not have been able to get inside LogOn method. You should re-check that fields are sent from client and those fields are put inside request body, not query string. You could check it with chrome for example, by inspecting network traffic or simply by debugging HttpContext.Current.Request.Form property
Here's Clojure's doc:
clojure.core/time ([expr]) Macro Evaluates expr and prints the time it took. Returns the value of expr. Is there some (semi-) standard way to do this in Emacs lisp?
-12989084 0change this
message[i].getFrom() to
message[i].getFrom()[0].toString())
-14356547 0 localStorage doesn't refresh the grid I can't solve this problem.
Here is my code
var selectedID = ""; var selectedIDPremise = ""; var PremisesGrid = ""; var PremisesGrid2 = ""; var selectedIDPremise2 = ""; //var selectedOD2 = ""; var nova = ""; $(document).ready(function () { $("#routes").kendoDropDownList({ dataTextField: "Name", dataValueField: "Id", dataSource: { type: "application/jsonp", transport: { read: { url: "http://" + servername + "/uBillingServices/Administration/Administration.svc/getRoute", dataType: "json", data: { ID: 0 } } } }, select: onSelect }); //nova = PremisesGrid2.getKendoDropDownList().dataSource.transport.options.read.data.Route_ID; function onSelect(e) { //$.getJSON("http://" + servername + "/uBillingServices/Administration/Administration.svc/getRoute", { ID: nova }, function (json) { }); window.localStorage.setItem("Nova", ""); nova = this.dataItem(e.item.index()); window.localStorage.setItem("Nova", nova.ID); PremisesGrid2.getKendoGrid().dataSource.read(); //nova = PremisesGrid2.getKendoDropDownList().dataSource.transport.options.read.data.Route_ID; // var data = [{}]; //PremisesGrid2.getKendoGrid().dataSource.data(data) for (var i = 0; i < 3000; i++) { if (i == 2999) { PremisesGrid2.getKendoGrid().dataSource.read(); } } } PremisesGrid2 = $("#assignedRoute").kendoGrid({ //dataTextField: "Name", //dataValueField: "Id", dataSource: { type: "application/jsonp", transport: { read: { url: "http://" + servername + "/uBillingServices/Premise/Premise.svc/GetAllPremisesByRoute", dataType: "json", data: { Route_ID: window.localStorage.getItem("Nova"), UserName: userName, WorkStation: workStation } } }, schema: { model: { fields: { ID: { type: "string" }, PostalCode: { type: "string" }, Latitude: { type: "string" }, Longitude: { type: "string" }, IsMember: { type: "string" } } } } }, change: function (arg) { myIndex = this.select().index(); var PremisesRow = this.select(); }, dataBound: function (e) { row = e.sender.tbody.find(">tr:not(.k-grouping-row)").eq(0); if (row.length == 0) { e.sender.select(e.sender.tbody.find(">tr:first")); } else { e.sender.select(row); } }, selectable: true, scrollable: true, filterable: true, groupable: false, sortable: { mode: "single", allowUnsort: false }, height: 330, columns: [ { field: "PostalCode", title: "Assigned Route" } ]//, width: "100px" }); the localStorage is working fine(in resources it changes), but it doesn't refresh the grid when I select another Reon (form the DropDown list),and when I refresh the page it shows the last one I selected
Can anyone tell me what is the problem? Thanks
-2536376 0Selectors are ONE way to go... the alternative is to create a protocol and to require invokers of your API to provide a "delegate" object that implements the protocol. Then you can invoke the required selectors of that protocol on the delegate object that you have been given. Each has its advantages and disadvantages.
Example using selectors: NSThread:detachNewThreadSelector:toTarget:withObject
Example using delegates:NSXMLParser:setDelegate + NSXMLParser:parse
-162192 0 Visual Studio 2008 - Add ReferenceWhen adding a DLL as a reference to an ASP.Net project, VS2008 adds several files to the bin directory. If the DLL is called foo.dll, VS2008 adds foo.dll.refresh, foo.pdb and foo.xml. I know what foo.dll is :-), why does VS2008 add the other three files? What do those three files do? Can I delete them? Do they need to be added in source control?
-37988054 0One solution is to create a version of your network that is truncated at the LSTM layer of which you want to monitor the gate values, and then replace the original layer with a custom layer in which the stepfunction is modified to return not only the hidden layer values, but also the gate values.
For instance, say you want to access the access the gate values of a GRU. Create a custom layer GRU2 that inherits everything from the GRU class, but adapt the step function such that it returns a concatenation of the states you want to monitor, and then takes only the part containing the previous hidden layer activations when computing the next activations. I.e:
def step(self, x, states): # get prev hidden layer from input that is concatenation of # prev hidden layer + reset gate + update gate x = x[:self.output_dim, :] ############################################### # This is the original code from the GRU layer # h_tm1 = states[0] # previous memory B_U = states[1] # dropout matrices for recurrent units B_W = states[2] if self.consume_less == 'gpu': matrix_x = K.dot(x * B_W[0], self.W) + self.b matrix_inner = K.dot(h_tm1 * B_U[0], self.U[:, :2 * self.output_dim]) x_z = matrix_x[:, :self.output_dim] x_r = matrix_x[:, self.output_dim: 2 * self.output_dim] inner_z = matrix_inner[:, :self.output_dim] inner_r = matrix_inner[:, self.output_dim: 2 * self.output_dim] z = self.inner_activation(x_z + inner_z) r = self.inner_activation(x_r + inner_r) x_h = matrix_x[:, 2 * self.output_dim:] inner_h = K.dot(r * h_tm1 * B_U[0], self.U[:, 2 * self.output_dim:]) hh = self.activation(x_h + inner_h) else: if self.consume_less == 'cpu': x_z = x[:, :self.output_dim] x_r = x[:, self.output_dim: 2 * self.output_dim] x_h = x[:, 2 * self.output_dim:] elif self.consume_less == 'mem': x_z = K.dot(x * B_W[0], self.W_z) + self.b_z x_r = K.dot(x * B_W[1], self.W_r) + self.b_r x_h = K.dot(x * B_W[2], self.W_h) + self.b_h else: raise Exception('Unknown `consume_less` mode.') z = self.inner_activation(x_z + K.dot(h_tm1 * B_U[0], self.U_z)) r = self.inner_activation(x_r + K.dot(h_tm1 * B_U[1], self.U_r)) hh = self.activation(x_h + K.dot(r * h_tm1 * B_U[2], self.U_h)) h = z * h_tm1 + (1 - z) * hh # # End of original code ########################################################### # concatenate states you want to monitor, in this case the # hidden layer activations and gates z and r all = K.concatenate([h, z, r]) # return everything return all, [h] (Note that the only lines I added are at the beginning and end of the function).
If you then run your network with GRU2 as last layer instead of GRU (with return_sequences = True for the GRU2 layer), you can just call predict on your network, this will give you all hidden layer and gate values.
The same thing should work for LSTM, although you might have to puzzle a bit to figure out how to store all the outputs you want in one vector and retrieve them again afterwards.
Hope that helps!
-1320687 0The <legend> element can contain any inline element, so you can apply virtually whatever formatting you'd like.
The cause for this error is most likely a missing syntax token that bash expects but the string you pass ends before bash encountered it. Look for ifs, fors etc. that have no closing fi or done.
-7789486 0While the Windows Media Player Com might not officially support a feature like this, its quite easy to 'fake' this. If you use a CtlControls2, you have access to the built-in "step(1)" function, which proceeds exactly one frame.
I've discovered that if you call step(1) after calling pause(), searching on the trackbar will also update the video.
It's not pretty, but it works!
-20186846 0Make your HTML like this:
<input type="text" name="mytextbox" id="mytextbox" onKeyUp="countChar(this)" size="1" maxlength="1" value="" /> And JS will be this:
function countChar(that) { var xy = that.value; var len = xy.length; if (len >= 2) { that.value = that.value.substring(0, 1); } else { that.value=(1 - len); } }
-2086081 0 I think it's because of the circular reference between InventoryUser and ProductUserPK.
Either InventoryUser.pk or ProductUserPK.user should be lazy.
-25330954 0 Div not expanding to fill the windowI've been trying to find a solution to this for days, but haven't found anything that works. I thought I'd finally make an account on this great website, so here goes:
I am trying to have a div expand from left to right, with 170px of clearance on both sides. However, when there is no content on the page, or only a few words, the div doesn't expand. I've tried to add width: 100% in several different divs to try and have them take up the full space, but that either does nothing, or completely busts the page layout. for example, instead of filling out the page, the div that's supposed to hold the content moves off the right side of the screen, and also doesn't leave the 170px margin.
I hope you can be of help, my code is posted below: Thanks in advance, Chris
the html:
<html> <body> <div id="wrapper"> <div id="pagetopwrap"> </div> <div id="pagemainliquid"> <div id="pagemainwrap"> <div id="content"> <div id="headerwrap"> <div id="header_left"> </div> <div id="header_main"> <div id="logo_row"> <p id="logotext">Site Title</p> </div> <div id="menu_row"> <!-- irrelevant menu button code --> </div> </div> <div id="header_right"> </div> </div> <div id="contentbody"> <div id="contenttext"> <p id="contenttextmakeup">Lorum Ipsum Dolor Sit Amet</p> </div> </div> </div> </div> </div> <div id="leftcolumnwrap"> <div id="leftcolumn"> </div> </div> <div id="rightcolumnwrap"> <div id="rightcolumn"> </div> </div> <div id="footerwrap"> <div id="footer"> </div> </div> </div> </body> </html> the css: It is not ordered too well, the uninteresting sides, top and footer are first, and the main part of the website at the bottom
body { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 13px; background-color: #0f0f0f; /* is normally an image */ } #wrapper { width: 100%; min-width: 960px; max-width: 1920px; margin: 0 auto; height: 100% } #pagetopwrap { height: 50px; width: 100%; float: left; margin: 0 auto; } #pagemainliquid { float: left; } #pagemainwrap { margin-left: 170px; margin-right: 170px; float: left; } #leftcolumnwrap { width: 170px; margin-left:-100%; float: left; } #leftcolumn { margin: 5px; } #rightcolumnwrap { width: 170px; margin-left: -150px; float: left; } #rightcolumn { margin: 5px; } #footerwrap { width: 100%; float: left; margin: 0 auto; clear: both; bottom:50px; } #footer { height: 0px; margin: 5px; } #headerwrap { width: 100%; margin: 0 auto; } #header_left { background-color: #ff0000; /* is normally an image */ width:25px; height:200px; float:left; } #header_right { background-color: #ff0000; /* is normally an image */ width:25px; height:200px; margin-left: 0px; float:right; position:relative; top:-200px; } #header_main { background-color: #00ff00; /* is normally an image */ margin-left: 25px; margin-right: 25px; height:200px; background-size: 100% 200px; } #contentbody { background-color: #E2E2E2; border-radius: 10px; margin-top:10px; border: 1px solid #A7A7B2; } #contenttext { margin-left:10px; margin-right:10px; } #logo_row { height:150px; width:100%; float:left; } #logotext { margin-top:20px; margin-left:10px; vertical-align: middle; font-size: 55px; font-family: "Arial Black", Arial; } #contenttextmakeup { margin-top:12px; margin-left:10px; vertical-align: middle; } #menu_row { width:100%; } button.menubutton { /* irrelevant button markup */ } http://jsfiddle.net/w9qLh6tp/ if that helps, I've seen it a lot around here :)
-20657924 0When you are storing code in MySQL wrap the input in the addslashes() PHP function. Then when you retrieve code from MySQL you need to wrap the output in stripslashes().
See: http://www.php.net/stripslashes http://li1.php.net/addslashes
Hopefully this is what you were looking for.
-11463190 0Be careful about trusting the console, there is often asynchronous behavior that can trip you up.
You're expecting console.log(x) to behave like this:
console.log(x).x is dumped to the console.console.log(x) call.But that's not what happens, the reality is more like this:
console.log(x).x, and queues up the "real" console.log call for later.console.log call from (2) gets around to dumping the current state of x into the console but this x won't necessarily match the x as it was in (2).In your case, you're doing this:
console.log(this.attributes); console.log(this.attributes.widgets); So you have something like this at (2):
attributes.widgets ^ ^ | | console.log -+ | console.log -----------+ and then something is happening in (3) which effectively does this.attributes.widgets = [...] (i.e. changes the attributes.widget reference) and so, when (4) comes around, you have this:
attributes.widgets // the new one from (3) ^ | console.log -+ console.log -----------> widgets // the original from (1) This leaves you seeing two different versions of widgets: the new one which received something in (3) and the original which is empty.
When you do this:
console.log(_(this.attributes).clone()); console.log(_(this.attributes.widgets).clone()); you're grabbing copies of this.attributes and this.attributes.widgets that are attached to the console.log calls so (3) won't interfere with your references and you see sensible results in the console.
That's the answer to this:
It's showing that widgets is not empty when logging
this.attributesbut it's shown as empty when loggingthis.attributes.widgets. Does anyone know what would cause this?
As far as the underlying problem goes, you probably have a fetch call somewhere and you're not taking its asynchronous behavior into account. The solution is probably to bind to an "add" or "reset" event.
I'm using webbrowser control embeded in a winform in my C# app to do some scraping. The content I'm looking for is dynamically loaded with ajax. However, when I navigate to the page the content won't load unless I have no other code running. I tried doing
while(webbrowser1.isBusy); But that's not helping. I also tried pausing the program for a few second to give it time to load
Thread.Sleep(2000); but it's still not loading. If I navigate to the page with no code following, it loads fine. I'm not really sure how I could split this into threads. Any help would be appreciated.
-24549960 0 How to loop through Two arrays in TWO FOR Each loopThere are two FOR EACH loops in the code below. The first FOR loop cycles through the first array (shape 1,shape 2 ,shape 3).The second FOR loop cycles through the second array (0.3, 0.4, 0.5).
Shape 1 0.3
Shape 2 0.4
Shape 3 0.5
The second FOR loop colors the shape on my worksheet based on the value of second array. The problem is all of my shapes are being colored with first value (i.e 0.3). I want Shape 1 to be colored based on 0.3 , Shape 2 based on 0.4 and so on. Thanks for helping me with this.
Private Sub Worksheet_Calculate() Dim arr1 Dim arr2 Set arr1 = Worksheets("Sheet2").Range("valueforarr1") Set arr2 = Worksheets("Sheet2").Range("Valueforarr2") Dim c, d As Range For Each c In arr1 c = Replace(c, " ", "_") MsgBox c For Each d In arr2 If d >= 0.2 And d <= 0.3 Then Worksheets("Sheet1").Shapes(c).Fill.ForeColor.RGB = RGB(237, 247, 249) Exit For ElseIf d > 0.3 And d <= 0.4 Then Worksheets("Sheet1").Shapes(c).Fill.ForeColor.RGB = RGB(218, 238, 243) Exit For ElseIf d > 0.4 And d <= 0.5 Then Worksheets("Sheet1").Shapes(c).Fill.ForeColor.RGB = RGB(183, 222, 232) Exit For ElseIf d > 0.5 Then Worksheets("Sheet1").Shapes(c).Fill.ForeColor.RGB = RGB(146, 205, 220) Exit For ElseIf d Is Nothing Then Worksheets("Sheet1").Shapes(c).Fill.ForeColor.RGB = RGB(255, 255, 255) Exit For End If Next d Next c End Sub
-29885235 0 The while loop is synchronous. You'll need to use an asynchronous loop. You have a couple options for this:
var loop = function(f, callback){ setTimeout(function(){ var count=0; while(f>10){ count++; } callback(count); }, 0); }; or
var loop = function(f, callback){ var count = 0; var si = setInterval(function(){ count++ if(f<=10){ clearInterval(si); callback(count); } }, 1000); }; Using these functions:
loop(frequencyVariable, function(count){ //callback has been called successfully and the loop has ended. //do stuff here });
-1924487 0 C# doesn't support covariant return types. When implementing an interface, you have to return the type specified by the interface. If you want to, you can explicitly implement the interface and have another method with the same name that returns the subtype. For example:
class MyImplementation : MyInterface { MyBaseClass MyInterface.someFunction() { return null; } public MySubClass someFunction() { return null; } }
-29756431 0 jquery parse xml with unlimited child level category I'm fairly new on parsing xml with jquery, so if my question looks like noobish, please forgive me.
I have an xml it contains my recursive categories. Some of them has sub categories, some of them not. It has some deep level categories under sub categories.
Sample of xml;
<Urunler> <Urun> <ID>1</ID> <Parent>0</Parent> <Name>Red</Name> </Urun> <Urun> <ID>2</ID> <Parent>0</Parent> <Name>Green</Name> </Urun> <Urun> <ID>3</ID> <Parent>0</Parent> <Name>Blue</Name> </Urun> <Urun> <ID>4</ID> <Parent>3</Parent> <Name>Sky</Name> </Urun> <Urun> <ID>5</ID> <Parent>3</Parent> <Name>Sea</Name> </Urun> <Urun> <ID>6</ID> <Parent>5</Parent> <Name>Fish</Name> </Urun> <Urun> <ID>7</ID> <Parent>4</Parent> <Name>Bird</Name> </Urun> </Urunler> Desired HTML output
<ul> <li>Red</li> <li>Green</li> <li>Blue <ul> <li>Sky <ul> <li>Bird</li> </ul> </li> <li>Sea <ul> <li>Fish</li> </ul> </li> </ul> </li> </ul> I find an example on http://codereview.stackexchange.com/questions/43449/parsing-xml-data-to-be-put-onto-a-site-with-jquery unfortunately it supports only first child level.
if needed; i call my xml via $.ajax
$.ajax({ url: 'webservice/Resim/Kategori.xml', dataType: 'xml', cache:true, success: parseXml }); Any help will greatly appricated.
-5856918 0 Performance with WPF Combo Box inside a ListViewI was wondering if I was missing something obvious.
I have a simple window with a ListView with 3 columns in it. One displays text and the other two have combo boxes in them.
The ListView has approx. 500 records and the Comboboxes both pull from the same contact list which has approx. 8,000 records in it.
I am using MVVM.
This window takes for ever to open and once it does open it is practically frozen solid (it moves so slow)
the queries to the database take under ten seconds (I log when the VM is fully loaded) then it takes two or three minutes to open the window. I made sure to store both lists in List<T> in my VM to make sure its not reprocessing the data or anything like that.
As you can see below. I've tried explicitly using Virtualizing Stack Panel but that did not help much.
Thank you for any help
<DataTemplate x:Key="ComboboxItemTemplate"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Image Grid.RowSpan="3" Source="{Binding ImageURL, IsAsync=True}" Width="50" /> <TextBlock Grid.Column="1" Text="{Binding Name}" /> <TextBlock Grid.Column="1" Grid.Row="1" Text="{Binding Email}" /> <TextBlock Grid.Column="1" Grid.Row="2" Text="{Binding CampusName}" /> </Grid> </DataTemplate> <ListView ItemsSource="{Binding MainList}" IsSynchronizedWithCurrentItem="True" Grid.RowSpan="2"> <ListView.ItemsPanel> <ItemsPanelTemplate> <VirtualizingStackPanel /> </ItemsPanelTemplate> </ListView.ItemsPanel> <ListView.View> <GridView> <GridViewColumn Width="200" Header="Internal"> <GridViewColumn.CellTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding Name}" FontWeight="Bold" /> <TextBlock Text="{Binding MName}" /> <TextBlock Text="{Binding CampusName}" /> </StackPanel> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn Width="200" Header="Contact1"> <GridViewColumn.CellTemplate> <DataTemplate> <ComboBox ItemsSource="{Binding Source={StaticResource VM}, Path=ContactList, IsAsync=True}" SelectedValue="{Binding HisContactID}" SelectedValuePath="id" ItemTemplate="{StaticResource ComboboxItemTemplate}" Background="{Binding HisColor}" Margin="0,82,0,115" Grid.Row="1" Grid.Column="1"> <ComboBox.ItemsPanel> <ItemsPanelTemplate> <VirtualizingStackPanel /> </ItemsPanelTemplate> </ComboBox.ItemsPanel> </ComboBox> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn Width="200" Header="Contact2"> ... </GridViewColumn> </GridView> </ListView.View> </ListView>
-23807810 0 you can just do
std::ratio<a,b>::num if you don't want to use typedef
-10405671 0 UrlEncoding issue for string with ß characterI have a parameter which I must pass as part of a url. The parameter contains this character: ß
When I encode this string, I am expecting this: %DF but instead i'm getting: %c3%9f
Here is a line of C# which I have been using to test
string test = HttpUtility.UrlEncode("ß");
-16743380 0 string to xmlNode delphi (or how to add an xml fragment to TXMLDocument) I Have a few text strings that contain well formed XML.
I would like to be able to (1) turn these strings into IXMLNodes then (2) append them to an existing XMLDocument. Preferably without declaring a new XMLDocument first.
This doesn't seem possible?
Is there any easy way to accomplish something equivalent though? My initial thought was to use the IXMLNode.XML (string) property and insert the new strings. No such luck as IXMLNode.XML is Read Only.
Here is an example, if I had the following strings in a TStringList,
<Property Name="Version" RttiType="tkString"></Property> <Property Name="ShowSubunit" RttiType="tkBoolean"></Property> And I had the following XML, already loaded into a TXMLDocument, how could I easily append the two lines above into the TXMLDocument below?
<Program Name="PFOO"> <Class Name="CFOO"> <Property Name="DBN" RttiType="tkString"/> <Property Name="SDate" RttiType="tkClass" ClassType="TXSDATE">12/30/1899</Property> <Property Name="XForm" RttiType="tkEnumeration">xfXML</Property> <Property Name="Singleton" RttiType="tkBoolean">True</Property> </Class> </Program> Any other (simple) ways to achieve this (no protected hack on the XML property please)?
Thank you!
-3736720 0My favorite tool for this kind of thing is HtmlAgilityPack. I use it to parse complex HTML documents into LINQ-queryable collections. It is an extremely useful tool for querying and parsing HTML (which is often not valid XML).
For your problem, the code would look like:
var htmlDoc = HtmlAgilityPack.LoadDocument(stringOfHtml); var images = htmlDoc.DocumentNode.SelectNodes("//img[id=lookforthis]"); if(images != null) { foreach (HtmlNode node in images) { node.Attributes.Append("alt", "added an alt to lookforthis images."); } } htmlDoc.Save('output.html');
-9069461 0 In MATLAB, you can run
format debug in the MATLAB Command Window to force it to display the variable as its memory location, rather than as its value. (This is an undocumented (AFAIK), but publicly known, option for the FORMAT function.)
See HELP FORMAT to determine what your current display format is, and more importantly, how to restore it, once you're done looking at the memory locations.
-31230674 0 Using AsyncTask with timer in fragmentI'm using Asynctask to load data via Volley. I want to do that AsyncTask invoked after n minutes, maybe this is duplicate and a silly question, but i cant figure how to implement it. Maybe I need to implement AsyncTask in my fragment ?
This is my AsyncTask.class
package com.aa.qc.task; import android.os.AsyncTask; import com.aa.qc.callbacks.ZleceniaLoadedListner; import com.aa.qc.extras.ZleceniaSorter; import com.aa.qc.extras.ZleceniaUtils; import com.aa.qc.network.VolleySingleton; import com.aa.qc.pojo.Zlecenia; import com.android.volley.RequestQueue; import java.util.ArrayList; public class TaskLoadZlecenia extends AsyncTask<Void, Void, ArrayList<Zlecenia>>{ private ZleceniaLoadedListner myComponent; private VolleySingleton volleySingleton; private RequestQueue requestQueue; private ZleceniaSorter mSorter = new ZleceniaSorter(); public TaskLoadZlecenia(ZleceniaLoadedListner myComponent) { this.myComponent = myComponent; volleySingleton = VolleySingleton.getsInstance(); requestQueue = volleySingleton.getmRequestQueue(); } @Override protected ArrayList<Zlecenia> doInBackground(Void... params) { ArrayList<Zlecenia> listZlecenias = ZleceniaUtils.loadZlecenia(requestQueue); mSorter.sortZleceniaByTime(listZlecenias); return listZlecenias; } @Override protected void onPostExecute(ArrayList<Zlecenia> listZlecenias) { if (myComponent != null) { myComponent.onZleceniaLoaded(listZlecenias); } } } This is listner.class
package com.aa.qc.callbacks; import com.aa.qc.pojo.Zlecenia; import java.util.ArrayList; public interface ZleceniaLoadedListner { public void onZleceniaLoaded(ArrayList<Zlecenia> listZlecenias); } This is my fragment where i want to repeat asynctask (I have activity with two tabs, each tabs is a fragment)
public class FragmentZlecenia extends Fragment implements SortListener, ZleceniaLoadedListner, SwipeRefreshLayout.OnRefreshListener { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; private ArrayList<Zlecenia> listZlecenias = new ArrayList<>(); private RecyclerView zleceniaArrived; private AdapterZlecenia adapterZlecenia; private SwipeRefreshLayout mSwipeRefreshLayout; private ZleceniaSorter mSorter = new ZleceniaSorter(); // TODO: Rename and change types of parameters private String mParam1; private String mParam2; /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment FragmentZlecenia. */ // TODO: Rename and change types and number of parameters public static FragmentZlecenia newInstance(String param1, String param2) { FragmentZlecenia fragment = new FragmentZlecenia(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } public FragmentZlecenia() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } public void onSortByTime() { L.t(getActivity(), "Sort by time"); mSorter.sortZleceniaByTime(listZlecenias); adapterZlecenia.notifyDataSetChanged(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View layout = inflater.inflate(R.layout.fragment_zlecenia, container, false); mSwipeRefreshLayout = (SwipeRefreshLayout) layout.findViewById(R.id.swipeZlecenia); mSwipeRefreshLayout.setOnRefreshListener(this); zleceniaArrived = (RecyclerView) layout.findViewById(R.id.listZlecenia); zleceniaArrived.setLayoutManager(new LinearLayoutManager(getActivity())); adapterZlecenia = new AdapterZlecenia(getActivity()); zleceniaArrived.setAdapter(adapterZlecenia); if (savedInstanceState != null) { //if this fragment starts after a rotation or configuration change, load the existing zlecenias from DB listZlecenias = MyApplication.getWritableDatabase().getAllZlecenia(); } else { //if this fragment starts for the first time, load the list of zlecenias from a database MyApplication.getWritableDatabase().deleteAll(); //if the database is empty, trigger an AsycnTask to download zlecenias list from the web if (listZlecenias.isEmpty()) { new TaskLoadZlecenia(this).execute(); } } //update your Adapter to containg the retrieved zlecenias adapterZlecenia.setListZlecenia(listZlecenias); return layout; } @Override public void onZleceniaLoaded(ArrayList<Zlecenia> listZlecenias) { L.m("onZleceniaLoaded Fragment"); new TaskLoadZlecenia(this).execute(); adapterZlecenia.setListZlecenia(listZlecenias); } @Override public void onRefresh() { L.t(getActivity(), "onRefresh"); new TaskLoadZlecenia(this).execute(); } }
-11413096 0 show login form using ajax after session expiration in grails I had a list of users displayed in a table whose session expires after 20min, but after expiration it doesn't go to login page without refreshing and I want to show a pop-up to display a login form which after login will keep me to the same url. I'm working on grails; can anyone help with it?
-38218234 0 Selected all Items in Custom product gridI have created a custom product grid in magento backend .I have used filters and csv export there and they working fine. but when i apply massaction to select all items it only select visible items.
it there any way to select all items of the grid even those are not visible.
new Date("2015/04/29 11:24:00").getTime(); //for answer in milliseconds (new Date("2015/04/29 11:24:00").getTime()/1000); //to get answer in seconds :)
-3877198 0 how to dice up the arrayI have an array like this (below is the var_dump)
array 0 => object(stdClass)[11] public 'VN' => string '571.5' (length=5) public 'color' => string 'GREEN' (length=5) public 'name' => string 'CIRRHOSIS' (length=9) public 'icd9ID' => string '5765' (length=4) public 'ID' => string '46741' (length=5) 1 => object(stdClass)[12] public 'VN' => string '571.5' (length=5) public 'color' => string 'GREEN' (length=5) public 'name' => string 'CIRRHOSIS' (length=9) public 'icd9ID' => string '5765' (length=4) public 'sortOrder' => string '1' (length=1) public 'ID' => string '46742' (length=5) 2 => object(stdClass)[15] public 'VN' => string 'V58.69' (length=6) public 'color' => string 'ORANGE' (length=6) public 'name' => string 'Long-term (current) use of other medications' (length=44) public 'icd9ID' => string '15116' (length=5) public 'ID' => string '46741' (length=5) 3 => object(stdClass)[14] public 'VN' => string '070.32' (length=6) public 'color' => string 'GREEN' (length=5) public 'name' => string 'HEPATITIS B CHRONIC' (length=19) public 'icd9ID' => string '14463' (length=5) public 'ID' => string '46742' (length=5) 4 => object(stdClass)[13] public 'VN' => string '070.32' (length=6) public 'color' => string 'GREEN' (length=5) public 'name' => string 'HEPATITIS B CHRONIC' (length=19) public 'icd9ID' => string '14463' (length=5) public 'ID' => string '46741' (length=5) I want to two HTML tables. One that will carry all the same ID and second one will carry the other ID
How can I do that Thanks!
-14259082 0Possible solutions:
Is it possible to have a hasMany relationship on two columns?
My table has two columns, user_id and related_user_id.
I want my relation to match either of the columns.
In my model I have
public function userRelations() { return $this->hasMany('App\UserRelation'); } Which runs the query: select * from user_relations where user_relations.user_id in ('17', '18').
The query I need to run is:
select * from user_relations where user_relations.user_id = 17 OR user_relations.related_user_id = 17 EDIT:
I'm using eager loading and I think this will affect how it will have to work.
$cause = Cause::with('donations.user.userRelations')->where('active', '=', 1)->first();
-23832876 0 Adding an entity to the context Why is this simple add not working! I get a previous record from the database, instantiate a new entity to add by using the previous record's data, except I increment the report number by 1. I keep getting the error "The property 'ReportNbr' is part of the primary key and cannot be modified." I thought this error was when you tried to update an existing entities' primary key field.
Here's my object and previous record that I use.
var previousRecord = _repo.GetLatestRecord(); var recordToAdd = new Record() { Year = previousRecord.Year, Month = previousRecord.Month, ReportNbr = ++previousRecord.ReportNbr, ...//other info }; _repo.AddRecord(recordToAdd); The three fields show are the primary key to the table. Any help would be greatly appreciated.
-33221981 0As far as I can see in the documentation, the define method of Parse.Cloud object requires a function which should take two parameters. Your function push_httpRequest then is not correctly defined. From Parse documentation:
-37795417 0 Check/Uncheck radio on filling textbox
define( name, func )Defines a Cloud Function.
Available in Cloud Code only. Parameters:
- name
<String>The name of the Cloud Function- func
<Function>
The Cloud Function to register. This function should take two parameters aParse.Cloud.FunctionRequestandParse.Cloud.FunctionResponse
I've got this little piece of code here I've been working on for a while, and for some reason it doesn't work. Can somebody have a look at it and tell me whats wrong with it?
All I need it to do is to check the "Other amount" radio box when someone enters an amount in the textbox. I'd also like to clear the amount written when any other radios are checked. Cross browser is a must.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Donation amount</title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script> <script type="text/javascript"> $("#donationAmountMan").on("input propertychange change paste keyup", function() { if ($("#donationAmountMan").val().length > 0) { $("#da_man").prop("checked", true); } else { $("#da_man").prop("checked", false); } }); </script> </head> <body> <label>Donation amount</label> <div> <label><input type='radio' name='donationAmount' id='da25' value='25' required /> $25</label> <label><input type='radio' name='donationAmount' id='da50' value='50' required /> $50</label> <label><input type='radio' name='donationAmount' id='da100' value='100' required /> $100</label> <label><input type='radio' name='donationAmount' id='da150' value='150' required /> $150</label> <label><input type='radio' name='donationAmount' id='da_man' value='0' required /> Other amount <input type='text' name='donationAmountMan' id='donationAmountMan'>$</label> </div> </body> </html> Thank you all for your precious help!
-22047775 0 Move of class with pimpl won't compileIn the following example, how is it possible that ~CImpl is called correctly but when the class needs to be moved, the compiler says it has an incomplete type?
If the declaration of Impl is moved to the header it works, my question is how come the destructor is called fine so it doesn't seem that the type is incomplete, but the problem appears when moving.
file: C.hpp
#include <memory> class Impl; class C { public: C(); ~C(); C(C&&) = default; C& operator=(C&&) = default; std::unique_ptr<Impl> p; }; file C.cpp
#include "C.hpp" #include <iostream> using namespace std; class Impl { public: Impl() {} virtual ~Impl() = default; virtual void f() = 0; }; class CImpl: public Impl { public: ~CImpl() { cout << "~CImpl()" << endl; } void f() { cout << "f()" << endl; } }; C::C(): p(new CImpl()) {} C::~C() file: main.cpp
#include <iostream> #include <vector> #include "C.hpp" using namespace std; int main(int argc, char *argv[]) { vector<C> vc; // this won't compile //vc.emplace_back(C()); C c; C c2 = move(c); // this won't compile } Compiler output:
+ clang++ -std=c++11 -Wall -c C.cpp + clang++ -std=c++11 -Wall -c main.cpp In file included from main.cpp:3: In file included from ./C.hpp:1: In file included from /usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/memory:80: /usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/unique_ptr.h:65:16: error: invalid application of 'sizeof' to an incomplete type 'Impl' static_assert(sizeof(_Tp)>0, ^~~~~~~~~~~ /usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/unique_ptr.h:184:4: note: in instantiation of member function 'std::default_delete<Impl>::operator()' requested here get_deleter()(__ptr); ^ ./C.hpp:12:5: note: in instantiation of member function 'std::unique_ptr<Impl, std::default_delete<Impl> >::~unique_ptr' requested here C(C&&) = default; ^ ./C.hpp:3:7: note: forward declaration of 'Impl' class Impl; ^ 1 error generated.
-34413478 0 FlipView is a Windows Store/Universal App only class.
The page you link to clearly states:
Requirements (Windows 10 device family)
Device family Universal
and
Requirements (Windows 8.x and Windows Phone 8.x)
Minimum supported client Windows 8 [Windows Store apps only]
If you want to have the same functionality in a WPF desktop application you will need to either find a third party control that does the same or write your own.
-1857611 0This is really complicated. I understand that you can edit your spreadsheets with Python using their API, Google tends to offer that ability on many of their web services and it's all done by sending HTTP post requests made of XML somehow, I hope you know that part, I don't.
According to this you can at least add worksheets, read rows from other worksheets and write rows to worksheets. if you must, you could copy it one row at a time, however sending an additional POST request for each row seems like a horrible idea.
Edit:
I'm learning more and more about this, but still a long way off from solving your original problem. This overview of REST principles goes over the basic style of interaction that goes on between programs on the web. Google seems to be following it religiously.
It all takes place within the HTTP protocol, something I knew nothing about before today. In this HTTP specification the basic game is spelled out. Its not as dry as it looks, and maybe I'm just a huge geek, but I find it an inspiring read. Not unlike The Constitution of The United States.
So since you want to "clone" a document, your going to be using a GET request for a particular worksheet, and then sending that worksheet back as the payload of POST.
Getting closer :)
-21497235 0I see one problem here. The line:
execlp ("./dummy", "dummy", NULL); /* replace myself with a new program */ was very important in your original program. If it is commented out, the child will continue the loop and spawning it's own sub-childs in the loop. So you will create (n*(n-1))/2 processes which then exits or are killed in a an unpredictable way.
Also your timing is very tight. Try to use delays in order of tens of seconds, so that you can manually watch what happens in your system.
Otherwise the program seems OK for me.
Concerning order of execution once the new process is created it competes for CPU in the same way as its parent process. So it is basically unpredictable which one will run first and for how long. If there are several cores in your CPU, they can actually run in the same time.
-30140741 0Do we really need to convert?
SELECT * FROM DBO.CUSTOMER WHERE CAST([date] AS DATE) >= '01/12/2014' AND CAST([date] AS DATE) <= '31/12/2014'
-39237502 0 git fetch /wp-contents/themes master git merge -s ours --no-commit FETCH_HEAD git read-tree --prefix=wp-contents/themes -u FETCH_HEAD git commit -m "message" Actually i propose to merge directories manually and commit the changes.
-30748306 0 How to edit the link of a variable in opencart register.tpl file?Here is the code of register.tpl file. The variable is called and this $action variable called the account/login.php file how to I can change the link of $action variable.
<form action="<?php echo $action; ?>" method="post" enctype="multipart/form-data"> <h2><?php echo $text_your_details; ?></h2> <div class="content"> <table class="form"> <tr> <td><span class="required">*</span> <?php echo $entry_firstname; ?></td> <td><input type="text" name="firstname" value="<?php echo $firstname; ?>" /> <?php if ($error_firstname) { ?> <span class="error"><?php echo $error_firstname; ?></span> <?php } ?></td> </tr> <tr> <td><span class="required">*</span> <?php echo $entry_lastname; ?></td> <td><input type="text" name="lastname" value="<?php echo $lastname; ?>" /> <?php if ($error_lastname) { ?> <span class="error"><?php echo $error_lastname; ?></span> <?php } ?></td> </tr> <tr> <td><span class="required">*</span> <?php echo $entry_email; ?></td> <td><input type="text" name="email" value="<?php echo $email; ?>" /> <?php if ($error_email) { ?> <span class="error"><?php echo $error_email; ?></span> <?php } ?></td> </tr> <tr> <td><span class="required">*</span> <?php echo $entry_telephone; ?></td> <td><input type="text" name="telephone" value="<?php echo $telephone; ?>" /> <?php if ($error_telephone) { ?> <span class="error"><?php echo $error_telephone; ?></span> <?php } ?></td> </tr>
-16435836 0 For anyone experiencing a similar problem, this is how I was able to solve this.
I first created the implementation and header files for a UIButton subclass with the NSIndexPath property. I assigned the uibutton in the Storyboard the superclass of this new custom unbutton with the NSIndexPath property. I added the following code to the segue identification step (the key was realizing i could use the sender object as the source of triggering the segue):
else if ([[segue identifier] isEqualToString:@"Add"]) { SearchAddRecordViewController *addRecordViewController = [segue destinationViewController]; addRecordButton *button = (addRecordButton*) sender; NSIndexPath *path = button.indexPath; SearchCell *cell = [self.tableView cellForRowAtIndexPath:path]; addRecordViewController.workingRecord = cell.record; }
-34678230 0 ROUTES
replace this
match "/users?q=" => "users#show", :via => [:get] to this
get "users" => "users#show" get "users/:q" => "users#show" and
CONTROLLER
def set_user @user ||= EvercamUser.find(:all, :conditions => ["id = ? or email = ?", params[:q], params[:q]]) end
-19482386 0 Highlighting a single item in a list menu with many items I have a navigation menu and I'm trying to do two things. When I hover 1 list item I'm trying to get that single item to be highlighted, if I click on a single item, I'm trying to make a certain color or style to be applied indicating that this item is currently in focus or active. If I select another, the current item deactivates and the newly selected item becomes active.
This is the CSS I tried but right now all items are being highlighted as soon as I hover any list item, instead of just one:
#listContainer{ margin-top:15px; } #expList ul, li { list-style: none; margin:0; padding:0; cursor: pointer; } #expList p { margin:0; display:block; } #expList p:hover { background-color:#121212; } #expList li { line-height:140%; text-indent:0px; background-position: 1px 555555px; padding-left: 20px; background-repeat: no-repeat; margin-bottom: 5px; } #expList ul{ margin-top: 5px; } #expList li:hover{ background-color: #eee; This is where the problem is } /* Collapsed state for list element */ #expList .collapsed { background-image: url('https://hosted.compulite.ca/kc/MD/SiteAssets/collapsed.png'); } /* Expanded state for list element /* NOTE: This class must be located UNDER the collapsed one */ #expList .expanded { background-image: url('https://hosted.compulite.ca/kc/MD/SiteAssets/expanded.png'); } Here's a JSFiddle with most of the code http://jsfiddle.net/aHSmy/1/
-12507646 0Your "error:function(msg)" callback function isn't using the right arguments.
I would suggest:
error: function(jqXHR, textStatus, errorThrown) { console.log(jqXHR, textStatus, errorThrown); //Check with Chrome or FF to see all these objects and decide what you want to display alert('Error! '+textStatus); } http://api.jquery.com/jQuery.ajax/
Also, check your PHP error logs to see if it does what you intend it to do.
-26018088 0You can use
filters.reject { |k, v| v.empty? }.length # => 2
-8262410 0 How to set Content-Length when sending POST request in NodeJS? var https = require('https'); var p = '/api/username/FA/AA?ZOHO_ACTION=EXPORT&ZOHO_OUTPUT_FORMAT=JSON&ZOHO_ERROR_FORMAT=JSON&ZOHO_API_KEY=dummy1234&ticket=dummy9876&ZOHO_API_VERSION=1.0'; var https = require('https'); var options = { host: 'reportsapi.zoho.com', port: 443, path: p, method: 'POST' }; var req = https.request(options, function(res) { console.log("statusCode: ", res.statusCode); console.log("headers: ", res.headers); res.on('data', function(d) { process.stdout.write(d); }); }); req.end(); req.on('error', function(e) { console.error(e); }); When i run the above code i am getting below error.
error message:
statusCode: 411 headers: { 'content-type': 'text/html', 'content-length': '357', connection: 'close', date: 'Thu, 24 Nov 2011 19:58:51 GMT', server: 'ZGS', 'strict-transport-security': 'max-age=604800' } "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 411 - Length Required How to fix the abobe error?
I have tried doing below
var qs = 'ZOHO_ACTION=EXPORT&ZOHO_OUTPUT_FORMAT=JSON&ZOHO_ERROR_FORMAT=JSON&ZOHO_API_KEY=dummy1234&ticket=dummy9876&ZOHO_API_VERSION=1.0'; ' options.headers = {'Content-Length': qs.length} But if I try this way I am getting below error:
{ stack: [Getter/Setter], arguments: undefined, type: undefined, message: 'socket hang up' } Can anybody help me on this?
Thanks
koti
PS:If I enter the whole url into browser address bar and hit enter I am getting JSON response as expected.
-16208603 0Basically you need to select the nodes you want to remove and .remove() them. Assume mycontent is a jQuery reference to the node with class item-options:
var warranty = mycontent.children('#warranty'); var txtContent = warranty.siblings('dd').last(); warranty.remove(); txtContent.remove(); If mycontent is a DOM node then just select it with jQuery:
var $mycontent = $(mycontent); A suggestion would be to structure your DOM such that the warranty element holds nodes related to it as children not as siblings. Otherwise the semantics is lost.
You can also check if the device can invoke the SMS app with
[[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:stringURL]]
-29046415 0 Currently your query is returning 4 rows:
[ { name: 'john', baggageno: 5, destination: 'toronto', 'max(ts)': 'Sat Mar 14 2015 02:25:03 GMT-0400' }, { name: 'jill', baggageno: 1, destination: 'karachi', 'max(ts)': 'Sat Mar 14 2015 02:25:03 GMT-0400' }, { name: 'jane', baggageno: 2, destination: 'new york', 'max(ts)': 'Sat Mar 14 2015 02:25:03 GMT-0400' }, { name: 'jim', baggageno: 5, destination: 'glasgow', 'max(ts)': 'Sat Mar 14 2015 02:25:03 GMT-0400' }, ] and you're picking the first row out of that result set, so that is why you're seeing what you're seeing (although the ordering of the rows is up to the server because you did not request a specific ordering).
You need to add some kind of filter if you're trying to find the record(s) with the latest ts value. For example, using a join might look something like:
SELECT map.* FROM map LEFT JOIN map map2 ON map.name = map2.name AND map.baggageno = map2.baggageno AND map.destination = map2.destination AND map.ts < map2.ts WHERE map2.name IS NULL You can also do something similar except using an inner join, if you want to do it that way.
-1145668 0Make sure that your self-signed certificate matches your site URL. If it does not, you will continue to get a certificate error even after explicitly trusting the certificate in Internet Explorer 8 (I don't have Internet Explorer 7, but Firefox will trust the certificate regardless of a URL mismatch).
If this is the problem, the red "Certificate Error" box in Internet Explorer 8 will show "Mismatched Address" as the error after you add your certificate. Also, "View Certificates" has an Issued to: label which shows what URL the certificate is valid against.
-20401142 0Do you really need to hide it for ALL other browsers? you should generaly use feature detection and allow any browser with the capabilities to play the video.
<video width="320" height="240" controls> <source src="movie.mp4" type="video/mp4"> Your browser does not support the video tag. </video> http://www.w3schools.com/html/html5_video.asp
-8414764 0Under Windows 7 on present generation processors, this is a reliable high precision (nanosecond) timer inside the CPU (HPET).
Under previous versions and on previous generations of processors, it is "something", which can mean pretty much anything. Most commonly, it is the value returned by the RDTSC instruction (or an equivalent, on non-x86), which may or may not be reliable and clock-independent. Note that RDTSC (originally, by definition, but not any more now) does not measure time, it measures cycles.
On current-and-previous-generation CPUs, RDTSC is usually reliable and clock-independent (i.e. it is now really measuring time), on pre-previous generation, especially on mobile or some multi-cpu rigs it is not. The "timer" may accelerate and decelerate, and even be different on different CPUs, causing "time travel".
Edit: The constant tsc flag in cpuid(0x80000007) can be used to tell whether RDTSC is reliable or not (though this does not really solve the problem, because what to do if it isn't, if there is no alternative...).
On yet older systems (like, 8-10 years old), some other timers may be used for QueryPerformanceCounter. Those may neither have high resolution at all, nor be terribly accurate.
-21756156 0Old question, but I found that the existing answers do not completely convert the text to plain. They seem to set the font to Helvetica and the size to 12.
However, you can pipe pbcopy and pbpaste to really remove formatting.
In the Terminal:
$ pbpaste | pbcopy As an AppleScript:
do shell script "pbpaste | pbcopy" That's it.
-5609354 0Nevermind, I figured it out. It was very simple, I just needed to delete the same value from the array that I was deleting from the database - it was always working on the same object so that variable never changed and each subsequent call once again saw previously deleted messages as valid messages.
-5701333 0As your error log shows "open_basedir restriction in effect." you can't really include anything outside from your basedir or outside from webroot in this server without changing the php configuration open_basedir variable
-23387413 0 pywinauto batch file running errorIm a biologist and new to pywinauto, i wrote a code to open an input file in HYPHY application using pywinauto, when i run my code line by line in command line it works fine but when i run the code as a batch file it gives the following error.
Traceback (most recent call last): File "C:\Users\Masyh\Desktop\autowin_test.py", line 8, in <module> w_handle = pywinauto.findwindows.find_windows(title=u' Please select a batch file to run:', class_name='#32770')[0] IndexError: list index out of range the code is:
import pywinauto pwa_app = pywinauto.application.Application() w_handle = pywinauto.findwindows.find_windows(title=u'HYPHY Console', class_name='HYPHY')[0] window = pwa_app.window_(handle=w_handle) window.SetFocus() window.MenuItem(u'&File->&Open->Open &Batch File\tCtrl+O').Click() w_handle = pywinauto.findwindows.find_windows(title=u' Please select a batch file to run:', class_name='#32770')[0] window = pwa_app.window_(handle=w_handle) window.SetFocus() ctrl = window['Edit'] ctrl.Click() ctrl.TypeKeys('brown.nuc') ctrl=window['&open'] ctrl.Click() i guess the problem is that the window which gets the input(#'please select a batch file menue') is not open at the beginning and the first part of the code opens it but python looks for it from the beginning and cant find it. i really appreciate any suggestions how to solve this.
-2137251 0Since you are using a Mac, I assume you have Ruby installed.
What you are talking about sounds like you want a thread to sleep for 30 seconds and then execute a script in the background.
You should put … do some stuff in a script named dostuff.scpt and place it in your Desktop.
Then change your current script to the following code:
using terms from application "iChat" on logout finished do shell script "ruby -e 'Thread.new {`sleep 30 && osascript ~/Desktop/dostuff.scpt`}' &> /dev/null" end logout finished end using terms from A code breakdown: do shell script (executes something from the command line)
ruby -e (executes ruby code from the command line)
Thread.new (makes a new thread to hide in the background)
` (Everything in the backtick is a shell command in ruby)
osascript (Executes an applescript from the command line)
~/Desktop/dostuff.scpt (Points the pathname to your file, the tilde substitutes to your home directory, and I assume you put dostuff.scpt on the Desktop)
&> /dev/null (Tells Applescript to not look for output and immediately go to the next code line)
I tried doing this without Ruby, however, I had no luck. Let me know if this works for you!
-12527400 0Suggested by remi, I implemented the same matrix multiplication using Eige. Here it is:
const int descrSize = 128; MatrixXi a(nframes, descrSize); MatrixXi b(vocabulary_size, descrSize); MatrixXi ab(nframes, vocabulary_size); unsigned char* dataPtr = DATAdescr; for (int i=0; i<nframes; ++i) { for (int j=0; j<descrSize; ++j) { a(i,j)=(int)*dataPtr++; } } unsigned char* vocPtr = vocabulary; for (int i=0; i<vocabulary_size; ++i) { for (int j=0; j<descrSize; ++j) { b(i,j)=(int)*vocPtr ++; } } ab = a*b.transpose(); a.cwiseProduct(a); b.cwiseProduct(b); MatrixXi aa = a.rowwise().sum(); MatrixXi bb = b.rowwise().sum(); MatrixXi d = (aa.replicate(1,vocabulary_size) + bb.transpose().replicate(nframes,1) - 2*ab).cwiseAbs2(); The key line is the line that says
ab = a*b.transpose(); vocabulary an DATAdescr are arrays of unsigned char. DATAdescr is 2782x128 and vocabulary is 4000x128. I saw at implementation that I can use Map, but I failed at first to use it. The initial loops for assigment are 0.001 cost, so this is not a bottleneck. The whole process is about 1.23 s
The same implementation in matlab (0.05s.) is:
aa=sum(a.*a,2); bb=sum(b.*b,2); ab=a*b'; d = sqrt(abs(repmat(aa,[1 size(bb,1)]) + repmat(bb',[size(aa,1) 1]) - 2*ab)); Thanks remi in advance for you help.
-36562428 0 Extract Skin pixels in face using scale space filtering methodI'm trying to implement color constancy method in this paper.'http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=6701394'. In this paper , the skin pixels are detected using scale space filtering method. I'm unable to go forward after forming a scale space image for the histogram of skin pixels extracted from face regions. please help me out. thanks in advance.
close all; clear all; clc; a = imread('Input.jpg'); %subplot(2,2,1); imshow(a); [row col dim] = size(a); hsv = rgb2hsv(a); % convert rgb to hsv h = hsv(:,:,1); h=h(:); s = hsv(:,:,2); v = hsv(:,:,3); [Hi,x]=hist(h,200); % forming an histogram with 200 bins plot(x,Hi); N=sum(Hi); Hist=Hi./N; % Normalize the histogram P=[]; figure;plot(Hist); sigma=2:2:50; % range of sigma values taken for forming scale space count=length(sigma); for i=1:count f1 = normpdf(-20:20,0,sigma(i)); % <== f(x) gaussian distribution p1 = conv(Hist,f1,'same'); P=[P; p1]; subplot(count,1,i); plot(p1);%title('smoothed signal with sigma='num2str(sigma)); end % Here P is tha scale space image mask=[1 -2 1]; for j=1:count P_derv(j,:)=conv(P(j,:),mask,'same'); %figure; subplot(count,1,j); end %P_derv is the 2nd derivative of the scale space image. Now , I have to found the zero contour and interval tree to identify the peak in histogram. The scale space filtering method is found in this paper. http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=1172729
-8021261 0 jQuery 1.7 is *still* returning the event.layerX and event.layerY error in ChromeWhat am I doing wrong? Am I misunderstanding the problem or is it something else entirely?
On my page I was using jQuery 1.6.4 from the Google CDN. This would, of course, generate the error:
event.layerX and event.layerY are broken and deprecated in WebKit. They will be removed from the engine in the near future.
I read here that jQuery 1.7 removed this issue. However, after updating my application to 1.7, I'm still seeing it. I'm using the Microsoft CDN until Google put the link up.
Things I've tried before posting this:
.on() works fine when I use 1.7 but obviously gives undefined errors with 1.6.4 - I thought this should prove 1.7 is actually runningAny ideas?
-26050930 0Let's define a term: operation = command or query from a domain perspective, for example ChangeTaskDueDate(int taskId, DateTime date) is an operation.
By REST you can map operations to resource and method pairs. So calling an operation means applying a method on a resource. The resources are identified by URIs and are described by nouns, like task or date, etc... The methods are defined in the HTTP standard and are verbs, like get, post, put, etc... The URI structure does not really mean anything to a REST client, since the client is concerned with machine readable stuff, but for developers it makes easier to implement the router, the link generation, and you can use it to verify whether you bound URIs to resources and not to operations like RPC does.
So by our current example ChangeTaskDueDate(int taskId, DateTime date) the verb will be change and the nouns are task, due-date. So you can use the following solutions:
PUT /api{/tasks,id}/due-date "2014-12-20 00:00:00" or you can use PATCH /api{/tasks,id} {"dueDate": "2014-12-20 00:00:00"}. the difference that patch is for partial updates and it is not necessary idempotent.
Now this was a very easy example, because it is plain CRUD. By non CRUD operations you have to find the proper verb and probably define a new resource. This is why you can map resources to entities only by CRUD operations.
Going back to the REST Service, the way I see it there are 3 options:
- Make RPC style urls e.g. http://example.com/api/tasks/{taskid}/changeduedate
- Allow for many commands to be sent to a single endpoint e.g.:
- URL: http://example.com/api/tasks/{taskid}/commands
- This will accept a list of commands so I could send the following in the same request:
- ChangeDueDate command
- ChangeDescription command
- Make a truly restful verb available and I create domain logic to extract changes from a dto and in turn translate into the relevant events required e.g.:
- URL: http://example.com/api/tasks/{taskid}
- I would use the PUT verb to send a DTO representation of a task
- Once received I may give the DTO to the actual Task Domain Object through a method maybe called, UpdateStateFromDto
- This would then analyse the dto and compare the matching properties to its fields to find differences and could have the relevant event which needs to be fired when it finds a difference with a particular property is found.
The URI structure does not mean anything. We can talk about semantics, but REST is very different from RPC. It has some very specific constraints, which you have to read before doing anything.
This has the same problem as your first answer. You have to map operations to HTTP methods and URIs. They cannot travel in the message body.
This is a good beginning, but you don't want to apply REST operations on your entities directly. You need an interface to decouple the domain logic from the REST service. That interface can consist of commands and queries. So REST requests can be transformed into those commands and queries which can be handled by the domain logic.
I have a two dimensional array that looks like this:
TITLETYPE = [['Prof.', '4'], ['Dr.', '3'], ['Mrs.', '2'], ['Ms.', '1'], ['Mr.', '0']] I need to get the key for value 1 for example (which should be 'Ms.') How should I go about doing that?
-12581309 0 hosting tomcat on mac osI'm using mini mac and tomcat 7.0.29, I want to host it from my computer so other computer outside the network could connect to it. I have set the port forwarding into 80 both start and end. set static IP on my mini mac. however, after getting the router IP address from ip2location.com and access to it from external computer,it display "it works!" screen, not the tomcat home page. this page is also displayed when I use localhost instead localhost:8080. Here is some snap shot that I've taken from both computer http://i182.photobucket.com/albums/x38/DNK90/staticIP.jpg
http://i182.photobucket.com/albums/x38/DNK90/portforwarding.jpg
And this one is from external computer
i182.photobucket.com/albums/x38/DNK90/tomcat.jpg
anybody who know how to access directly to the localhost:8080 through router IP, tell me ^^
-1853306 0Could you use a HyperLink control rather than a LinkButton?
eg
<asp:HyperLink id="hyperlink1" NavigateUrl="<%#Eval('name')%>" Text="<%#Eval('name')%>" Target="_blank" runat="server"/>
-15099488 0 As written in the answer, you'll need to provide hard links for bots.
Just treat it like a user without JavaScript. You should support users with no JavaScript. Feel free to implement the <noscript> tag.
I am writing a program to validate web pages on a remote server. It uses selenium RC to run Firefox with a battery of tests, so I can call arbitrary javascript. When there is a failure I would like to log the page's generated HTML. Now getting access to the DOM HTML is easy, But I am having real trouble finding a way to get at the source. Thanks.
I should reiterate that I am not looking for the DOM, but the original unmodified source code. As can be seen through Right click -> view page source. Specifically if <Html> <body> <table> <tr> <td> fear the table data </td> </table>
is the real HTML. Calls to document.documentElement.outerHTML || document.documentElement.innerHTML and selenium.getHTMLSource() will result in <head> </head><body> <table> <tbody><tr> <td> fear the table data </td> </tr></tbody></table> </body>
As you give no code it's hard to suggest actual code... However, the customary way to make text invisible is to use the text render mode. All text in PDF has such a text render mode and it determines whether the text is rendered as filled text (normal), stroked text, filled and stroked... And one of the possibilities is "invisible" which makes sure the text isn't shown.
When parsing text on a page iText amongst other things allows you to filter the text that is returned - see the FilteredRenderListener for example. During filtering you can then determine whether you're interested in the text or not. There is a lot of information about the text you can inspect using the TextRenderInfo object. This object has a method called "getTextRenderMode" that will return the above text render mode. If that call returns "3", you know the text is rendered invisibly.
Now, if you want to know for sure whether this text is indeed rendered invisibly (and not using one of the other nasty tricks @jongware suggests in his comment, you'll have to inspect the PDF or share an example with us so that we can take a look.
-25399483 0$array = [1, 6, 2]; array_unshift($array, array_pop($array)); Or possibly:
$array = [1, 6, 2]; $tmp = array_splice($array, 2, 1); array_unshift($array, $tmp[0]); You're not really looking for sorting on values, you just want to swap indices.
If you want to insert the value somewhere other than the front of the array, splice it back in with array_splice.
If you have more keys that you need to change around, then sorting may after all become the simplest solution:
uksort($array, function ($a, $b) { static $keyOrder = [2 => 0, 0 => 1, 1 => 2]; return $keyOrder[$b] - $keyOrder[$a]; });
-16642405 0 The following contrived examples do not have a unique solution. You need to decide what happens in these cases:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9 // first item move to end 2, 1, 3, 4, 5, 6, 7, 8, 9, 0 // adjacent items swapped For all other cases, luckily the telling trait is that the "out-of-order" item will be more than 1 away from both its neighbors (because #2 above).
for (i = 0; i < arr.length; i++) { int priorIndex = (i-1) % arr.length; int nextIndex = (i+1) % arr.length; int diffToPriorValue = abs(arr[i] - arr[priorIndex]); int diffToNextValue = abs(arr[i] - arr[nextIndex]); if (diffToPriorValue > arr.length/2) diffToPriorValue = arr.length - diffToPriorValue; // wrap-around if (diffToNextValue > arr.length/2) diffToNextValue = arr.length - diffToNextValue; // wrap-around if (diffToPriorValue != 1 && diffToNextValue != 1) return i; return -1;
-20154840 0 The first error is strictly a client-side javascript error. The error description means exactly what it says. You should update your js appropriately.
The second set of error message probably related to the fact you are making a cross-domain request for a javascript file which is not subject to your headers being sent by PHP. You would need to configure CORS on webserver for such endpoint
-35188317 0No, you don't need to create a service to access a database on a server. What you are actually asking is how to read from (write to) database on C#. As I understand you already have an access to the database (user account with granted access and password). You will need to use ADO.NET - it's a technology for data access.
You will utilize SqlConnection, SqlDataReader and SqlCommand classes. check for example this example: Reading values from SQL database in C#
There is a newer technology from Microsoft called Entity Framework. It provides better solution for working with databases. Use it if you need to work with many tables and complicated queries.
-38379066 0Missed Iops, This is working now
{ "AWSTemplateFormatVersion" : "2010-09-09", "Resources" : { "MyDB" : { "Type": "AWS::RDS::DBInstance", "Properties": { "DBInstanceClass" : "db.t2.medium", "AllocatedStorage" : "400", "MasterUsername" : "xxxxxxxxxxxx", "MasterUserPassword" : "xxxxxxxxxxxx", "DBSnapshotIdentifier" : "xxxxxxxxxxxx-2016-07-13-1700", "Iops":"2000", "StorageType":"io1" } } } }
-22265971 0 PHPrunner uses inbuilt server to preview your generated application. So quite obvious when you close Runner it will close the inbuilt server connection as well. You will have to move the output folder to root folder of your web server. If you look inside your project folder, you will find a folder named output, move this folder to the root folder of your web server, it should work fine.
Make sure your web server is powered to use PHP and other drivers related to your project.
-928463 0Universal Business Language and dozens of others are documented at OASIS. UBL is widely accepted as an invoicing standard, at least, and some countries (at least Denmark) make UBL a legal requirement for invoicing public organisations.
-31492440 0 Parsing this kind of dataI have written a wrapper for an API. Previously I'd worked on simple string-based GET requests to PHP scripts using Perl.
As part of analysing the response, I have to analyse the following data which appears to be an object. Unfortunately, I'm not sure how to extract usable data from this.
print Dumper on the data returns this:
$VAR1 = bless( { '_rc' => '200', '_request' => bless( { '_uri_canonical' => bless( do{\(my $o = 'http://example.com/?list=1&token=h_DQ-3lru6uy_Zy0w-KXGbPm_b9llY3LAAAAALSF1roAAAAANxAtg49JqlUAAAAA')}, 'URI::http' ), '_content' => '', '_uri' => $VAR1->{'_request'}{'_uri_canonical'}, '_method' => 'GET', '_headers' => bless( { 'accept-charset' => 'iso-8859-1,*,utf-8', 'accept' => 'image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png, */*', 'cookie' => 'GUID=cHoW3DLOljP4K9LzposM', 'user-agent' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7) Gecko/20041107 Firefox/1.0', 'authorization' => 'Basic YWRtaW46bmljb2xl', 'cookie2' => '$Version="1"', '::std_case' => { 'cookie' => 'Cookie', 'cookie2' => 'Cookie2' }, 'accept-language' => 'en-US' }, 'HTTP::Headers' ) }, 'HTTP::Request' ), '_headers' => bless( { 'client-peer' => 'myip:8085', 'content-type' => 'text/plain', 'cache-control' => 'no-cache', 'connection' => 'keep-alive', 'client-date' => 'Sat, 18 Jul 2015 12:41:00 GMT', '::std_case' => { 'client-response-num' => 'Client-Response-Num', 'set-cookie2' => 'Set-Cookie2', 'client-date' => 'Client-Date', 'client-peer' => 'Client-Peer', 'set-cookie' => 'Set-Cookie' }, 'client-response-num' => 1, 'content-length' => '8684' }, 'HTTP::Headers' ), '_msg' => 'OK', '_protocol' => 'HTTP/1.1', '_content' => '{"build":30470,"torrents": [ ["043CC5FA0C741CDAD9D2E5CC20DF64A4A400FA34",136,"Epi.S01E03.720p.HDTV.x264-IMMERSE[rarbg]",690765843,39,26951680,671744,24,0,0,0,"",0,1454,0,114,2436,1,663814163,"","","Stopped","512840d7",1437022635,0,"","/mydir/Epi.S01E03.720p.HDTV.x264-IMMERSE[rarbg]",0,"0368737A",false], ["097AA60280AE3E4BA8741192CB015EE06BD9F992",200,"Epi.S01E04.HDTV.x264-KILLERS[ettv]",221928759,1000,221928759,8890308649,40059,0,0,0,"",0,1461,0,4395,65536,-1,0,"","","Queued Seed","512840d8",1437022635,1437023190,"","/mydir/Epi.S01E04.HDTV.x264-KILLERS[ettv]",0,"8F52310A",false]], "label": [],"torrentc": "350372445" ,"rssfeeds": [] ,"rssfilters": [] } ', '_msg' => 'OK', '_protocol' => 'HTTP/1.1' }, 'HTTP::Response' ); I would like to extract each of the following strings from the returned object
097AA60280AE3E4BA8741192CB015EE06BD9F992 200 Epi.S01E04.HDTV.x264-KILLERS[ettv] Unfortunately, my understanding of objects in Perl is very elementary.
The original code which returns this data looks like this:
my $ua = LWP::UserAgent->new(); my $response = $ua->get( $url, @ns_headers ); print Dumper($response); How can I work on the strings that of interest?
-15797505 0Without more detail on your situation, here are some helpful resources.
For time zones on Rails, have a look here for the various options you can use: http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html
To format for your users, look into strftime. Docs: http://apidock.com/ruby/Time/strftime
A site that helps you generate strftime code: http://strftime.net/
A guide to I18n / internationalization: guides.rubyonrails.org/i18n.html (thanks @house9)
-7725485 0this would probably do the trick
success: function (data) { response($.map(data, function (item) { return { label: item.First, value: item.First} })) });
-17180066 0 100% height input-field and align text vertically Maybe a duplicate but I did not found a question with a similar problem.
Ok, I've to create a 100% height input field that centers the text vertically and horizontally. The problem is that if I set the line-height to window-width the cursor gets the same size in Chrome.
Any ideas how to center the text without line-height?
input { position: absolute; top: 0; left 0; margin: 0; padding: 0; width: 100%; height: 100%; text-align: center; border: 0; outline: 0 } Just to set the line-height:
$('input').css({ lineHeight: $(window).height() + 'px' }); http://fiddle.jshell.net/G9uVw/
Update
It seems that the question needs to be changed. The problem is that oldIE doesn't center the text, but all other browsers do. So the new question is, how can we check if a browser supports this auto-center-feature?! (Since we know thatua`-sniffing is evil, I don't want to check for a particular browser...)
Update2
It seems that this is a bug in webkit: https://code.google.com/p/chromium/issues/detail?id=47284
-11121579 0I had a similar problem with SVG for a responsive design I was working on. I ended up removing the height and width attributes on the SVG element, and setting them via CSS instead. There is also a viewBox attribute on my SVG element and preserveAspectRatio="xMidYMin meet". With that setup I was able to have an SVG element that resizes dynamically based on viewport size.
-36644898 0I think that your initial idea is pretty good and can be made to work with not too much code. It will require some tinkering in order to decouple "is a Runnable for this value already running" from "execute this Runnable", but here's a rough illustration that doesn't take care about that:
equals() and hashCode() in Process, so that instances can safely be used in unordered sets and maps.ConcurrentMap<Process, Boolean> Collections.newSetFromMap(new ConcurrentHashMap<Process, Boolean>) because you'd want to use the map's putIfAbsent() method.putIfAbsent() each Process that you will be submitting and bail if the returned value is not null. null return value means that there's already an equivalent Process in the map (and therefore being processed).Process instance and have putIfAbsent(this, true) as the first thing you do in your run() method.Process that has finished processing. Process instance and have remove(this) as the last thing you do in your run() method.Process implement Callable and return its unique value as a result, so that it can be removed from the map, or use CompletableFuture and its thenAccept() callback.Here's a sample that illustrates the trivial and not very clean solution described above (code too long to paste directly here).
-28517254 0You can start looking at developer tools of chrome where you can understand more about rendering of html elements.. Check the image attached for one such instance. Your h2(id="block-bens-main-menu-menu") tag has by default margin-top & margin-botom values which is actually creating the space. Investigate more by yourself ;) 
Your new table should look like this:
public class MessageByPerson { @ManyToOne private Message message; @ManyToOne private Person person; @Column private Date date; }
-5737076 0 Simple Rspec test for positive number just won't pass I'm new to rails and trying to write my first app. I have a table with columns order_size:integer and price:decimal(8,5). The price column holds currency prices so it needs to be really precise, in case you're wondering. I'm trying to write tests to make sure the price and order_size are a positive numbers, but no matter what I do they won't pass.
Here are the Rspec tests
it "should require a positive order size" do @attr[:order_size] = -23 @user.orders.create!(@attr).should_not be_valid end it "should require a positive price" do @attr[:price] = -1.2908 @user.orders.create!(@attr).should_not be_valid end Here are the Order class validations
validates_presence_of :user_id validates_numericality_of :order_size, :greater_than => 0, :only_integer => true validates_numericality_of :price, :greater_than => 0 Here's the test results
Failures: 1) Order validations should require a positive order size Failure/Error: @user.orders.create!(@attr).should_not be_valid ActiveRecord::RecordInvalid: Validation failed: Order size must be greater than 0 # ./spec/models/order_spec.rb:39:in `block (3 levels) in <top (required)>' 2) Order validations should require a positive price Failure/Error: @user.orders.create!(@attr).should_not be_valid ActiveRecord::RecordInvalid: Validation failed: Price must be greater than 0 # ./spec/models/order_spec.rb:44:in `block (3 levels) in <top (required)>' What exactly is going on here? I even tried running the test asserting they should be_valid, but they still fail. Any help would be appreciated.
-13491922 1 What is the difference between url() and tuple for urlpatterns in Django?So in Django the two lines of url code below work the same:
urlpatterns = patterns('', url(r'^login/$', 'django.contrib.auth.views.login'), (r'^login/$', 'django.contrib.auth.views.login') ) AFAIK, the only difference is I can define name='login' so I can use it for reversing url. But besides this, is there any other differences?
Before storing, cast the pointer with a dynamic_cast<void*> - this will give you a void pointer to the most derived object; this void pointer will, for the same objects, have the same address stored.
See also this question.
-31403686 0Just a simple trick you can do
just use a string variable for messages appending and counter.
$(document).ready(function () { var Messages; var counter=0; $('#btnSave').click(function (e) { validateTitle(); validatePrefix(); validateTextBoxes(); if(counter > 0) { alert(Messages); e.preventDefault(); counter=0; } }); function validateTitle() { debugger; if ($("#ddlTitle").val() > "0") { if ($("#ddlTitle").val() == "1104" && $("#txtTitle").val() === "") { Messages += "Please enter the text in other title"; Messages += "\n"; counter ++; } } else { Messages += 'Please select the title'; Messages += "\n"; counter ++; } } function validatePrefix() { debugger; if ($("#ddlPrefix").val() > "0") { if ($("#ddlPrefix").val() == "1110" && $("#txtPrefix").val() === "") { Messages += "Please enter the text in other prefix"; Messages += "\n"; counter ++; } } else { Messages += 'Please select the prefix'; Messages += "\n"; counter ++; } } function validateTextBoxes() { debugger; if ($("#txtFirstName").val() === "") { Messages += 'First name is required'; Messages += "\n"; counter ++; } if ($("#txtMiddleName").val() === "") { Messages += 'Middle name is required'; Messages += "\n"; counter ++; } if ($("#txtLastName").val() === "") { Messages += 'Last name is required'; Messages += "\n"; counter ++; } if ($("#txtFatherName").val() === "") { Messages += 'Father name is required'; Messages += "\n"; counter ++; } if ($("#txtCurrentCompany").val() === "") { Messages += 'Current company is required'; Messages += "\n"; counter ++; } if ($("#txtDateofJoin").val() === "") { Messages += 'Date is required'; Messages += "\n"; counter ++; } if ($("#txtCurrentExp").val() === "") { Messages += 'Current Experience is required'; Messages += "\n"; counter ++; } } }); Just update counter and impliment check if check > 0 show message (alert)
it will benefit you two things
User dont need to click each time and get alert.. dont need to return false.user Must know at once what erors are in form.
Secondly code is simple/Simple logic.
I'm working on an enterprise iOS app using MvvmCross 3.2.1 and iOS 8 (with updated profile 259) and it's throwing exception "Failed to resolve parameter for parameter factory of type ISQLiteConnectionFactory when creating MyDataService".
The same application works fine using MvvmCross 3.1.1 and iOS 7 and profile24.
It's appearing that the PlugIns aren't being loaded in time based on the application output.
Here's a snippet of the output from the version that works:
2014-09-25 09:30:36.453 MyApp[2665:70b] mvx: Diagnostic: 5.19 Setup: MvvmCross settings start 2014-09-25 09:30:36.453 MyApp[2665:70b] mvx: Diagnostic: 5.19 Setup: Singleton Cache start 2014-09-25 09:30:36.454 MyApp[2665:70b] mvx: Diagnostic: 5.19 Setup: Bootstrap actions 2014-09-25 09:30:36.466 MyApp[2665:70b] mvx: Diagnostic: 5.20 Setup: StringToTypeParser start 2014-09-25 09:30:36.469 MyApp[2665:70b] mvx: Diagnostic: 5.21 Setup: ViewModelFramework start 2014-09-25 09:30:36.470 MyApp[2665:70b] mvx: Diagnostic: 5.21 Setup: PluginManagerFramework start 2014-09-25 09:30:36.475 MyApp[2665:70b] mvx: Diagnostic: 5.21 Ensuring Plugin is loaded for Cirrious.MvvmCross.Plugins.File.PluginLoader 2014-09-25 09:30:36.478 MyApp[2665:70b] mvx: Diagnostic: 5.22 Ensuring Plugin is loaded for Cirrious.MvvmCross.Plugins.Network.PluginLoader 2014-09-25 09:30:36.479 MyApp[2665:70b] mvx: Diagnostic: 5.22 Ensuring Plugin is loaded for Cirrious.MvvmCross.Plugins.Visibility.PluginLoader 2014-09-25 09:30:36.480 MyApp[2665:70b] mvx: Diagnostic: 5.22 Ensuring Plugin is loaded for Cirrious.MvvmCross.Community.Plugins.Sqlite.PluginLoader 2014-09-25 09:30:36.481 MyApp[2665:70b] mvx: Diagnostic: 5.22 Ensuring Plugin is loaded for Cirrious.MvvmCross.Plugins.Messenger.PluginLoader 2014-09-25 09:30:36.482 MyApp[2665:70b] mvx: Diagnostic: 5.22 Ensuring Plugin is loaded for Cirrious.MvvmCross.Plugins.ResourceLoader.PluginLoader 2014-09-25 09:30:36.483 MyApp[2665:70b] mvx: Diagnostic: 5.22 Ensuring Plugin is loaded for Cirrious.MvvmCross.Plugins.WebBrowser.PluginLoader 2014-09-25 09:30:36.484 MyApp[2665:70b] mvx: Diagnostic: 5.22 Setup: App start
And here's the output for the iOS version that throws the exception:
2014-09-25 09:36:35.078 MyApp[2889:122068] mvx: Diagnostic:
6.69 Setup: MvvmCross settings start 2014-09-25 09:36:35.078 MyApp[2889:122068] mvx: Diagnostic: 6.69 Setup: Singleton Cache start 2014-09-25 09:36:35.079 MyApp[2889:122068] mvx: Diagnostic: 6.69 Setup: Bootstrap actions 2014-09-25 09:36:35.096 MyApp[2889:122068] mvx: Diagnostic: 6.71 Setup: StringToTypeParser start 2014-09-25 09:36:35.098 MyApp[2889:122068] mvx: Diagnostic: 6.71 Setup: CommandHelper start 2014-09-25 09:36:35.098 MyApp[2889:122068] mvx: Diagnostic: 6.71 Setup: ViewModelFramework start 2014-09-25 09:36:35.099 MyApp[2889:122068] mvx: Diagnostic: 6.71 Setup: PluginManagerFramework start 2014-09-25 09:36:35.101 MyApp[2889:122068] mvx: Diagnostic: 6.71 Setup: App start
With the missing "Ensure PlugIn loaded" statements, I'm thinking that the PlugIns aren't being loaded (I'm using File, Messenger, Visibility, Community Sqlite, Network, ResourceLoader and WebBrowser).
As part of my debugging process, I integrated my application directly with the MvvmCross source code, using project references rather than packages. Not sure if that makes a difference but thought I should mention it.
Still relatively new to MvvmCross, and any thoughts on why the PlugIns aren't loaded or what I might be missing in the conversion to iOS 8 would be greatly appreciated
-15796025 0 Execute a SQL query With Anchor Tagplease help to solve this issue,
I have a Anchor Tag in my page.
i want to perform a SQL UPDATE query when users click the anchor tag, how can i do that without reloading the page?
Thanks in advance.
-14688536 0 Move adjacent tab to split?Is there an easy way to move an adjacent tab in Vim to current window as a split?
While looking around I reached a mailing list discussion where someone said it's the reverse of the operation Ctrl+W,T without providing the solution.
-37508754 0All the occurances of stocklevel are getting replaced with the value of newlevel as you are calling s.replace (stocklevel ,newlevel).
string.replace(s, old, new[, maxreplace]): Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.
As you suggested, you need to get the code and use it replace the stock level.
This is a sample script which takes the 8 digit code and the new stock level as the command line arguments adn replaces it:
import sys import re code = sys.argv[1] newval= int(sys.argv[2]) f=open("stockcontrol.csv") data=f.readlines() print data for i,line in enumerate(data): if re.search('%s,\d+'%code,line): # search for the line with 8-digit code data[i] = '%s,%d\n'%(code,newval) # replace the stock value with new value in the same line f.close() f=open("in.csv","w") f.write("".join(data)) print data f.close() Another solution using the csv module of Python:
import sys import csv data=[] code = sys.argv[1] newval= int(sys.argv[2]) f=open("stockcontrol.csv") reader=csv.DictReader(f,fieldnames=['code','level']) for line in reader: if line['code'] == code: line['level']= newval data.append('%s,%s'%(line['code'],line['level'])) f.close() f=open("stockcontrol.csv","w") f.write("\n".join(data)) f.close() Warning: Keep a back up of the input file while trying out these scripts as they overwrite the input file.
If you save the script in a file called test.py then invoke it as:
python test.py 34512340 10.
This should replace the stockvalue of code 34512340 to 10.
-10604690 0 Noise/distortion after doing filters with vDSP_deq22 (biquad IIR filter)I'm working on a DSP class (obj-c++) for Novocaine, but my filters only seem to cause noise/distortion on the signal.
I've posted my full code and coefficients here: https://gist.github.com/2702844 But it basically boils down to:
// Deinterleaving... // DSP'ing one channel: NVDSP *handleDSP = [[NVDSP alloc] init]; [handleDSP setSamplingRate:audioManager.samplingRate]; float cornerFrequency = 6000.0f; float Q = 0.5f; [handleDSP setHPF:cornerFrequency Q:Q]; [handleDSP applyFilter:audioData length:numFrames]; // DSP other channel in the same way // Interleaving and sending to audio output (Novocaine block) See the gist for full code/context.
The coefficients:
2012-05-15 17:54:18.858 nvdsp[700:16703] b0: 0.472029 2012-05-15 17:54:18.859 nvdsp[700:16703] b1: -0.944059 2012-05-15 17:54:18.860 nvdsp[700:16703] b2: 0.472029 2012-05-15 17:54:18.861 nvdsp[700:16703] a1: -0.748175 2012-05-15 17:54:18.861 nvdsp[700:16703] a2: 0.139942 (all divided by a0)
Since I presumed the coefficients are in the order of: { b0/a0, b1/a0, b2/a0, a1/a0, a2/a0 } (see: IIR coefficients for peaking EQ, how to pass them to vDSP_deq22?)
What is causing the distortion/noise (the filters don't work)?
-20196226 0The following regex will strip the first and last slashes if they exist,
var result = "/installers/services/".match(/[^/].*[^/]/g)[0];
-16811289 0 Read here
-39630921 0Tiered Compilation
Tiered compilation, introduced in Java SE 7, brings client startup speeds to the server VM. Normally, a server VM uses the interpreter to collect profiling information about methods that is fed into the compiler. In the tiered scheme, in addition to the interpreter, the client compiler is used to generate compiled versions of methods that collect profiling information about themselves. Since the compiled code is substantially faster than the interpreter, the program executes with greater performance during the profiling phase. In many cases, a startup that is even faster than with the client VM can be achieved because the final code produced by the server compiler may be already available during the early stages of application initialization. The tiered scheme can also achieve better peak performance than a regular server VM because the faster profiling phase allows a longer period of profiling, which may yield better optimization.
I could not figure out a proper solution to the timming issue so here is a workaround:
function resize(){ $("#id_permissions_from").css("height", 600); $("#id_permissions_from").css("overflow", "scroll"); $("#id_permissions_to").css("height", 600); $("#id_permissions_to").css("overflow", "scroll"); } $(function() { setTimeout(function() { resize() }, 1000); //resize(); })
-16311007 0 knockout.js using the mapping plugin I am a newbie with knockout.js and want to start using the automatic mapping plugin. How can I convert this manually mapped code to use the mapping plugin?
http://jsfiddle.net/infatti/jWTtb/6/
// Here's my data model var ViewModel = function (firstName, lastName) { var self = this; self.firstName = ko.observable(firstName); self.lastName = ko.observable(lastName); self.loadJson = function () { $.getJSON("http://echo.jsontest.com/firstName/Stuart/lastName/Little", function (data) { self.firstName(data.firstName); self.lastName(data.lastName); }); return true; }; }; var vm = new ViewModel(); ko.applyBindings(vm); // This makes Knockout get to work
-30406849 0 glfwOpenWindow fail on osx yosemite I am trying to build and run the following project on OS X Yosemite to play with ray marching & shaders:
https://github.com/lightbits/ray-march/blob/master/raymarch-dev.md
I am not too familiar with compilation on OS X nor openGL.
The error:
I got the project to compile but « glfwOpenWindow » fail on,
glfwOpenWindow( width, height, 8, 8, 8, 0, 24, 8, false ) I don’t get any error message and don’t know why it failed. I think the problem comes from what I did to build the codebase.
What I did:
The external includes are:
#include <glload/gl_3_1_comp.h> // OpenGL version 3.1, compatability profile #include <glload/gll.hpp> // The C-style loading interface #include <GL/glfw.h> // Context #include <glm/glm.hpp> // OpenGL mathematics #include <glm/gtc/type_ptr.hpp> // for value_ptr(matrix) #include <string> I replaced, in "opengl.h",
#include <glload/gl_3_1_comp.h> // OpenGL version 3.1, compatability profile #include <glload/gll.hpp> // The C-style loading interface
with,
`#include <OpenGL/gl3.h>` I removed, in "opengl.cpp".
if(glload::LoadFunctions() == glload::LS_LOAD_FAILED) return false;
my current compiling command is:
g++ main.cpp fileio.cpp opengl.cpp -I /usr/local/include/GL/ -L /usr/local/lib/ -framework OpenGL -lGLFW
I think you are going the wrong way. Backpropagation isn't a good choice for this type of learning (somehow incremental learning). To use backpropagation you need some data, say 1000 data where different types of similaritiy (input) and the True Similarity (output) are given. Then weights will update and update until error rate comes down. And besides you need test data set too that will make you sure the result network will do good even for similarity values it didn't see during training.
-25943857 0To draw multi line text with Snap.svg is a bit bother.
When you call Paper.text method with string array, Snap.svg creates tspan elements under the text element.
If you want to display the text element as multi line, you should set position to each tspan element manually.
var paper = Snap(200,200); paper.text({text:["Line1", "Line2", "Line3"]}) .attr({fill:"black", fontSize:"18px"}) .selectAll("tspan").forEach(function(tspan, i){ tspan.attr({x:0, y:25*(i+1)}); });
-9865292 0 trouble debugging and running sample android project I installed the Android 2.2 SDK (2.2 is the version i have on my smartphone). I've tried running the NotePad sample project as an Android project. Here is what happens: the emulator loads, but when I click on the app, the screen goes blank. There are no errors being thrown. Has anyone else run into this problem? If so, how have you fixed it?
-22378668 0 Select jquery inputIt's a quick question for you,
I need to select Jquery element by type AND by name.
I know that we can do something like:
$('.form-control input[type=text]').... but I need to select by name too..
do you have another way to do that unless using:
$('.form-control input[type=text]').each(function (){ if($(this).attr('name') == 'search'){ // this is my selector } } thank you
-10992734 0try right: 100% instead of left: 0, which basically tells your menu that it should position its left edge to the leftmost edge of its parent. right: 100% should tell it to align its rightmost edge with your parent menus leftmost edge. Hope this helps!
This is my nginx config:
server { listen 80; server_name localhost; keepalive_timeout 5; access_log /home/tunde/django-projects/mumu/nginx/access.log; error_log /home/tunde/django-projects/mumu/nginx/error.log; root /home/tunde/django-projects/mumu; location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://127.0.0.1:8000; } } My settings.py looks like:
import os settings_dir = os.path.dirname(__file__) PROJECT_ROOT = os.path.abspath(os.path.dirname(settings_dir)) STATIC_ROOT = '/home/tunde/django-projects/mumu/STATIC/' STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, 'static/'), ) My supervisord.conf file looks like:
[program: mumu] command = /home/tunde/ENV1/bin/gunicorn -w 1 --bind=127.0.0.1:8000 mumu.wsgi:application directory = /home/tunde/django-projects/mumu/ stdout_logfile= /home/tunde/django-projects/mumu/supervisor/logfile.log stderr_logfile= /home/tunde/django-projects/mumu/supervisor/error.log user = tunde The problem is that static files don't get served and I have no idea what I'm doing wrong. A url like /static/css/styles.css returns a 404. Help will be greatly appreciated.
-16714062 0 Replace a method with parameters by a closure in metaclassI have two class:
class Foo { String doSomething(String a, String b) { return 'Not Working' } } class Bar { String methodIWannaTest() { return new Foo().doSomething('val1', 'val2') } } And I want to replace 'doSomething' in a test but it dosent work
class BarTests { @Test void testMethodIWannaTest() { Foo.metaClass.doSomething {String a, String b -> return 'Working'} assert new Bar().methodIWannaTest() == 'Working' //THIS TEST FAIL, return 'Not Working' } } *I know the test doesn't really make sens, it's just to show my point
What do I do wrong ? Is it possible to do it without using 'mockFor' ?
-33671497 0 RegEx with preg_match to find and replace a SIMILAR stringI am using regular expressions with preg_replace() in order to find and replace a sentence in a piece of text. The $search_string contains plain text + html tags + elements. The problem is that only sometimes the elements convert to white space on run time, making it difficult to find and replace using str_replace(). So, I'm trying to build a pattern that is equal to the search string and will match anything like it which contains, or does not contain the elements;
For example:
$search_string = 'Two years in, the company has expanded to 35 cities, five of which are outside the U.S. Plus, in April, <a href="site.com">ClassPass</a> acquired its main competitor, Fitmob.'; $pattern = $search_string(BUT IGNORE THE elements in the subject)
$subject = "text text text text text". $search_string . "text text text text text"; Using A regular expression to exclude a word/string, I've tried:
$pattern = '`^/(?!\ )'.$search_string.'`'; $output = preg_replace($pattern, $replacement_string,$subject); The end result will be that if the $subject does contains a string that is like my $seach_string but without the elements, it will still match and replace it with $replacement_string
EDIT:
The actual values:
$subject = file_get_contents("http://venturebeat.com/2015/11/10/sources-classpass-raises-30-million-from-google-ventures-and-others/"); $search_string = "Two years in, the company has expanded to 35 cities, five of which are outside the U.S. Plus, in April, ClassPass acquired its main competitor, Fitmob."; $replacement_string = "<span class='smth'>Two years in, the company has expanded to 35 cities, five of which are outside the U.S. Plus, in April, ClassPass acquired its main competitor, Fitmob.</span>";
-26607495 0 This is a bug in Unity. You may want to submit a bug report and wait for a patch release to fix it (though you used a preview image, it is also likely to happen on retail Android 5.0).
Edit: I tried on a Nexus Player, and the fonts were rendering just fine. Looks like Google forgot to add some fonts to the preview image. If you are experiencing this issue with a retail version of Android 5.0, please submit a bug for Unity.
-19387031 0You can create a List(Of String) e.g.
Dim arr As New List(Of String) And inside of your loop collect your strings:
arr.Add(CurrentString) After the loop arr would have all the strings. Then you can run a simple LINQ query:
Dim Summary = From a In arr Group By Name = a Into Group _ Select Name, Cnt = Group.Count() This Summary will give you the counts. You can use it for example
For Each elem In Summary 'Output elem.Name 'Output elem.Cnt Next For your example this will produce
Name = "Jane", Cnt = 3 Name = "Matt", Cnt = 4 Name = "Paul", Cnt = 1
-24299268 0 Adding a WCF Service reference in Visual Studio 2013 Following an example about WCF, it seems that in VS 2010 you could right click the references, hit "Add Service Reference", and then hit the "Discover" to get find services in the solution.
This does not work in VS 2013. I have my Service dll, I have a service host, but it will not find any services.
Clean, rebuild, try again -> same outcome.
I'm running VS as an administrator (Win 8 + VS 2013 -> can't run WCF if not admin).
The option of running the service through VS and then adding a reference does not exist (won't allow to add service reference when running), so the only solutions I've found are:
Any ideas what's up?
-12714690 0I sadly do not have the SEO answer to your question, but a solution would be to use a negative margin to hide the element off screen. Then when javascript kick in you set the correct position and hide, then you fade in or do what ever you want to do.
-8637520 0I recently ran some benchmarks to compare ""+myInt vs Integer.toString(myInt).
And the winner is... Integer.toString() ! Because it does not create temporary strings, uses only a adequately-sized char buffer, and some funky algorithms to convert from a digit to its char counterpart.
Here is my blog entry if you read french (or use the sidebar translation widget if you don't) : http://thecodersbreakfast.net/index.php?post/2011/11/15/Au-coeur-du-JDK-performance-des-conversions
-30762999 0Using what you posted, it works fine for me, it produces the red "!" above the textbox. However, I DID remember to set my DataContext, ie.
public MainWindow() { InitializeComponent(); this.DataContext = this; } Without this, it won't work.
-29008772 0 Change JLabel and wait for sometime to exitI want to change the label when I click the button, and then after 3 seconds exit the program. But if I click the button, label does not change. It just exits after 3 seconds. This is my logic
Change the label.
Sleep for 3 seconds
Then exit the program.
btnNewButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("Stopping the program."); state.setText("Bye..."); state.setBackground(SystemColor.textHighlight); doStop(); } }); state = new JLabel("Not listening"); state.setForeground(new Color(255, 255, 255)); state.setBackground(new Color(204, 0, 51)); state.setHorizontalAlignment(SwingConstants.CENTER); state.setBounds(10, 222, 488, 24); state.setOpaque(true); frame.getContentPane().add(state); public void doStop() { try{ Thread.sleep(3000); } catch(InterruptedException e){ } System.exit(0); }
I am trying to check a template type and appropriate invoke a function. However, this doesn't seem to work. I tried with is_same, C++ compile-time type checking, compile-time function for checking type equality and the boost::is_same. Everything is giving me the same error. The following is a sample code.
#include <iostream> #include <type_traits> using namespace std; class Numeric { public : bool isNumeric() { return true; } }; class String { }; template <class T> class Myclass { private: T temp; public: void checkNumeric() { if(std::is_same<T,Numeric>::value) { cout << "is numeric = " << temp.isNumeric(); } else { cout << "is numeric = false" << endl; } } }; int main() { Myclass<Numeric> a; a.checkNumeric(); Myclass<String> b; b.checkNumeric(); } While compiling the above code, I am getting the following error.
make all Building file: ../src/TestCPP.cpp Invoking: GCC C++ Compiler g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/TestCPP.d" -MT"src/TestCPP.d" -o "src/TestCPP.o" "../src/TestCPP.cpp" ../src/TestCPP.cpp:36:36: error: no member named 'isNumeric' in 'String' cout << "is numeric = " << temp.isNumeric(); ~~~~ ^ ../src/TestCPP.cpp:51:4: note: in instantiation of member function 'Myclass<String>::checkNumeric' requested here b.checkNumeric(); ^ 1 error generated. make: *** [src/TestCPP.o] Error 1 In this case, I neither have String or Numeric class. It comes out of a third party library. I implement only MyClass which will be packaged as another library. I expect the application that uses MyClass will either pass me a String or Numeric which belongs to a third party class. MyClass is a specialized matrix operation and Dense/Sparse matrix are the Numeric and String like classes that comes from a third party library. I want to check if the application that uses my library and the third party library is invoking MyClass based on the class type that belongs to the third party library.
Kindly let me know how to fix this problem.
-31827720 0I add this as a response as I can't add long comments. I have checked the .pom files of the maven repository. The main difference between 2.3.2 and 2.4.0/2.5.0 is that 2.4.0/2.5.0 add some exclusions to the dependency:
<exclusions> <exclusion> <artifactId>crashlytics-core</artifactId> <groupId>com.crashlytics.sdk.android</groupId> </exclusion> <exclusion> <artifactId>crashlytics-ndk</artifactId> <groupId>com.crashlytics.sdk.android</groupId> </exclusion> <exclusion> <artifactId>digits</artifactId> <groupId>com.digits.sdk.android</groupId> </exclusion> <exclusion> <artifactId>crashlytics</artifactId> <groupId>com.crashlytics.sdk.android</groupId> </exclusion> <exclusion> <artifactId>beta</artifactId> <groupId>com.crashlytics.sdk.android</groupId> </exclusion> </exclusions>
-29298617 0 Thanks Pradeep. The following code fixed my problem
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack ) { txt_rname.Enabled = false; txt_rmobile.Enabled = false; txt_remail.Enabled = false; con.Open(); // string qry = "select * from Reporter where Reporter_ID= " + DropDownList1.SelectedValue + ""; lbl_1.Text = Session["id"].ToString(); string qry = "select * from Reporter where Reporter_ID= " + Session["id"] + " "; SqlCommand cmd = new SqlCommand(qry, con); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); // table data-> data table con.Close(); txt_rname.Text = dt.Rows[0][1].ToString(); txt_remail.Text = dt.Rows[0][2].ToString(); txt_rmobile.Text = dt.Rows[0][3].ToString(); } else { } }
-392507 0 In Windows Mobile (5/6) SDK, where did windns.h go? According to http://msdn.microsoft.com/en-us/library/aa916070.aspx (DnsQuery_W), DNS query libraries are available on Windows Mobile / CE developers for versions 5.0 onwards. Yet, "#include " gives nasty "file not found" errors. What gives? Strangely enough "dnsapi.lib" is available. Does Microsoft actually expect developers to scavenge the file from somewhere?..
-1040677 0A variety of hacks:
convert to convert your datetime to a string using just the date portionsubstring to chop off the endfloorThe compiler needs to have access to the entire template definition (not just the signature) of addItem in order to generate code for each instantiation of the template, so you need to move its definition to your header i.e follow the inclusion model.
Infact modern C++ compilers do not easily support the separate compilation model for templates.
-15436922 0 get value from child from to parent formi have 2 form in my media player project i have make object of from1 (parent form) and by that get value from form1 in form3. but i also need to get value of a variable from form3 to form1. but the problem is that when i make the object of form3 in form1 like this
Form3 m_child; public Form1(Form3 frm3) { InitializeComponent(); m_child = frm3; } it shows the error in the program.cs that from1 does not contain a constructor that contain 0 argument. i know i have to pass there a parameter in Application.Run(new Form1());
but what i should pass i have no idea. plz help if is there any solution or any other way to get the value from child to parent form.
this is my code for form3 now i want to use value of smileplay, surpriseplay ,sadplay,normalplay,ambiguousplay in form1
Form1 m_parent; public Form3(Form1 frm1) { InitializeComponent(); m_parent = frm1; } private void Form3_Load(object sender, EventArgs e) { WMPLib.IWMPPlaylistArray allplaylist= m_parent.axWindowsMediaPlayer1.playlistCollection.getAll(); for (int litem = 0; litem < allplaylist.count; litem++) { smilecombo.Items.Add( allplaylist.Item(litem).name); surprisecombo.Items.Add(allplaylist.Item(litem).name); sadcombo.Items.Add(allplaylist.Item(litem).name); normalcombo.Items.Add(allplaylist.Item(litem).name); ambiguouscombo.Items.Add(allplaylist.Item(litem).name); } } private void savebtn_Click(object sender, EventArgs e) { WMPLib.IWMPPlaylist smileplay= m_parent.axWindowsMediaPlayer1.playlistCollection.getByName(smilecombo.SelectedItem.ToString()).Item(0); WMPLib.IWMPPlaylist surpriseplay = m_parent.axWindowsMediaPlayer1.playlistCollection.getByName(surprisecombo.SelectedItem.ToString()).Item(0); WMPLib.IWMPPlaylist sadplay = m_parent.axWindowsMediaPlayer1.playlistCollection.getByName(sadcombo.SelectedItem.ToString()).Item(0); WMPLib.IWMPPlaylist normalplay = m_parent.axWindowsMediaPlayer1.playlistCollection.getByName(normalcombo.SelectedItem.ToString()).Item(0); WMPLib.IWMPPlaylist ambiguousplay = m_parent.axWindowsMediaPlayer1.playlistCollection.getByName(ambiguouscombo.SelectedItem.ToString()).Item(0); }
-11319128 0 You could also try:
set rowcount 1000 delete from mytable where id in (select id from ids) set rowcount 0 --reset it when you are done. http://msdn.microsoft.com/en-us/library/ms188774.aspx
-24773795 0 Value from MYSQL is coming nullI am fetching code from codeignitor using implode function. here is the code
$this->load->database(); $session_data = $this->session->userdata('logged_in'); $user_id = $session_data['user_id']; $this->db->select('skill_id'); $this->db->from('user_info_skillset'); $this->db->where('user_id',$user_id); $query = $this->db->get(); foreach($query->result() as $row) { $skill_id[] = $row->skill_id; } $test = implode(',',$skill_id); // echo '<pre />'; // print_r($test); exit; $this->db->select('project_id'); $this->db->from('project'); $this->db->where_in('required_skills',$test); $query1 = $this->db->get(); echo '<pre />'; print_r($query1); exit; return $query1->result(); The problem is i can not able to fetch data for
echo '<pre />'; print_r($query1); exit; return $query1->result(); When i try enter this database query manually in mysql workbench it is working, but by code it displays null value. is that anything missing in code? please guide me. below is my output.
Output
CI_DB_mysql_result Object ( [conn_id] => Resource id #34 [result_id] => Resource id #38 [result_array] => Array ( ) [result_object] => Array ( ) [custom_result_object] => Array ( ) [current_row] => 0 [num_rows] => 0 [row_data] => )
-19923653 0 this may not be the direct answer, but in such "multiple parameter search" situations i just forget about anything and do the simple thing, for ex: Search By Car Manufacturer, CategoryId, MillageMax, Price :
var searchResults = from c in carDb.Cars where (c.Manufacturer.Contains(Manufacturer) || Manufacturer == null) && (c.CategoryId == CategoryId || CategoryId == null) && (c.Millage <= MillageMax || MillageMax== null) && (c.Price <= Price || Price == null) select c now if any of the parameters is null it cancels the containing line by making the whole expression in brackets True and so it does not take a part in search any more
I have various versions of python on a mac OSX 10.6 machine, some of them installed with macports:
> python_select -l Available versions: current none python24 python26 python26-apple python27 The default or system version is python26-apple. I am now using python27, which I selected with
> sudo python_select python27 I recently tried installing django using easy_install, but it got installed with the default python (I can check that by python_selecting python26-apple and importing django). If, instead, I download the django tarball, expand and use
> sudo python setup.py install everything works as expected, i.e. I get django in python 2.7. Now the question is, is there a way to get easy_install to work with the version of python I have selected with python_select?
UPDATE Apparently python_select is deprecated. The following command seems to be equivalent:
port select --list python producing:
Available versions for python: none python24 python26 python26-apple python27 (active)
-7880123 0 I believe you can use the defaultdict in the collections module for this. http://docs.python.org/library/collections.html#collections.defaultdict
I think the examples are pretty close to being exactly what you want.
-11138172 0You can create a class to represent a property. and use a List in your object.
class Property{ enum dataType; //create a specific enum String name; Object value; } If you want to go further then you could inherit from this property to add somme type specialised class like BooleanProperty or StringProperty.
-15986605 0You have to call the function for each of the images.
$(document).ready(function(){ $('img.profilepicture').each(function() { $(this).imgscale({ parent : '.ppparent', fade : 1000 }); }); });
-9631832 0 Defining a Panel and instantiating it in a viewport I am trying to get Ext.define & Ext.create working in Sencha touch 2, so that I can define everything in my library and just create stuff pre-configured.
However, Ext.define is not doing what I would expect it to in anything I've tried.
Why does the following code not create a panel inside the viewport with the field label "Tame"?
Ext.define('mobi.form.Login',{ extend:'Ext.form.Panel', items: [{ xtype: 'textfield', name: 'Tame', label: 'Tame' } ] }); Ext.application({ viewport: { layout:'fit' }, launch: function(){ var form = Ext.create('Ext.form.Panel', { items: [{ xtype: 'textfield', name: 'name', label: 'Name' } ] }); Ext.Viewport.add(Ext.create('mobi.form.Login')); // This doesnt add anything to the viewport Ext.Viewport.add(form); //magically this works } })
-11375476 0 I have found the following link which is like a pseudocode, a guideline of using condition variable. I hope it will greatly help students working on their nachos project or learning pthreads.
https://computing.llnl.gov/tutorials/pthreads/#ConVarOverview
-22369189 0When you add a PhotoImage or other Image object to a Tkinter widget, you must keep your own reference to the image object. If you don’t, the image won’t always show up. Here is essentially what I'm trying to say:
def displayLabel(): photoimage = ImageTk.PhotoImage(file="lena.png") canvas.create_image(0,0, image=photoimage, anchor = NW) canvas.image=photoimage #keep the reference! I learned it from here.
Also you need to remove the parenthesis ()
b3 = Button(tk, text="Display Label", width=30, command= displayLabel) #no parenthesis otherwise it will be called directly without even the button press. You might not have noticed it up until now since Tk was just making the image blank as you may understand now from the link.
Also if you want to send some arguments to displayLabel you need to use lambda. For eg:
b3 = Button(tk, text="Display Label", width=30, command= lambda:displayLabel(args)) In your asked question,you were missing the colon :
My approach on structurizing my website is having a lot of small view files. My controllers look like this
$this->load->view('templates/header'); $this->load->view('templates/navmenu'); $this->load->view('products/create', $dat); $this->load->view('templates/footer'); In CodeIgniter-Google-Maps-V3-API-Library examples controller passes $data variable one view file
$this->load->library('googlemaps'); $this->googlemaps->initialize(); $data['map'] = $this->googlemaps->create_map(); $this->load->view('my_view', $data); where my_view is:
<html> <head><?php echo $map['js']; ?></head> <body><?php echo $map['html']; ?></body> </html> I have been trying to pass JS to my header view but with no success. My controller now:
$this->load->view('templates/header, $data'); $this->load->view('templates/navmenu'); $this->load->view('products/create', $data); $this->load->view('templates/footer'); and header view file:
<html> <head> <title>CodeIgniter Tutorial</title> <link rel = "stylesheet" type = "text/css" href = "<?php echo base_url(); ?>css/style.css"> <?php echo $map['js']; ?></head> <body> Whatever I try to do (have spent a couple of hours) when I inspect the site I see that either JS or html part is not there.
I really liked that I had header.php view file that opened the <body> tag. It is quite easy to mix different methods on one page.
First thing, you should fix up your markup, your nesting is wrong:
<nav> <ul> <li id="menu_toggle">Menu</li> <li><a href="#">Link 01</a></li> <li><a href="#">Link 02</a></li> <li><a href="#">Link 03</a></li> </ul> </nav> And change your CSS to something like this:
nav li { display: none; } nav.open li, nav:hover li, #menu_toggle { display: block; } This means all your list items are invisible, but for the toggle and if the nav has a class open, or if the mouse hovers the nav (on a desktop).
Then your JavaScript (jQuery) could look like this:
$(function(){ // document ready $('#menu_toggle').on('touchstart', function(){ $('nav').toggleClass('open'); }); }); This will toggle the menu on a touch device when hover isn't really working.
Tracking a touch anywhere else but the menu is a bit trickier, you could:
So for option 1, assuming you have something like this:
<nav>...</nav> <div id="content">...</div> You could do this:
$(function(){ // document ready var isMenuOpen = false; $('#menu_toggle').on('touchstart', function(){ // reverse boolean isMenuOpen = !isMenuOpen; // add/remove class depending on state $('nav').toggleClass('open', isMenuOpen); if( isMenuOpen ){ // If menu is now open, add a closing event handler to the content $('#content').once('touchstart', function(){ $('nav').removeClass('open'); }); } }); });
-16220532 0 This seems to work: http://jsfiddle.net/QLn9b/1/
It is using your original code:
$("select").change(function() { $("select").not(this).find("option[value="+ $(this).val() + "]").attr('disabled', true); });
-2428589 0 <script type="text/javascript"> function voimakaksikkoStats(obj) { alert(obj.TestsTaken); } </script> <script type="text/javascript" src="http://www.heiaheia.com/voimakaksikko/stats.json"></script> I never got it working with jQuery, but the simple code above solved my problems. I found help from Yahoo: http://developer.yahoo.com/common/json.html
-33240205 1 Pass list of different named tuples to different csv by tuple nameI have a program in which I wish to record all major changes that occur. For example: each time a variable x changes in value record the time of the change and the change itself. Within the program there are many such changes and not all have the same number of parameters.
I decided to use namedtuples to store each instance of a change and to then put those namedtuples into a single master data list -ready for export to csv. I have used tuples as of course they are immutable which is ideal for record keeping. Below I have tried to explain in as concise a manner as possible what I have done and tried. Hopefully my problem and attempts so far are clear.
So I have:
data = [] as the main repository, with namedtuples of the form:
a_tuple = namedtuple('x_change', ['Time', 'Change']) another_tuple = namedtuple('y_change', ['Time', 'Change', 'id']) I can then append instances of these namedtuples each time a change is detected to data using commands as below:
data.append(a_tuple(a_time, a_change)) data.append(another_tuple(a_time, a_change, an_id)) If I then print out the contents of data I would get output like:
x_change(a_time=4, a_change=1) y_change(a_time=5, a_change=3, an_id = 2) y_change(a_time=7, a_change=1, an_id = 3) x_change(a_time=8, a_change=3) what I would like to do is export these tuples to csv files by tuple name. So in the above case I would end up with two csv files of the form:
name, time, change x_change, 4, 1 x_change, 8, 3 and;
name, time, change, id y_change, 5, 3, 2 y_change, 7, 1, 3 I have to date managed to write to a single csv as below:
with open ('events.csv', 'w', newline='') as csvfile: output = csv.writer(csvfile, delimiter = ',') for row in data: output.writerow(row) which produces the output minus the tuple name. So:
4, 1 5, 3, 2 7, 1, 3 8, 3 I have also tried:
with open ('events.csv', 'w', newline='') as csvfile: output = csv.writer(csvfile, delimiter = ',') for row in data: output.writerow(str(row)) Which splits the file into csv format, including the tuple name, by every character getting (first line only included):
x, _, c, h, a, n, g, e, 4, 1 I have searched for a solution but not come across anything that fits what I am trying to do and am now at a loss. Any assistance would be appreciated.
-35759859 0If I assume that the values are unique in each column, then the key idea is doing a join on the second column in the table followed by aggregation.
A having clause can count the number of matches and be sure that it matches the expected number in the first table:
select t1.c1, t2.c1 from t1 join t2 on t1.c2 = t2.c2 group by t1.c1, t2.c1 having count(*) = (select count(*) from t1 tt1 where tt1.c1 = t1.c1);
-25691983 0 The reason why you are getting different results is the fact that your colour segmentation algorithm uses k-means clustering. I'm going to assume you don't know what this is as someone familiar in how it works would instantly tell you that this is why you're getting different results every time. In fact, the different results you are getting after you run this code each time are a natural consequence to k-means clustering, and I'll explain why.
How it works is that for some data that you have, you want to group them into k groups. You initially choose k random points in your data, and these will have labels from 1,2,...,k. These are what we call the centroids. Then, you determine how close the rest of the data are to each of these points. You then group those points so that whichever points are closest to any of these k points, you assign those points to belong to that particular group (1,2,...,k). After, for all of the points for each group, you update the centroids, which actually is defined as the representative point for each group. For each group, you compute the average of all of the points in each of the k groups. These become the new centroids for the next iteration. In the next iteration, you determine how close each point in your data is to each of the centroids. You keep iterating and repeating this behaviour until the centroids don't move anymore, or they move very little.
How this applies to the above code is that you are taking the image and you want to represent the image using only k possible colours. Each of these possible colours would thus be a centroid. Once you find which cluster each pixel belongs to, you would replace the pixel's colour with the centroid of the cluster that pixel belongs to. Therefore, for each colour pixel in your image, you want to decide which out of the k possible colours this pixel would be best represented with. The reason why this is a colour segmentation is because you are segmenting the image to belong to only k possible colours. This, in a more general sense, is what is called unsupervised segmentation.
Now, back to k-means. How you choose the initial centroids is the reason why you are getting different results. You are calling k-means in the default way, which automatically determines which initial points the algorithm will choose from. Because of this, you are not guaranteed to generate the same initial points each time you call the algorithm. If you want to repeat the same segmentation no matter how many times you call kmeans, you will need to specify the initial points yourself. As such, you would need to modify the k-means call so that it looks like this:
[cluster_idx, cluster_center] = kmeans(ab,nColors,'distance','sqEuclidean', ... 'Replicates', 3, 'start', seeds); Note that the call is the same, but we have added two additional parameters to the k-means call. The flag start means that you are specifying the initial points, and seeds is a k x p array where k is how many groups you want. In this case, this is the same as nColors, which is 3. p is the dimension of your data. Because of the way you are transforming and reshaping your data, this is going to be 2. As such, you are ultimately specifying a 3 x 2 matrix. However, you have a Replicate flag there. This means that the k-means algorithm will run a certain number of times specified by you, and it will output the segmentation that has the least amount of error. As such, we will repeat the kmeans calls for as many times as specified with this flag. The above structure of seeds will no longer be k x p but k x p x n, where n is the number of times you want to run the segmentation. This is now a 3D matrix, where each 2D slice determines the initial points for each run of the algorithm. Keep this in mind for later.
How you choose these points is up to you. However, if you want to randomly choose these and not leave it up to you, but want to reproduce the same results every time you call this function, you should set the random seed generator to be a known number, like 123. That way, when you generate random points, it will always generate the same sequence of points, and is thus reproducible. Therefore, I would add this to your code before calling kmeans.
rng(123); %// Set seed for reproducibility numReplicates = 3; ind = randperm(size(ab,1), numReplicates*nColors); %// Randomly choose nColors colours from data %// We are also repeating the experiment numReplicates times %// Make a 3D matrix where each slice denotes the initial centres for each iteration seeds = permute(reshape(ab(ind,:).', [2 nColors numReplicates]), [2 1 3]); %// Now call kmeans [cluster_idx, cluster_center] = kmeans(ab,nColors,'distance','sqEuclidean', ... 'Replicates', numReplicates, 'start', seeds); Bear in mind that you specified the Replicates flag, and we want to repeat this algorithm a certain number of times. This is 3. Therefore, what we need to do is specify initial points for each run of the algorithm. Because we are going to have 3 clusters of points, and we are going to run this algorithm 3 times, we need 9 initial points (or nColors * numReplicates) in total. Each set of initial points has to be a slice in a 3D array, which is why you see that complicated statement just before the kmeans call.
I made the number of replicates as a variable so that you can change this and to your heart's content and it'll still work. The complicated statement with permute and reshape allows us to create this 3D matrix of points very easily.
Bear in mind that the call to randperm in MATLAB only accepted the second parameter as of recently. If the above call to randperm doesn't work, do this instead:
rng(123); %// Set seed for reproducibility numReplicates = 3; ind = randperm(size(ab,1)); %// Randomly choose nColors colours from data ind = ind(1:numReplicates*nColors); %// We are also repeating the experiment numReplicates times %// Make a 3D matrix where each slice denotes the initial centres for each iteration seeds = permute(reshape(ab(ind,:).', [2 nColors numReplicates]), [2 1 3]); %// Now call kmeans [cluster_idx, cluster_center] = kmeans(ab,nColors,'distance','sqEuclidean', ... 'Replicates', numReplicates, 'start', seeds); Now with the above code, you should be able to generate the same colour segmentation results every time.
Good luck!
-4567218 0 C#:SerialPort: read and write buffer sizeI am writing a program to send and receive data via a serial port with C#.
Although I have read this reference: http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readbuffersize.aspx, I am not quite clear if I change the values of the buffer for reading and writing:
serialPort.ReadBufferSize = 1; // or 1024 ? serialPort.WriteBufferSize = 1;// or 1024 ? The values (1 or 1024) should be better to be smaller or bigger?
Thanks in advance.
-32706267 0There is only 1 IFRAME on the page so you can just find it by tag name. The page loaded very slowly for me but I'm in the US so that may have something to do with it. You may have to wait for the IFRAME to become available and then get a handle to it.
For an immutable flavour, Iterator does the job.
val x = Iterator.fill(100000)(someFn) Now I want to implement a mutable version of Iterator, with three guarantees:
fold, foldLeft, ..) and appendIterator should be destroyed.Is there an existing implementation to give me these guarantees? Any library or framework example would be great.
Update
To illustrate the desired behaviour.
class SomeThing {} class Test(val list: Iterator[SomeThing]) { def add(thing: SomeThing): Test = { new Test(list ++ Iterator(thing)) } } (new Test()).add(new SomeThing).add(new SomeThing); In this example, SomeThing is an expensive construct, it needs to be lazy.
Re-iterating over list is never required, Iterator is a good fit.
This is supposed to asynchronously and lazily sequence 10 million SomeThing instances without depleting the executor(a cached thread pool executor) or running out of memory.
Since selectedItem is an observable, you need to invoke it for accessing/changing it's data.
Try this:
<input type="text" id="textBoxAddressLine1" name="textBoxAddressLine1Name" data-bind="value: selectedItem() ? selectedItem().AddressLine1 : ''" /> And in your ViewModel:
selectItem: function(data) { this.selectedItem(data); }
-22312293 0 If I understand you correctly URL rewriting is not what you need. Why? Because mapping an external URL to some internal URL / alias is not going to help you serve the file.
What you need is a way to have an external URL process a request and return the file in question. Luckily Drupal 7 makes this pretty easy to do.
1.) Define a menu mapping in hook_menu()
function MODULE_menu() { $items = array(); $items['pdf'] = array( 'title' => 'Map PDF', 'page callback' => 'MODULE_show_pdf', 'access callback' => TRUE, 'description' => 'TBD', 'type' => MENU_CALLBACK, ); return ($items); } 2.) Define your callback function
function MODULE_show_pdf($somehtmlfile = '') { $stream_wrapper_uri = 'public://pdf/' . $somehtmlfile . '.pdf'; $stream_wrapper = file_create_url($stream_wrapper_uri); $stream_headers = array( 'Content-Type' => file_get_mimetype($stream_wrapper_uri), 'Content-Length' => filesize($stream_wrapper_uri), 'Pragma' => 'no-cache', 'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0', 'Expires' => '0', 'Accept-Ranges' => 'bytes' ); file_transfer($stream_wrapper_uri, $stream_headers); } Some things to note:
There is no need to explicitly define somehtmlfile param in the menu. This allows you more flexibility in that you can simply define whatever params you would like this external URL to support simply by adjusting the params in the callback function.
When public stream wrapper dirs/files are sub-dir of: sites/default/files
It is assumed that although you have somehtmlfile in the URL that you really want to stream somehtmlfile.pdf (if you want to stream somehtmlfile.html then simply adjust the hard coded '.pdf' suffix)
file_transfer calls drupal_exit() as its last step which essentially ends request processing.
Make sure to flush your cache otherwise the above will not work as menu entries are cached and the external URL will fail to be found
View.OnClickListener is an interface which you need to implement when you want to handle click events. In your code, you are doing that by doing new View.OnClickListener(). Here you are actually creating an anonymous class that implements View.OnClickListener. And any class that implements View.OnClickListener must also implement all the methods declared in it (e.g. the onClick method). Also, in public void onClick(View v) {..}, the View v denotes the view or the button that was clicked so that you can perform whatever you want with it. For example, get it's id, change it's color etc.
I have a code for Visual Basic programming language that reads byte array from files, I use that code:
Imports System.IO Imports System.Threading Public Class Form1 Dim thread As New Thread(AddressOf RW_EXE) Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click With OpenFileDialog1 If .ShowDialog() = Windows.Forms.DialogResult.OK Then thread.IsBackground = True Control.CheckForIllegalCrossThreadCalls = False thread.Start() End If End With End Sub Sub RW_EXE() RichTextBox1.Text = "" Dim FS As New FileStream(OpenFileDialog1.FileName, FileMode.Open, FileAccess.Read) Dim BS As New BinaryReader(FS) Dim x As Integer = BS.BaseStream.Position Dim y As Integer = BS.BaseStream.Length Dim s As String = "" ProgressBar3.Maximum = y While x < y RichTextBox1.Text &= BS.ReadByte.ToString("X") & " " ProgressBar3.Value = x x += 10 End While RichTextBox1.Text = s FS.Close() BS.Close() thread.Abort() End Sub That code does it's job well, but I have one problem, It's very slow, it takes big time to read array bytes from files with size of 100 KB and from bigger files.
Please, help.
Thanks for attention.
-29665446 0You can change the hostname value for key IdentityProviderSSOServiceURL in repository/conf/security/authenticators.xml file.
I have a nexus running Lollipop and I tried to use the new options available to screenrecord,
I used
adb shell screenrecord --o raw-frames --bit-rate 4000000 /sdcard/output.raw And the framerate went for a toss, the device became really sluggish, but If I use the default mp4 format it's actually faster.
Technically If I save the trouble of encoding shouldn't device performance be snappier? Am I doing something wrong?
-20683123 0Make sure to use these commands in viewdidload [RMMapView class]; mapView.contents.tileSource = [[RMOpenStreetMapSource alloc] init];
-31859432 0 allow people to only alter certain values in an input JavaSciptI have the following code
<input id="startDate "type="text" name="courseDate" value="MM/YYYY" /> I was wondering how I could use JavaScript to ensure that a user can only edit the "MM" and "YYYY" in the textbox.
Thanks Y
-22659877 0 Form submit to another page and then review or write to a fileI have a script that users can submit certain data, and after a submit they can "review" the output and go back to previous page or submit to it again and there is my proble, the submitted page: How can I submit it again to write it to a file?
form.html
<form method="post" action="vaihe2.php"> <input name="laskuttaja" type="text" value="Nimi" size="25"> <input name="submit" type="submit" value="Lähetä" /> </form> vaihe2.php
<? $laskuttaja = $_POST['laskuttaja']; $data = '<B>'.$laskuttaja.'</b>'; echo $data; ?> So how can I post that $data to next page(vaihe3.php) with submit and let the script write it to a file. I know how php write file works but the post to third page is not working.
-15528594 0 My View Controller gets deallocated when the app goes to the backgroundMy View Controller class gets deallocated when the app goes to the background. I'm using ARC.
I have a UIViewController that subscribes to a notifications when the app becomes active and executes a method. But once the app is about 30 secs in the background and then resumes, the app crashes with "message sent to deallocated instance".
Enabling Zombie objects shows that the View Controller itself is the Zombie.
Thank you!
Instantiation of my view controller (in AppDelegate):
UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil]; MyViewController *myViewController = [storyBoard instantiateViewControllerWithIdentifier:@"MyViewController"]; The foreground notification in AppDelegate:
- (void)applicationDidBecomeActive:(UIApplication *)application { [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationForegrounded object:self]; } The foreground notification in the view controller:
- (void)viewDidLoad { [super viewDidLoad]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resumeForeground) name:kNotificationForegrounded object:nil]; } I tried creating a strong reference in the AppDelegate, but the view controller still gets deallocated:
@property (strong, nonatomic) MyViewController *myViewController; I tried adding the view controller to an array and have a strong reference to the array in the AppDelegae, but still I get the same results:
@property (strong, nonatomic) NSMutableArray *viewControllers; //... UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil]; MyViewController *myViewController = [storyBoard instantiateViewControllerWithIdentifier:@"MyViewController"]; self.viewControllers = [[NSMutableArray alloc] init]; [self.viewControllers addObject:myViewController];
-2182911 0 It's easy to know what to charge your customer. This is alway the biggest problems for us, because we don't know the scope of the project we can't give the customer a fixed price, and most customers demands a fixed price.
-15598057 0OK I found it,
The error was the ColumnSeries was missing the Title attribute, like this:
<charting:Chart Name="columnChart" Grid.Row="1" Grid.Column="1" Width="400" Height="400"> <charting:Chart.Series> <charting:ColumnSeries Title="Chart Title" ItemsSource="{Binding items}" IndependentValueBinding="{Binding Name}" DependentValueBinding="{Binding Value}" IsSelectionEnabled="True"> </charting:ColumnSeries> </charting:Chart.Series> </charting:Chart> It seems that the Title attribute is mandatory.
-33296297 0I think that what you are looking for are class-based helpers. You might have trouble with the resetting of the value, so keep an eye open for alternative solutions.
-37907423 1 Pickle Trained Classifier Only Return 1 Predicted Label to All Test DataI'm having trouble about pickle trained classifier. I pickled a classifier that I trained using 8000 training tweets. each tweet has been labeled with 1 out of 4 labels (Health, Music, Sport and Technology) when I tried using the pickle trained classifier in new tweets for testing, it return only 1 out of 4 labels to all of new tweets. new tweets are tweets I stream directly from Twitter using Tweepy.
here's the code I use to pickle the trained classifier using 8000 tweets for training that stored in database:
#set precision for numpy np.set_printoptions(precision=1) #get data from MySQL table using pandas engine = create_engine('mysql+mysqlconnector://root:root@localhost:3306/thesisdb?charset=utf8mb4') ttweets = pd.read_sql_query('SELECT label_id, tweet FROM training_tweets', engine) #text preprocessing (remove HTML markup, remove punctuation, tokenizing, remove stop words and stemming) using NLTK def Preprocessing(pptweets): pptweets = pptweets.lower() removeurl = re.sub(r'https:.*$',":", pptweets) removepunc = removeurl.replace("_", " ") tokenizer = RegexpTokenizer(r'\w+') tokenizetweets = tokenizer.tokenize(removepunc) removesw = [w for w in tokenizetweets if not w in stopwords.words('english')] stemmer = SnowballStemmer("english") stemmedtweets = [stemmer.stem(tokenizetweets) for tokenizetweets in removesw] return " ".join(stemmedtweets) #initialize an empty variable to hold the preprocessed tweets cleantweets = [] #loop over each tweet for i in range(0, len(ttweets["tweet"])): cleantweets.append(Preprocessing(ttweets["tweet"][i])) #text feature extraction using Bag of Words vectorizer = CountVectorizer(analyzer="word", tokenizer=None, preprocessor=None, stop_words=None, max_features=5000) #use fit_transform() to fit the model and learn the vocabulary as well as transform the training data into feature vectors traintweetsfeatures = vectorizer.fit_transform(cleantweets) #convert the result to array using Numpy traintweetsfeatures = traintweetsfeatures.toarray() #create a Logistic Regression classifier variable and train it using the training tweets clfr = LogisticRegression() x_train, y_train = traintweetsfeatures, ttweets["label_id"] clfr.fit(x_train, y_train) #save trained classifier in pkl file if os.path.exists(dest): os.remove(classifiername) os.remove(vectorizername) pickle.dump(clfr, open(os.path.join(dest, 'clfr.pickle'), 'wb'), protocol=2) pickle.dump(vectorizer, open(os.path.join(dest, 'vectorizer.pickle'), 'wb'), protocol=2) else: os.makedirs(dest) pickle.dump(clfr, open(os.path.join(dest, 'clfr.pickle'), 'wb'), protocol=2) pickle.dump(vectorizer, open(os.path.join(dest, 'vectorizer.pickle'), 'wb'), protocol=2) and below is the code to use pickle trained classifier for predicting label of new tweets:
if request.method == 'POST': auth = OAuthHandler(ckey, csecret) auth.set_access_token(atoken, asecret) api = tweepy.API(auth) getlabelid = Label.query.filter_by(label_id=request.form['label']).first() getlabelname = getlabelid.label_name number = int(request.form['number']) def Preprocessing(pptweets): pptweets = pptweets.lower() removeurl = re.sub(r'https:.*$',":", pptweets) removepunc = removeurl.replace("_", " ") tokenizer = RegexpTokenizer(r'\w+') tokenizetweets = tokenizer.tokenize(removepunc) removesw = [w for w in tokenizetweets if not w in stopwords.words('english')] stemmer = SnowballStemmer("english") stemmedtweets = [stemmer.stem(tokenizetweets) for tokenizetweets in removesw] return " ".join(stemmedtweets) class listener(StreamListener): def __init__(self, api=None): self.api = api or API() self.n = 0 self.m = number def on_data(self, data): all_data = json.loads(data) tweet = all_data["text"] username = all_data["user"]["screen_name"] getlabelid = Label.query.filter_by(label_id=request.form['label']).first() getlabelname = getlabelid.label_name #initialize an empty variable to hold the preprocessed tweets cleantesttweet = Preprocessing(tweet) #load trained classifier & bag of words dest = os.path.join('classifier', 'pkl_objects') clfr = pickle.load(open(os.path.join(dest, 'clfr.pickle'), 'rb')) vectorizer = pickle.load(open(os.path.join(dest, 'vectorizer.pickle'), 'rb')) #predict test tweet label testtweetfeatures = vectorizer.transform(cleantesttweet) result = clfr.predict(testtweetfeatures) #result = 1 ttweets = TestingTweets(label_id=result, tweet_username=username, tweet=tweet) try: db.session.add(ttweets) db.session.commit() # Increment the counter here, as we've truly successfully # stored a tweet. self.n += 1 except IntegrityError: db.session.rollback() except tweepy.error.TweepError: return False # Don't stop the stream, just ignore the duplicate. # print("Duplicate entry detected!") if self.n >= self.m: #print("Successfully stored", self.m, "tweets into database") # Cross the... stop the stream. return False else: # Keep the stream going. return True def on_error(self, status): print(status) auth = OAuthHandler(ckey, csecret) auth.set_access_token(atoken, asecret) twitterStream = Stream(auth, listener()) twitterStream.filter(track=[getlabelname], languages=["en"]) label = Label.query.all() tetweet = TestingTweets.query.order_by(TestingTweets.tweet_id.desc()) return render_template('testtweets.html', labels=label, tetweets=tetweet) does anyone can help me solve this problem?
-19674209 0 Clean rubbish Autofac configurations?Just wondering whether there is a good way to find out rubbish configurations in Autofac modules. I mean, while the project is growing bigger and bigger with lots of refactoring done, there could be some classes become unused but they are still registered in the module configurations. Those rubbish classes could get hidden from Reshaper because it is used in the configuration code. I just don't like to go through every line in the configuration code to find whether an interface or class is never used any more and delete them manually.
Would be nice if there is good idea to find out all those rubbish automatically. Please throw in your brilliant thoughts. Thanks.
-31067817 0It is a bad idea, but if you change the private variable to a public one, you will achieve your goal. You probably should declare the variable as final as well to avoid surprises, but it is not strictly necessary, and doesn't make it a good idea (IMO).
For what it is worth, there is no way to implement a singleton that doesn't involve an explicit variable to hold the instance, or an enum.
Here is what Bloch has to say on the tradeoff between the public and private variable approaches:
"One advantage of the factory-method approach is that it gives you the flexibility to change your mind about whether the class should be a singleton without changing its API. The factory method returns the sole instance but could easily be modified to return, say, a unique instance for each thread that invokes it. A second advantage, concerning generic types, is discussed in Item 27. Often neither of these advantages is relevant, and the final-field approach is simpler."
My argument is that knowing that you won't need to change your mind in the future involves a degree of prescience.
Or to put it another way, you can't know that: you can only predict that. And your prediction can be wrong. And if that prediction does turn out to be wrong, then you have to change every piece of code the accesses the singleton via the public variable.
Now if your codebase is small, then the amount of code you need to change is limited. However, if your codebase is large, or if it is not all yours to change, then this this kind of of mistake can have serious consequences.
That is why it is a bad idea.
-6354196 0 how to divide QGridLayout into rows and columns at Design Time in QT?how to divide QGridLayout into rows and columns at Design Time in QT ?
I want to design one form where i want to have 2 columns and 7 rows . I am designing using QTCreator but i am not getting any option of giving rows/columns.
It shows only these properties

If I understood it correctly you want to reference the fragment created by heat ($(TargetDir)$(ProjectName).wxs) in your generic WiX source file?
If this is the case you just have to add a ComponentGroupRef-tag below your Feature-element (instead of a ComponentRef-element you would use normally). As Id for the elemenet you have to use the name of the ComponentGroup that you used in the heat-commandline, harvestedComponents in your example. E.g.
<Feature Id="MyFeature" ...> ... <ComponentRef Id="aNormalComponentFromTheCurrentFile" ... /> ... <ComponentGroupRef Id="harvestedComponents" /> </Feature> Or did I miss the point?
-6031856 0Okay I thought it all over.. and basically if i do understand correct you want the sum for each distinct set.
So not 34 + 34 + 34 + 23 + 23 + 23 + 43 + 43 + 43 ... BUT 34 + 23 + 43
In order to that you need to trick MySQL with the following query :
SELECT SUM(tot.invalid_votes) AS total FROM (SELECT DISTINCT QV, invalid_votes FROM `results`) tot This will return the SUM of the Distinct values based on QV field.
Table :
QV invalid_votes 0544 5 0544 5 0544 5 0545 6 0545 6 based on the database information you provided i get the following result 11
-38124033 0Should use GCM high-priority messages to wake the app and access the network. Example of High priority GCM message:-
{ "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...", "priority" : "high", "notification" : { "body" : "This week’s edition is now available.", "title" : "NewsMagazine.com", "icon" : "new", }, "data" : { "volume" : "3.21.15", "contents" : "http://www.news-magazine.com/world-week/21659772" } } See the "priority" key has value "high", this will awake the device and gcm message will be delivered instantly and it wont crash.
Check this out for more information https://developer.android.com/training/monitoring-device-state/doze-standby.html#whitelisting-cases
-16003170 0First, you never want to do default initializations in calling code, you can create a constructor for your struct and do it there:
struct Neuron { Neuron() : activation(0.0), bias(0.0), incomingWeights(0) {} double activation; double bias; double *incomingWeights; }; Then (since this is C++)
for (int i = 0; i < din; i++) { ann.inputLayer[i] = new Neuron[din]; You should use new over malloc in C++, though if you ever did need malloc your statement would need to be fixed, to:
ann.inputLayer = (Neuron*)malloc(din * sizeof(Neuron));
-12777200 0 Weird issue when looping using the Do While in C I'm running into a weird issue when I try and move my Do loop, or add another loop to nest it. I place the DO where you see it below, it loops through fine:
{ float numbers[MAX_DATA]; printf("Please Eneter the Amount of Numbers You Would Like to Use\n"); scanf("%d",&amount); if (amount>MAX_DATA) { printf("Your entry was too big"); } else { input(numbers,amount); do { printf("\nStatistical Calculator Menu\n"); printf("\n(1) Mean\n(2) Standard Deviation\n(3) Range\n(4) Restart/Exit\n"); scanf("%d",&input2); if (input2==1) { mean(numbers,amount); } else if (input2==2) { standard(numbers,amount); } else if (input2==3) { range(numbers,amount); } else if(input2==4) { printf("Would You Like to (5)Restart or (6)Quit?"); scanf("%d",&input2); } } while(input2!=4); } getch(); return 0; } But if I place it here or add an additional do loop to nest it, I get a "expect while before getch" error.
{ int amount=0; int input2; do { float numbers[MAX_DATA]; printf("Please Eneter the Amount of Numbers You Would Like to Use\n"); scanf("%d",&amount); if (amount>MAX_DATA) { printf("Your entry was too big"); } else { input(numbers,amount); printf("\nStatistical Calculator Menu\n"); printf("\n(1) Mean\n(2) Standard Deviation\n(3) Range\n(4) Restart/Exit\n"); scanf("%d",&input2); if (input2==1) { mean(numbers,amount); } else if (input2==2) { standard(numbers,amount); } else if (input2==3) { range(numbers,amount); } else if(input2==4) { printf("Would You Like to (5)Restart or (6)Quit?"); scanf("%d",&input2); } } while(input2!=4); } getch(); return 0; } Why do I get this error?
-38683420 0 Show hide marker using circle points openlayers 3How to show hide markers (P icon) using circle points (something like point1.distanceTo(point2))
need to show markers If markers comes inside the circle another hide it (currently changing circle radius through slider)
// we change this on input change var radius = 10; longitude = 400000; latitude = 300000; var styleFunction = function() { return new ol.style.Style({ image: new ol.style.Circle({ radius: radius, stroke: new ol.style.Stroke({ color: [51, 51, 51], width: 2 }), fill: new ol.style.Fill({ color: [51, 51, 51, .3] }) }) }); }; var update = function(value) { // $('#range').val() = value; radius = value; vectorLayer.setStyle(styleFunction); // $('#range').val(value) // document.getElementById('range').value=value; } var feature = new ol.Feature(new ol.geom.Point([longitude, latitude])); var vectorLayer = new ol.layer.Vector({ source: new ol.source.Vector({ features: [feature] }), style: styleFunction }); var rasterLayer = new ol.layer.Tile({ source: new ol.source.TileJSON({ url: 'http://api.tiles.mapbox.com/v3/mapbox.geography-class.json', crossOrigin: '' }) }); // icon marker start here var iconFeature5 = new ol.Feature({ geometry: new ol.geom.Point([longitude, latitude]), name: 'Missing Person', population: 4000, rainfall: 500 }); var vectorSource5 = new ol.source.Vector({ features: [iconFeature5] }); var vectorLayer5 = new ol.layer.Vector({ source: vectorSource5 }); var iconStyle5 = new ol.style.Style({ image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({ anchor: [0.5, 46], anchorXUnits: 'fraction', anchorYUnits: 'pixels', src: 'https://cloud.githubusercontent.com/assets/41094/2833021/7279fac0-cfcb-11e3-9789-24436486a8b1.png' })) }); iconFeature5.setStyle(iconStyle5); // 2nd marker longitude1 = 100000; latitude1 = 100000; var iconFeature1 = new ol.Feature({ geometry: new ol.geom.Point([longitude1, latitude1]), name: 'Missing Person', population: 4000, rainfall: 500 }); var vectorSource1 = new ol.source.Vector({ features: [iconFeature1] }); var vectorLayer1 = new ol.layer.Vector({ source: vectorSource1 }); iconFeature1.setStyle(iconStyle5); var map = new ol.Map({ layers: [rasterLayer,vectorLayer,vectorLayer5,vectorLayer1], target: document.getElementById('map'), view: new ol.View({ center: [400000, 400000], zoom: 4 }) }); html, body, #map { height: 100%; overflow: hidden; } .input { margin: 5px 0; } <script src="http://openlayers.org/en/v3.16.0/build/ol.js"></script> <div class="input"> <input type="range" id="range" min="10" max="50" onchange="update(this.value)"> <input type="text" id="range" value="10"> </div> <div id="map" class="map"></div> Possible Duplicate:
How to Trigger the soft keyboard?
Any one please help me to display a keyboard in my app. I want to show my keyboard when i click on the textfield
-1023073 0You can save keystrokes by holding the Ctrl key and using the arrow keys. Instead of moving one character, it moves one word at a time. This also works when backspacing. So Ctrl-Backspace will delete the entire word instead of just the last character.
-26373691 0Turns out I can't upload images to heroku.
I have decided to use cloudinary for the time being.
I will probably switch to S3 eventually.
-26743684 0Did you want just the current domain, or the domain with parent domains included?
Current Domain Name:
Import-Module ActiveDirectory $name = Get-ADDomain | Select -ExpandProperty NetBIOSName Get-ADObject -Filter 'objectclass -eq "user"' -Properties CN,DisplayName,Discription | select | Export-Csv -NoTypeInformation "c:\" + $name + ".csv"
-39687070 0 id3js in giving RangeError: Offset is outside the bounds of the DataView I'm trying to move bulk mp3 files from one directory to other directory and renaming them on the basis of their name/title/album name. I'm using id3js for finding its id3 values:
My code snippet as follows:
let files = []; let walker = walk.walk(arg['search'], { followLinks: false }); walker.on('file', (root, stat, next)=>{ if(!strReg.test(""+root)) { let typ = stat.name.split("."); if (stat.name.substring(stat.name.lastIndexOf(".")) == '.mp3') { files.push({nm:stat.name,pth:root + ""+path.sep + stat.name}); } } next(); }); walker.on('end', function() { console.log("files are: ",files); files.forEach((o, i)=> { console.log((i/files.length*100),"% done and Working on :",o.nm); try { id3({file: o.pth, type: id3.OPEN_LOCAL}, function (err, tags) { let itsNm; if (o.nm.indexOf(".com") == -1 && o.nm.indexOf(".in") == -1) { itsNm = o.nm.substring(0, o.nm.lastIndexOf(".")).replace(/[^A-Za-z ]+/gi, '').trim(); } else if (tags.title && tags.title.indexOf(".com") == -1 && tags.title.indexOf(".in") == -1) { itsNm = tags.title.substring(0, tags.title.lastIndexOf(".")).replace(/[^A-Za-z ]+/gi, '').trim(); } else if (tags.album && tags.album.indexOf(".com") == -1 && tags.album.indexOf(".in") == -1) { itsNm = tags.album .substring(0, tags.album .lastIndexOf(".")).replace(/[^A-Za-z ]+/gi, '').trim(); } else { itsNm = o.nm.substring(0, o.nm.lastIndexOf(".")).replace(/[^A-Za-z ]+/gi, '').trim(); } fs.createReadStream(o.pth) .pipe(fs.createWriteStream(path.join(arg["out"], itsNm + o.nm.substring(o.nm.lastIndexOf("."))))); }); } catch (e){ console.log(e); } }); }) But it gives following error:
frameBit = dv.getUint8(position + i); ^ RangeError: Offset is outside the bounds of the DataView at DataView.getUint8 (native) at D:\projBulderMac\node_modules\id3js\dist\id3.js:928:22 at D:\projBulderMac\node_modules\id3js\dist\id3.js:118:4 at FSReqWrap.wrapper [as oncomplete] (fs.js:576:17)
-26140875 0 It's really difficult to guess what's the issue there without more complete example. One thing that could be the reason is empty cells which are collapsing. Also I've moved the innerHTML to html variable which is appended just once..
to compensate that try this code which is adding a non breaking space to empty cells:
var Htmltable = document.getElementById('table'); var day = 1; var html = ''; for(i = 1; i <= 6; i++){ //weeks in a month (rows) html += '<tr>'; for(j = 0; j <= 6; j++){ //7 days in a week (coloumns) html += '<td>'; if(day <= wca.totDayInMonth){ html += day; day++; } else { html += " "; } html += '</td>'; } //if day > totDayMonth - stop making line html += '</tr>'; } Htmltable.innerHTML += html;
-38550170 0 The text is only showing up in white when you hover over the link tage: <a>, not the whole list item <li>.
I think a better way to fix this is to make the link a block element, filling the whole list item space. If people hover anywhere over the list, they'll not only see the text in white, they'll also be able to click anywhere on the item.
Here's a rework:
#menu { margin-top: 10px; } #menu li { list-style:none; } #menu li a { font-family: 'Open Sans', sans-serif; font-weight: 400; font-size: 13px; padding:5px; text-decoration: none; line-height: 22px; width: 100%; color: #565656; border-bottom: 1px solid #e1e1e1; display:block; } #menu li a:hover { background-color: #c0392b; color: #FFF; } <ul id="menu"> <li><a href="#">Strona główna</a></li> <li><a href="#">Historia szkoły</a></li> <li><a href="#">Absolwenci</a></li> <li><a href="#">Dokumenty szkoły</a></li> <li><a href="#">Ewaluacja wewnętrzna</a></li> <li><a href="#">Zasady rekrutacji</a></li> <li><a href="#">Nauczyciele</a></li> <li><a href="#">Samorząd Uczniowski</a></li> <li><a href="#">Rada Rodziców</a></li> <li><a href="#">Kierunki i wychowawcy klas</a></li> <li><a href="#">Kalendarz roku szkolnego</a></li> <li><a href="#">Profilaktyka</a></li> <li><a href="#">Kalendarz imprez i uroczystości</a></li> <li><a href="#">Olimpiady, konkursy, zawody</a></li> <li><a href="#">Koła zainteresowań</a></li> <li><a href="#">Matura</a></li> <li><a href="#">Egzamin zawodowy</a></li> </ul> I have ~500 tasks, each of them takes ~5 seconds where most of the time is wasted on waiting for the remote resource to reply. I would like to define the number of threads that should be spawned myself (after some testing) and run the tasks on those threads. When one task finishes I would like to spawn another task on the thread that became available.
I found System.Threading.Tasks the easiest to achieve what I want, but I think it is impossible to specify the number of tasks that should be executed in parallel. For my machine it's always around 8 (quad core cpu). Is it possible to somehow tell how many tasks should be executed in parallel? If not what would be the easiest way to achieve what I want? (I tried with threads, but the code is much more complex). I tried increasing MaxDegreeOfParallelism parameter, but it only limits the maximum number, so no luck here...
This is the code that I have currently:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { private static List<string> _list = new List<string>(); private static int _toProcess = 0; static void Main(string[] args) { for (int i = 0; i < 1000; ++i) { _list.Add("parameter" + i); } var w = new Worker(); var w2 = new StringAnalyzer(); Parallel.ForEach(_list, new ParallelOptions() { MaxDegreeOfParallelism = 32 }, item => { ++_toProcess; string data = w.DoWork(item); w2.AnalyzeProcessedString(data); }); Console.WriteLine("Finished"); Console.ReadKey(); } static void Done(Task<string> t) { Console.WriteLine(t.Result); --_toProcess; } } class Worker { public string DoWork(string par) { // It's a long running but not CPU heavy task (downloading stuff from the internet) System.Threading.Thread.Sleep(5000); return par + " processed"; } } class StringAnalyzer { public void AnalyzeProcessedString(string data) { // Rather short, not CPU heavy System.Threading.Thread.Sleep(1000); Console.WriteLine(data + " and analyzed"); } } }
-31659897 0 R shiny reactive table, render plot can not work everyone. I am very new to shiny. I would like to plot a pie chart based on a filter data frame. Here is my data frame:
Duration Received Name Status 1 month 01/14/2014 Tim Completed 1 month 02/12/2014 Chris Completed 2 months 01/08/2015 Anna Completed 1 month 06/25/2014 Jenifer Completed 2 months 05/14/2015 Ruby Completed more than 3 months 11/05/2014 David Pending 2 months 05/12/2015 Anna Completed 1 months 03/26/2015 David Completed ... ... There may be more than 500 lines in the data frame
First, I tried to subset the data frame by Received Date. And plot the Duration Freq in pie chart. For example, I would like to choose all records after 12/31/2014. So I can select my Received Date. Then, table() Duration column in the subset data frame. Last, plot the pie chart.
My problem is when I change the date Rang of the Received date, my pie plot keep the consistent, never update. Can anyone help me to debug my script and tell me why? Thank you
Here is my code: ui.R
library(shiny) library(ggplot2) ggpie <- function (dat, by, totals) { ggplot(dat, aes_string(x=factor(1), y=totals, fill=by)) + geom_bar(stat='identity', color='black') + guides(fill=guide_legend(override.aes=list(colour=NA))) + coord_polar(theta='y') + theme(axis.ticks=element_blank(), axis.text.y=element_blank(), axis.text.x = element_blank(), axis.title=element_blank()) + scale_y_continuous(breaks=cumsum(dat[[totals]]) - dat[[totals]] / 2, labels=dat[[by]]) } shinyUI(fluidPage( headerPanel("My App"), sidebarPanel( dateRangeInput("dates", label = h3("Received Date Range"), start = "2013-01-01", end = as.character(Sys.Date()) ) ), mainPanel( plotOutput("Duration"), tableOutput("test") ) )) server.R
library(shiny) library(ggplot2) ggpie <- function (dat, by, totals) { ggplot(dat, aes_string(x=factor(1), y=totals, fill=by)) + geom_bar(stat='identity', color='black') + guides(fill=guide_legend(override.aes=list(colour=NA))) + coord_polar(theta='y') + theme(axis.ticks=element_blank(), axis.text.y=element_blank(), axis.text.x = element_blank(), #axis.text.x=element_text(colour='black',angle=45, size=10, vjust=0.5), axis.title=element_blank()) + scale_y_continuous(breaks=cumsum(dat[[totals]]) - dat[[totals]] / 2, labels=dat[[by]]) } shinyServer(function(input, output) { #table newData= reactive({ data1 = subset(data, input$dates[1]<=data$Received && data$Received<=input$dates[2]) data2 = as.data.frame(table(data1$Duration)) }) output$test<- renderTable({ newData() }) output$Duration<-renderPlot({ ggpie(newData(), by='Var1', totals="Freq") + ggtitle("Duration")+ scale_fill_discrete(name="Duration") }) })
-2090043 0 I think what you want to customize is compilation-parse-errors-filename-function, which is a function that takes a filename, and returns a modified version of the filename to be displayed. This is a buffer local variable, so you should set it in each buffer that will be displaying python errors (there is probably an appropriate hook to use, I do not have python mode installed so I cannot look it up). You would use propertize to return a version of the input filename that acts as a hyperlink to load the actual file. propertize is well documented in the elisp manual.
If compilation-parse-errors-filename-function is not getting called, then you want to add a list to compilation-error-regexp-alist-alist (that does say alist-alist, that is not a typo) which is a list of mode names followed by regular expressions to match errors, and numerical indexes of the matching line number, filename etc. info in the error regexp match.
First of all: "Free" = 0, "Normal" = 1, "Featured" = 0. <-- Featured would be 3 Im right?
Theres nothing wrong with you saving the three different objects in three different classes, actually I personally think thats the best option, rather than just puting everything together in one class and make a mess.
-37445324 0Regarding your 2nd question: If you need cashing for fullName, you may and should do it explicitly:
class Client { val firstName: String val lastName: String val fullName = "$firstName $lastName" } This code is equivalent to your snipped except that the underlying getter getFullName() now uses a final private field with the result of concatenation.
I have a navigation that I am animating. However the text jumps because it shows before the animation is done, so I want to set a delay of 300ms before triggering the display:inline-block. I cant get it to work? Any ideas?
$(".left-navigation ul li").hover(function(){ $(this).stop().animate({'width': '100%'}, 200); $(this).find("span.nav-text").delay(300).css("display", "inline-block"); }, function(){ $(this).stop().animate({'width': '35px'}, 200); $(this).find("span.nav-text").css("display", "none"); });
-25116142 0 How to render a Widget inside a TreeView cell with GTK# I'm developing an application with Mono and Gtk#. Inside my app, I need to use the TreeView control. I'm looking for a way to render a widget inside a cell instead of drawing everything. I have custom widgets that I would like to use inside those cells and I don't want to draw them manually.
I have looked over documentations and forums but haven't found a way to do this. I don't think this is impossible since CellRendererCombo and CellRendererToggle seems to render a Widget.
Thanks
-9952409 0It's a shame I didn't see this sooner.
At one time I had a branch of the Cake build tool that had almost full Ivy support. I again have a need for this, but since Cake is now deprecated I've had to branch leiningen. I only just started but it works for resolving (including configurations, exclusions, branches, etc).
Right now it's based of the lein2 preview release. I'm not sure how much more work I'll put into it though. I'd like to create a complementary lein-ivy plugin that could add the features of the old Cake version (publishing, dependency reports, multiple publications, etc).
-19523949 0 Symbols in email headlines for pear mailI'm trying to put a heart symbol ♥ into the headline of an email which should be sent via the php pear mail package.
But the receiver gets a ? instead of the heart so there has to be some mistake. It works if I manually send the email with my mail client.
My code is the following:
require_once "Mail.php"; $smtp = Mail::factory('smtp', array ('host' => 'host', 'port' => port, 'auth' => true, 'username' => 'username', 'password' => 'password'); $headers = array ('From' => 'sender', 'Subject' => '♥ test', 'Charset' => 'utf-8', ); $mail = $smtp->send($to, $headers, 'heart test'); What do I need to change in order to make the heart display correctly for the receiver of the email?
-25404839 0You probably didn't add feincms.module.page to your INSTALLED_APPS as per the documentation. If you follow the traceback, the error appears in get_object() where it tries to access the page model.
Are you using an older FeinCMS version? Newer versions raise a warning in that case.
-29959309 0 Remove back button from SearchView in toolbar AppCompat
How can I remove the back button icon when search view shows up in Toolbar (AppCompat)?
toolbar = (Toolbar) findViewById(R.id.tool_bar); // Set an OnMenuItemClickListener to handle menu item clicks toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { // Handle the menu item return true; } }); // Inflate a menu to be displayed in the toolbar toolbar.inflateMenu(R.menu.menu_main); toolbar.setTitle(""); setSupportActionBar(toolbar); actionBar = getSupportActionBar(); // this works for normal back button but not for one appears on tapping SearchView actionBar.setDisplayHomeAsUpEnabled(false);
-37051604 0 To the best of my knowledge the issue comes from the position=position_dodge.
Here you specify the distance between centers is lower than the width of your bars. You should try with position="dodge" instead.
You should be able to use Grails filters to do this:
class TimeFilters { def filters = { timeCheck(controller: '*', action: '*') { before = { model -> ... } after = { model -> ... } } } } If you look at the source code of java.util.Date:
public Date() { this(System.currentTimeMillis()); } So this is just a performance overhead to create and get time: new Date().getTime()
I was wondering, is it possible to enhance the speed of a page loading by decreasing the size of images within the page? Would this be possible via jQuery
No. This would require that the browser download the large image over the network and then process it to reduce it in size.
If you want to speed things up, you need to make the images smaller before they leave the server.
You don't need to do this manually though. Image resizing can be done programatically.
-26667878 0 How to display the json data in multiautocomplete textview?I am new to android, am developing one application in which i have to get the data from the server need to store that data in sqlite, so every time i should not hit the server,when ever i want get from database,in this app i used fragment concept,when i enter the single character in multiautocomplete textview based on the names in json response it needs to show the email-ids which are matching to that character in drop down list. i have done the code am not getting errors but not getting the expected result in textview
when i debug the code the following block of code is not executing i don't know what is the problem in this can you please help me any one
new Handler().post(new Runnable() { public void run() { Cursor cursor = contactDataSource.getAllData(); if (BuildConfig.DEBUG) Log.d(TAG, "total contcat count :" + cursor.getCount()); while (cursor.moveToNext()) { if (BuildConfig.DEBUG) Log.d(TAG, "Contact from cursor:" + cursor.getString(cursor .getColumnIndex(ExistingContactTable.COL_NAME))); } customAdapter = new CustomContactAdapter(getActivity(), cursor); Log.i("Custom contact adapter", "" + customAdapter); if (customAdapter != null) editorIdSharableEmail.setAdapter(customAdapter); } });
-23793919 0 Trying to get onLocationChanged from a service? I have some sample service that implements LocationListener now i want to get the lat/lng every time the location has been changed from that service that listens when location has been changed . But i dont know how to call from the mainactivity to that service to particular onLocationChanged .
This is what i'v tried:
From the MainActivity:
GpsTracker gps; // I declared that at the start of the activity //and then..... gps = new GpsTracker(MainActivity.this); gps.onLocationChanged(gps.location { lat=gps.getLatitude(); lng=gps.getLongitude(); }); and this is my service sample code:
public class GpsTracker extends Service implements LocationListener { private final Context mContext; // flag for GPS status boolean isGPSEnabled = false; // flag for network status boolean isNetworkEnabled = false; // flag for GPS status boolean canGetLocation = false; Location location; // location double latitude; // latitude double longitude; // longitude double patitude; double pongitude; // The minimum distance to change Updates in meters private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 10 meters // The minimum time between updates in milliseconds private static final long MIN_TIME_BW_UPDATES =0; // 1 minute // Declaring a Location Manager protected LocationManager locationManager; public GpsTracker(Context context) { this.mContext = context; getLocation(); } public Location getLocation() { try { locationManager = (LocationManager) mContext .getSystemService(LOCATION_SERVICE); // getting GPS status isGPSEnabled = locationManager .isProviderEnabled(LocationManager.GPS_PROVIDER); // getting network status isNetworkEnabled = locationManager .isProviderEnabled(LocationManager.NETWORK_PROVIDER); if (!isGPSEnabled && !isNetworkEnabled) { // no network provider is enabled } else { this.canGetLocation = true; if (isNetworkEnabled) { locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("Network", "Network"); if (locationManager != null) { location = locationManager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } // if GPS Enabled get lat/long using GPS Services if (isGPSEnabled) { if (location == null) { locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("GPS Enabled", "GPS Enabled"); if (locationManager != null) { location = locationManager .getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } } } } catch (Exception e) { e.printStackTrace(); } return location; } /** * Stop using GPS listener * Calling this function will stop using GPS in your app * */ public void stopUsingGPS(){ if(locationManager != null){ locationManager.removeUpdates(GpsTracker.this); } } /** * Function to get latitude * */ public double getLatitude(){ if(location != null){ latitude = location.getLatitude(); } // return latitude return latitude; } /** * Function to get longitude * */ public double getLongitude(){ if(location != null){ longitude = location.getLongitude(); } // return longitude return longitude; } /** * Function to check GPS/wifi enabled * @return boolean * */ public boolean canGetLocation() { return this.canGetLocation; } /** * Function to show settings alert dialog * On pressing Settings button will lauch Settings Options * */ public void showSettingsAlert(){ AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); // Setting Dialog Title alertDialog.setTitle("GPS is settings"); // Setting Dialog Message alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?"); // On pressing Settings button alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int which) { Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); mContext.startActivity(intent); } }); // on pressing cancel button alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); // Showing Alert Message alertDialog.show(); } @Override public void onLocationChanged(Location location) { latitude=location.getLatitude(); longitude=location.getLongitude(); } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public IBinder onBind(Intent arg0) { return null; } } What i'v wrote on the MainActivity gives errors... Would be glad to get some help.
-6070707 0I think you have alot of boiler plate code you don't need. If you do it this way you can add Commands without having to add code as well.
public interface Command { } public enum Commands { ; public static Command[] parseCommand(String command) { for (Class type : new Class[]{CameraCommand.class, RoverCommand.class}) try { return new Command[]{(Command) Enum.valueOf(type, command)}; } catch (IllegalArgumentException ignored) { } throw new IllegalArgumentException("Unknown Command " + command); } } public enum CameraCommand implements Command { CLICK } public enum RoverCommand implements Command { L, R, M; }
-18432851 0 Accuracy of GPS Timestamp in depending on position accuracy In need to exploit in my application time obtained from GPS. I need position and I need to know a time stamp which I can globally trust.
I'm getting information how accurate my position is, for instance 5m, 100m etc. But I would like to know how accurate it my timestamp depending on position accuracy. Of course I know that the accuracy of the position is correlated with accuracy of the timestamp (this is basic idea of gsp), but I would like know what error of the timestamp (in miliseconds) should I expect when I'm getting position with accuracy 5m ,50m, 100m etc. Is there easy way to calculate that?
-20789852 0Because layouts are typically constructed from left to right, it is common for the right side of the image to be cropped off when it's dimensions exceeds the width of it's containing parent.
Unfortunately, it is difficult to adjust the size of the <img /> element if you want to keep the aspect ratio and fill out all the available space. The former can be easily done with width: 100%; max-width: 100%;, but the latter is more of a challenge.
That brings us to the utility of background size. CSS now supports values of background-size such as cover, which dictates that the background image will fill out the container yet retain aspect ratio, cropping off parts that we don't need.
CSS:
.ls_video { background-size: cover; background-position: center center; margin-left: auto; margin-right: auto; width: 100%; height: 420px; text-align: left; } JS:
var videoSrc = "http://www.youtube.com/embed/MxuIrIZbbu0"; var videoParms = "?autoplay=1&fs=1&hd=1&wmode=transparent"; var youtubeVideo = "" + "<iframe class='ls_video' src='" + videoSrc + videoParms + "'>" + "</iframe>"; var theThumbNail = "" + "<div onclick=\"this.innerHTML = youtubeVideo;\" style=\"background-image: url(images/MLSFthumbnail.jpg);\"></div>"; document.write (theThumbNail);
-14900714 0 This uses MAX and MIN to see to that all values are the same; one needs to add a + 0 to each bit to make it available to normal numeric aggregate functions (like MIN/MAX/SUM/...)
SELECT ProjectId, EmployeeId FROM Temp GROUP BY ProjectId, EmployeeId HAVING MAX(IsWarning + 0) = 0 AND MAX(IsExpired + 0) = 0 AND MIN(IsIncomplete + 0) = 1
-843353 0 Windows Mobile Pocket PC how to mute | unmute (microphone) How can i mute | unmute a windows mobile pocket pc device (i'm using symbol MC70) programmatically? Waht API do I need to use?
-26512972 0Yes they are kind of Observer pattern, or a specialization of this pattern.. However i found in a blog about Android-useful design patterns and they are mentioning Adapter Pattern as a separate thing.
-37380984 0 Firebase Facebook Login from Ionic (Cordova) app in iOS EmulatorI'm configuring my Ionic app to work with Facebook Authentication. Everything seems about right when I debug the app from my browser; however, when I deploy the app to the iOS emulator I get the following message in the safari console:
"This domain is not authorized for OAuth operations for your Firebase project. Edit the list of authorized domains from the Firebase console."
I suppose that makes sense. I went over to the Firebase console to add an additional domain name which my emulator was running on, but have no idea what the domain would be. I even tried logging "window.location.hostname" but it came up as completely blank when I run the app from the emulator (it's localhost when I run it from the browser). Any idea how to allow the emulator to utilize Firebase authentication? Thanks a bunch. Please let me know if I can provide additional details.
-4922217 0 Can the SSMS editor be re-used in your own application, or is there an alternative?I would like to have IntelliSence or code completion, and syntax highlighting for SQL queries in my own .NET application.
Is it possible to use the SQL Server Management Studio's editor similar to the way you can use the SMO APIs?
Are there open source control(s) that can be used?
I have found code completion / syntax highlighting controls, but SQL is a funny beast because of the column / table aliases.
-14900756 0An array printed out with print_r cannot be parsed back into a variable.
In your server.php do echo json_encode($_POST);. Then in your client.php
<?php //... $output = curl_exec($curl_handle); // and now you can output it however you like if ($this->request_response_type == 'array') { //though i don't see why you would want that as output is now useless if someone ought to be using the variable $outputVar = json_decode($output); // that parses the string into the variable print_r((array)$outputVar); // or even better use serialize() echo serialize($outputVar); } else if ($this->request_response_type == 'json') { echo $output; //this outputs the original json } else if ($this->request_response_type == 'xml') { // do your xml magic with $outputVar which is a variable and not a string //xml conversion will be done here later. not ready yet. }
-10103712 0 It's not top-left, top-right but top left, top right.
Instead of assigning the actual values to the attribute properties, assign keys for resource strings. Then, you can use a custom ModelMetadataProvider that is aware of the localization context and will provide the appropriate string. To get a better solution, you can make your custom ModelMetadataProvider infer conventions, (which cuts down on the need for verbose attributes).
Phil Haack has a blog article called Model Metadata and Validation Localization using Conventions that explains how this works. There is also a corresponding NuGet package called ModelMetadataExtensions with source code available on github at https://github.com/Haacked/mvc-metadata-conventions .
As a side note, I'd recommend reviewing some of the awesome answers I got on an old question of mine: Effective Strategies for Localization in .NET. They don't specifically address your question, but will be very helpful if you are working on a multilingual .NET app.
-37854261 0This post should help you : http://stackoverflow.com/a/8996581/5941903.
Before posting, please try to do some research. I just typed : android rotate imageview on Google...
-19644515 0For only compiling part you can use following changes in the Makefile
file%.o:file%.c file%.h $(TOOLCHAIN_GCC) $(COMPILEOPTS) $< After this you need to make changes in linking of the object files to generate the final executable file.
-37123278 0This can be achieved by using a script (modify to suit your needs):
#!/bin/bash # Dynamic IP .htaccess file generator # Written by Star Dot Hosting # www.stardothosting.com dynDomain="$1" htaccessLoc="$2" dynIP=$(/usr/bin/dig +short $dynDomain) echo "dynip: $dynIP" # verify dynIP resembles an IP if ! echo -n $dynIP | grep -Eq "[0-9.]+"; then exit 1 fi # if dynIP has changed if ! cat $htaccessLoc | /bin/grep -q "$dynIP"; then # grab the old IP oldIP=`cat /usr/local/bin/htold-ip.txt` # output .htaccess file echo "order deny,allow" > $htaccessLoc 2>&1 echo "allow from $dynIP" >> $htaccessLoc 2>&1 echo "allow from x.x.x.x" >> $htaccessLoc 2>&1 echo "deny from all" >> $htaccessLoc 2>&1 # save the new ip to remove next time it changes, overwriting previous old IP echo $dynIP > /usr/local/bin/htold-ip.txt fi Than just cron it to generate a new line on the .htaccess file:
*/15 * * * * /bin/sh /usr/local/bin/.sh yourhostname.no-ip.org /var/www/folder/.htaccess > /dev/null 2>&1 Source: https://www.stardothosting.com
-10303129 0Yes, you can; if the variable/parameter you are trying to compare is already populated with data. Something like this:
DECLARE v_num1 NUMBER := 5; v_num2 NUMBER := 3; v_temp NUMBER; BEGIN -- if v_num1 is greater than v_num2 rearrange their values IF v_num1 > v_num2 THEN v_temp := v_num1; v_num1 := v_num2; v_num2 := v_temp; END IF; Provide more information based on what you are actually trying to do.
-28490593 0 Error on using Vim-latex ("can't find file ~")I'm not sure if this question is appropriate here but I have nowhere else to ask. I recently started to typeset some 'mathsy' stuff using Latex and it became a hobby for me. I've been using TeXnicCenter for this, but feeling that I've got familiar with Latex language, I decieded to improve 'efficiency' of typesetting by changing the editor.
So I decided to use Vim (latest version, 7.4) with Suite-Latex. I've just installed Vim and Suite-Latex, following exactly what was instructed here. I made every necessary changes mentioned here, and it seemed to me that installation was successful (I got what was expected on Step 4)
Then I started to work through this tutorial and everything went fine until this section.
When I press F9 for autoreference, I see that Vim is working on something for split seconds and red error message refering to "can't find [some file name]" in my user/appdata/local/temp directory. The "file name" changes every time I do this (so its kind of temporary file as its directory suggests?). And then it produces a new window with title __ OUTLINE __ where 2 empty lines are showing up.
If I press n (in the new window described above) error message saying "E486: Pattern not found: rf" pops up and pressing j results in going down one row. If I press enter key, message ":call Tex_FinishOutlineCompletion()" pops up.
More frustratingly, if I try to compile a file by entering command \ll, a new window pops up where there are two lines saying:
1.ll I can't find file `newfile.tex'. newfile.tex
2.ll Emergency stop
and below these is a message saying
[Quickfix list]: latex -interaction=nonstopmode -file-line-error-style newfile.tex
So I thought it maybe is something to do with VIM not being able to find files in my computer (so something wrong with grep?), and I tried to resolve it by downloading a software called "cygwin" on which developers said their tests were successful, but it changed nothing.
But I think the two problems are related.
As it is, I am completely newbie in this type of editing environment (or any kind of programming) but I really would like to learn some Vim seeing how efficient it is in typesetting etc. Sorry for not being a pro at typing codes here. Thanks for reading!
-10969732 0 multiple form within one HTML tableOut of a really long product list I am creating a table. Each row should be possible to update. HTML is not valid if I put multiple forms within one table. A solution would be to create for each row a single table, but the format would be really ugly.
I would like to make this:
<table> <tr><form><td><input type=\"text\" name=\"name\" value=\"".$row['name']."\" /></td>\n"; .... .... . . .
It is not vaild. What I could do?
-35937899 0I see.. Because you must change browser css defaults use in reset.css or normalize.css
Example delete margin:
index.html page:
<html> <head> <style> html, body { height:100%; margin:0px; //--> added this line } </style> </head> <body style="height:100%;"> <div style="width:100%; height:100%;"> <div id="theHead" style="height:10%; "> </div> <div id="theMain" style="height:80%;"> </div> <div id="theBottom" style="height:10%;"> </div> </div> </body> </html> Firefox default stylesheet file
Webkit default stylesheet file
-39970531 0 Should I Add String Conditional Method to Helper or Model or ...?What is the best way to do this?
I have this in a view <%= badges(challenge) %> or <%= challenge.badges %> depending on if I put badges in a helper or the model.
I was told to put it in a helper. I put it in so like this:
module ChallengesHelper def badges(challenge) if challenge.name == "Read 20 Min" ActionController::Base.helpers.image_tag("read.png", class: "gold-star") elsif challenge.name == "Exercise 20 Min" ActionController::Base.helpers.image_tag("exercise.png", class: "gold-star") elsif challenge.name == "Meditate 10 Min" ActionController::Base.helpers.image_tag("meditate.png", class: "gold-star") elsif challenge.name == "Stretch 5 Min" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif challenge.name == "Write 500 Words" ActionController::Base.helpers.image_tag("write.png", class: "gold-star") elsif challenge.name == "Walk 5,000 Steps" ActionController::Base.helpers.image_tag("walk.png", class: "gold-star") elsif challenge.name == "Eat Fruit & Veg" ActionController::Base.helpers.image_tag("fruit-and-vegetable.png", class: "gold-star") elsif challenge.name == "Plan Day" ActionController::Base.helpers.image_tag("plan.png", class: "gold-star") elsif challenge.name == "After Waking, Guzzle Water" ActionController::Base.helpers.image_tag("water.png", class: "gold-star") elsif challenge.name == "Track Food Consumption" ActionController::Base.helpers.image_tag("track-food.png", class: "gold-star") elsif challenge.name == "Random Act of Kindness" ActionController::Base.helpers.image_tag("random-kindness.png", class: "gold-star") elsif challenge.name == "Write 3 Gratitudes" ActionController::Base.helpers.image_tag("gratitude.png", class: "gold-star") elsif challenge.name == "Juice Fast" ActionController::Base.helpers.image_tag("juice.png", class: "gold-star") elsif challenge.name == "Not Smoke" ActionController::Base.helpers.image_tag("not-smoke.png", class: "gold-star") elsif challenge.name == "Not Drink Alcohol" ActionController::Base.helpers.image_tag("not-drink.png", class: "gold-star") # GOAL CHALLENGES elsif challenge.name == "Live Abroad" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif challenge.name == "Long Road Trip" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif challenge.name == "Tour Capital Building" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif challenge.name == "Karaoke" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif challenge.name == "See New York Skyline" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif challenge.name == "Run 5K" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif challenge.name == "Write Memoir" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif challenge.name == "Lose 10 Pounds" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif challenge.name == "Join Club" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif challenge.name == "Skydive" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif challenge.name == "Start a Blog" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif challenge.name == "Donate $100 to Charity" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif challenge.name == "Create Independent Income Stream" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif challenge.name == "Paint a Picture" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif challenge.name == "Give a Public Speech" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") else ActionController::Base.helpers.image_tag("gold-star-maze.png", class: "gold-star") end end end I'm only concerned because it seems more "wordy" in the helper than the model.
def badges if name == "Read 20 Min" ActionController::Base.helpers.image_tag("read.png", class: "gold-star") elsif name == "Exercise 20 Min" ActionController::Base.helpers.image_tag("exercise.png", class: "gold-star") elsif name == "Meditate 10 Min" ActionController::Base.helpers.image_tag("meditate.png", class: "gold-star") elsif name == "Stretch 5 Min" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif name == "Write 500 Words" ActionController::Base.helpers.image_tag("write.png", class: "gold-star") elsif name == "Walk 5,000 Steps" ActionController::Base.helpers.image_tag("walk.png", class: "gold-star") elsif name == "Eat Fruit & Veg" ActionController::Base.helpers.image_tag("fruit-and-vegetable.png", class: "gold-star") elsif name == "Plan Day" ActionController::Base.helpers.image_tag("plan.png", class: "gold-star") elsif name == "After Waking, Guzzle Water" ActionController::Base.helpers.image_tag("water.png", class: "gold-star") elsif name == "Track Food Consumption" ActionController::Base.helpers.image_tag("track-food.png", class: "gold-star") elsif name == "Random Act of Kindness" ActionController::Base.helpers.image_tag("random-kindness.png", class: "gold-star") elsif name == "Write 3 Gratitudes" ActionController::Base.helpers.image_tag("gratitude.png", class: "gold-star") elsif name == "Juice Fast" ActionController::Base.helpers.image_tag("juice.png", class: "gold-star") elsif name == "Not Smoke" ActionController::Base.helpers.image_tag("not-smoke.png", class: "gold-star") elsif name == "Not Drink Alcohol" ActionController::Base.helpers.image_tag("not-drink.png", class: "gold-star") # GOAL CHALLENGES elsif name == "Live Abroad" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif name == "Long Road Trip" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif name == "Tour Capital Building" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif name == "Karaoke" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif name == "See New York Skyline" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif name == "Run 5K" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif name == "Write Memoir" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif name == "Lose 10 Pounds" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif name == "Join Club" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif name == "Skydive" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif name == "Start a Blog" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif name == "Donate $100 to Charity" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif name == "Create Independent Income Stream" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif name == "Paint a Picture" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif name == "Give a Public Speech" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") else ActionController::Base.helpers.image_tag("gold-star-maze.png", class: "gold-star") end end Why is one spot better than the other? And what is the best practice for something like this where their are a lot of string conditions?
-32437218 0 How to remove or hide "Leave this page" button in confirm navigation of browsers?I want to remove/hide "Leave this page" button or want to trigger "Stay this page" button in confirm navigation of browsers?
window.onbeforeunload = function () { return "Please close the another tabs to logout.."; };
-21744550 0 Random number generator without repeating numbers I am trying to create a random number generator without repeating numbers {0 - 7}.
im getting a seg fault error here, and im pretty sure im allocating all the memory correctly there. One solution that i found that works occasionally is if i set shuffledbracket parameter size to 9. however since it has one extra memory it puts in an extra 0. any ideas on how i could get my array to only have a parameter size of 8 without a seg fault error?
-2386873 0 JVM benchmarking applicationWe want to compare general performance (CPU, I/O, network, ...) of different JVMs for the same Java version (1.5) in different environments (Windows, Solaris, ...).
Do you know of any JVM benchmarking application which can be used to compare results from different JVMs?
Thank you very much.
-14503052 0 Why exactly are Java arrays not expansible?Possible Duplicate:
Why aren’t arrays expandable?
I am starting to learn Java as my Computer Science school's assignments require this language and I'm liking the language. However, I've seen that Java arrays are not expansible - that is - you must declare their length before using them and it can't be changed further.
I'd like to know exactly why is that? Why the Java language designers chose to to make arrays as such? I guess it's for performance concerns but I'm not sure.
Thanks everyone in advance.
-28479843 0By default, Spring Boot 1.1 uses Flyway 3.0 which does not support COPY FROM STDIN. Support was added in 3.1. You can either upgrade to Spring Boot 1.2 (which uses Flyway 3.1 by default) or stick with Spring Boot 1.1 and try overriding the version of Flyway to 3.1.
Is it possible to get the publication date of CRAN packages from within R? I would like to get a list of the k most recently published CRAN packages, or alternatively all packages published after date dd-mm-yy. Similar to the information on the available_packages_by_date.html?
The available.packages() command has a "fields" argument, but this only extracts fields from the DESCRIPTION. The date field on the package description is not always up-to-date.
I can get it with a smart regex from the html page, but I am not sure how reliable and up-to-date the this html file is... At some point Kurt might decide to give the layout a makeover which would break the script. An alternative is to use timestamps from the CRAN FTP but I am also not sure how good this solution is. I am not sure if there is somewhere a formally structured file with publication dates? I assume the HTML page is automatically generated from some DB.
-17233800 0 Devise -- password doesn't match its confirmation for some reasonI'm using devise and I can't add an user neither via no via seeds.rb. Here is a rails console:
irb(main):100:0> a = User.new => #<User id: nil, email: "", encrypted_password: "", reset_password_token: nil, reset_password_sent_at: nil,......etc> irb(main):111:0> a.email = "email1@gmail.com" => "email1@gmail.com" irb(main):116:0> a.password = "1234a" => "1234a" irb(main):117:0> a.password => "1234a" irb(main):119:0> a.password_confirmation = "1234a" => "1234a" irb(main):120:0> a.password_confirmation == a.password => true irb(main):121:0> a.save! (0.8ms) BEGIN User Load (1.2ms) SELECT "users".* FROM "users" WHERE "users"."reset_password_token" = 'M9Xg7pYuPkgysuirxoj8' LIMIT 1 User Load (1.1ms) SELECT "users".* FROM "users" WHERE "users"."reset_password_token" = '4y8Vdn9b7nsC2QqtkCSs' LIMIT 1 User Exists (0.7ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = 'email1@gmail.com' LIMIT 1 User Exists (0.8ms) SELECT 1 AS one FROM "users" WHERE LOWER("users"."login") = LOWER('login1') LIMIT 1 User Exists (0.6ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = 'email1@gmail.com' LIMIT 1 (0.4ms) ROLLBACK ActiveRecord::RecordInvalid: Validation failed: Password doesn't match confirmation
-29704760 0 Does Symfony 2 support Cassandra DB? I wanted to know if I can use Symphony 2 and Cassandra Database for a web project. I know that Symphony 2 supports NoSQL databases like MongoDB, but I am not sure if it do the same with Cassandra.
Any clarification would be welcome.
-14790157 0Have you tried getting rid of the try/catch statement completely?
string clientLanguage = null; var userLanguages = filterContext.HttpContext.Request.UserLanguages; if (userLanguages != null && userLanguages.Length > 0) { var culture = CultureInfo .GetCultures(CultureTypes.AllCultures) .FirstOrDefault( x => string.Equals( x.Name, userLanguages[0].Name, StringComparison.OrdinalIgnoreCase ) ); if (culture != null) { clientLanguage = culture.TwoLetterISOLanguageName; } } Use try/catch only for handling exceptions that are out of your control. As their name suggests exceptions should be used for handling exceptional cases.
In this case you are doing standard parsing so it is much better to do defensive programming instead of trying, throwing, catching, ...
-6519964 0If you look at the source, you'll see a GoogleItem::SetMerchantPrivateItemData, which simply sets the GoogleItem::$merchant_private_item_data property. Examining GoogleItem::GetXML reveals GoogleItem::$merchant_private_item_data can be a MerchantPrivate (which appears to be unimplemented, but you can write your own as long as it has a MerchantPrivate::AddMerchantPrivateToXML(gc_XmlBuilder $xml) method) or a string, which (after a pass through htmlentities) becomes the content of the merchant-private-item-data element. If you want to structure your private data with XML, you'll have to implement class MerchantPrivate.
class MerchantPrivate { function AddMerchantPrivateToXML(gc_XmlBuilder $xml) { $xml->Push('merchant-private-item-data'); $this->_addMyData($xml); $xml->Pop('merchant-private-item-data'); } abstract protected function _addMyData($xml); } class ItemData extends MerchantPrivate { public $userid, $period, $attribute; function _addMyData(gc_XmlBuilder $xml) { $xml->Element('userid', $this->userid); $xml->Element('period', $this->period); $xml->Element('attribute', $this->attribute); } }
-39502586 0 Because you're not waiting for the mouse button to be released before you trigger your buttons.
pause() starts, it brings up two buttons.Main Menu.game_intro() is called, which puts a Quit button in the same place.I've requirement for getting a 4-byte hex value as a input, for which I'm using InputBox(), which is returning me the input value (for ex: 5C0F591C) as a string and hence it is failing when I'm comparing it with numerical equivalent.
By googling I found how to convert a char to int, I'd like to know if there are any procedures which can convert my 4-byte string in to a int/hex.
Also, it'd helpful if you can point to type conversion in VBScript for future purposes.
I'm very new to VBScript, correction can be made at any point, if I'm wrong
Appreciate your help, in advance.
-25983520 0What you can use is the Parse.Query.or function.
var currentUser = Parse.User.current(); var FriendRequest = Parse.Object.extend("FriendRequest"); var queryOne = new Parse.Query(FriendRequest); queryOne.equalTo("fromUser", currentUser); var queryTwo = new Parse.Query(FriendRequest); queryTwo.equalTo("toUser", currentUser); var mainQuery = Parse.Query.or(queryOne, queryTwo); mainQuery.equalTo("status", "Connected"); mainQuery.find({ /* ... */ });
-25873828 0 You might find this formula helpful, it will check for a null value in either column
{=IF(OR(A1:B1=""),"Null Value",IF(A1=B1,"Not Translated","Translated"))}
Leave out the curly braces and enter the function using Ctrl+Shift+Enter
You can drag that down for the following results
a a Not Translated b c Translated d Null Value e Null Value Null Value f f Not Translated
I have the following constant defined on the CUDA device:
__constant__ int deviceTempVariable = 1; Now I tried getting the address of deviceTempVariable using two methods, and I'm getting different results. The first is a direct memory access from a CUDA kernel as follows:
__global__ void cudaPointers(pointerStruct* devicePointer) { devicePointer->itsPointer = &deviceTempVariable; } The other is through host code as follows:
cudaGetSymbolAddress((void**) &pointerCuda, "deviceTempVariable"); I was curious and checked the address values; the first gives something like 00000008, and the second is 00110008. The offset seems to be the same in all cases (the number 8), but the rest is different. What's going on here, and which address would I have to use?
You need to fire the event on the form element itself, not on a jQuery selection. (In fact, you weren't even selecting the form element – inside setTimeout, this is the global object.)
Cache a reference to the form (this) and call its submit method:
$('form').submit( function(event) { var formId = this.id, form = this; mySpecialFunction(formId); event.preventDefault(); setTimeout( function () { form.submit(); }, 300); }); Note that I have also replaced your inefficient $(this).attr('id') call with this.id. Note also that you have to call the DOM form element's submit method, not the jQuery method, so that the jQuery event handler is not triggered, which would cause an infinite (and totally ineffectual) loop.
There is a Unix-only solution based on the PTools.jl package (https://github.com/amitmurthy/PTools.jl).
It relies on parallelism via forking instead of the Julia in-built mechanism. Forked processes are spawned with the same workspace as the main process, so all functions and variables are directly available to the workers.
This is a similar to the Fork clusters in R parallel package, so it can be used as the mclapply function.
The function of interest is pfork(n::Integer, f::Function, args...) and one noticeable difference with mclapply in R is that the function f must take as first argument the index of the worker.
An example:
Pkg.add("PTools") Pkg.checkout("PTools") #to get the last version, else the package does not build at the time of writing using PTools f(workid,x) = x[workid] + 1 pfork(3, f, [1,2,3,4,5]) #Only the three first elements of the array will be computed 3-element Array{Any,1}: 2 3 4 I expect that an interface to pfork will be built so that the first argument of the function will not need to be the index of the worker, but for the time being it can be used to solve the problem
-2751416 0That's perfectly correct. But it depends on what you want, perhaps you mean && instead of ||
If you know jQuery, you can use:
$('input[type=radio]').click(function() { var $this = $(this); $('.square').css('background', $(this).next().text()); })
-32300427 0 Some brief information about Stash and Git.
Git is a distributed version control system.
Stash is a repository management system of Atlassian. It can be used to manage Git repositories, also it can be used to manage repositories of other version control system like mercurial.
A good overview for each product can be found in their official sites;
Atlassian official site, stash product home page
There are many repository management system you can use with Git. One of the most popular is Stash in Enterprise world. But when you look to open source world, GitHub is the most popular one as far as I know.
You can create repository, push, or pull your code into Git repositories whether they are in your local computer or they are in remote corporate servers. Using a repository management system ( like Stash) for this kind of task is not necessary, but It is sometimes preferred, especially by the companies which has huge It departments.
So, Git, and Stash are not alternative but complementary to each other. You can think Git as a kernel and stash as the shell surrounding the kernel.
But, why we need repository management systems;
Now, Lets try to answer your questions;
I can access my company Stash project repositories. I cloned the project into my local Git repository
Whether Code repository is on remote server behind stash or it is in local computer. It is a Git repository.
Git is just a facilitator to communicate with Stash?
No, Vice versa is more correct. Git is the core of VCS, you use stash to make it more manageable, secure, and easy to use in your corporate.
Can't we use Git as distributed repository instead of Stash?
First you can not use Git instead of Stash, because they are not alternative to each other. But they are complement to each other.
If you mean using Git as remote repository, sure you can use it.
For clarification, Git is distributed not because you can have remote repositories. Whether centralized or distributed, you can have remote repository on all VCS. Distributed means, when you clone a repository, you also clone all history etc. In this structure, you can have a central repository but it is not required. If centrol repository get corrupted, it is not a big deal, any node can become new central repository. Even though in corporate world having a central repository is best practice, some open source projects ( for instance Linux kernel) don't have a central repository.
What is the relationship between those two tools?
I think it is already explained above. They are complementary to each other. Git is the VCS, and stash is repository management tool. It makes Git more secure and manageable for corporate IT departments.
Without Git, can the code be cloned, committed to Stash? Or, without Git, can Stash exist?
It is already explained as well. You can use Stash with other VCS. Git is not necessary. But you need at least one VCS.
You can not commit/clone code to/from stash. You can commit/clone code to/from VCS via stash.
VCS: Version Control System
-18768537 0You can do this in MVVM but you will need to use a service. In fact, this is where MVVM is weak (without using a framework such as Prism et al.). The following is a link to disore's DialogService class on CodeProject. it is awesome, but it will take time to get to grips with how it works.
The above library will enable you to close a View from a ViewModel.
I hope this helps.
-2114596 0No, I don't know of any. Because NHibernate is popular and very good at what it does, and EF is likely to pick up most of the remainder (particularly devs that don't want to stray from Microsoft-supplied frameworks), the barrier to entry for a new player is very high. Another ORM would need to add something significant over and above what NHibernate currently offers in order to get any reasonable level of interest.
If there was an open source project that wanted to deliver better Linq support in an ORM, in my opinion it would have greater success contributing to NHibernate Linq rather than attempting to build its own framework from scratch.
-3169296 0 DBus: Performance improvement practicesWhat are some good practices to obtain better time performance in applications that heavily utilize DBus?
Here are a few that our team has learned through the school of hard knocks:
Try following the manual, it's working great for me:
http://book.cakephp.org/view/1110/Running-Shells-as-cronjobs
I have never had the need to create a splash screen and wondered what is the best way to do it.
I have an mdi application that when the MDIParent loads it makes few database calls and displays.
What I would like to do is
I have done as follows but the problem i have is that the mdi still does the work when the splashscreen dissappears.I want the mdi to be fully loaded once the splash screen is gone.
[STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var splashForm = new SplashFormView(); splashForm.IntervalTime = 5000; --prop to decide how long the splashScreen should display splashForm.ShowDialog(); SetupUnityContainer(); } private static void SetupUnityContainer() { using (IUnityContainer container = new UnityContainer()) { container.RegisterType<IMyService2, MyService2>(); Application.Run(container.Resolve<MdiParent>()); } } Should run the splashscreen on a background thread? How can I make the MDIForm to be called and not visible till all loaded?
Many thanks
-27832159 0This is a printing poblem:
double d = 1.5; System.out.println(String.format("%.2f", d)); // 1.50
-25033424 0 This is how I solved the issue..
Overide onKeyDown() method in your activity.
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { // if one of the volume keys were pressed if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { // change the seek bar progress indicator position decreaseSeekbarValue(); } else if(keyCode == KeyEvent.KEYCODE_VOLUME_UP) { // change the seek bar progress indicator position increaseSeekbarValue(); } // propagate the key event return super.onKeyDown(keyCode, event); }
-30077324 0 Assuming your Job can only have one worker that is set when a Proposal is accepted, you'd want something like this:
class Job < ActiveRecord::Base belongs_to :poster, class_name: 'User', foreign_key: 'poster_id' belongs_to :worker, class_name: 'User', foreign_key: 'worker_id' has_many :proposals, dependent: :destroy end class User < ActiveRecord::Base has_many :posted_jobs, class_name: 'Job', foreign_key: 'poster_id', dependent: :destroy has_many :current_jobs, class_name: 'Job', foreign_key: 'worker_id' has_many :proposals, through: :jobs end class Proposal < ActiveRecord::Base belongs_to :job belongs_to :user end With this approach, you can get user.posted_jobs and user.current_jobs.
See this: Same Model for Two belongs_to Associations
-33845067 0 Android navigation drawer max number of itemsWhat is the max limit for number of items for android navigation drawer?
-5356255 0Just did an iPhone project hitting a REST service. To consume, try asihttprequest. Very good and used by many other apps.
How to use it (examples)
-1667365 0As far as I know there is no problems to work with Variant variable type in other languages. But it will be great if you export the same functions for different variable types.
-32347930 0 Java error trying to add admobIt shows red errors and I followed the instruction in Google site. Only prob in Java
-7259367 0mAdView.loadAd(adRequest) Unknown class:'adRequesr' Cannot resolve symbol loadAd
You simply need to mark the zip file as Embedded Resource under Build Action. http://msdn.microsoft.com/en-us/library/0c6xyb66.aspx
I had never use Google App Engine, but several times AWS systems, and sure, as AWS EC2 could be used as Linux Server Instance, I recommend you that provider. And coz' it seems that you use PHP, they have strong API for this langage. Have fun with AWS.
-39502274 0This took me so long to fix but the problem was that the Assets folder was removed from the build phases/copy bundle resources folder.
-7135252 0By setting RightToLeft to Yes, you are asking the Windows text rendering engine to apply the text layout rules used in languages that use a right-to-left order. Arabic and Hebrew. Those rules are pretty subtle, especially because English phrases in those languages are not uncommon. It is not going to render "txeT emaN" as it normally does with Arabic or Hebrew glyphs, that doesn't make sense to anybody. It needs to identify sentences or phrases and reverse those. Quotes are special, they delineate a phrase.
Long story short, you are ab-using a feature to get alignment that was really meant to do something far more involved. Don't use it for that.
-20971464 0from itertools import count, repeat def statistiken(request): # Get all members members = Member.objects.all() # Get maximum number of related events max_n_events = max(member.event_set.all().count() for member in members) # Create a list to hold table data table_data = [] for member in members: # Get all related events for the member events = member.event_set.all() # Get number of events n = events.count() # Append a iterator with member instance, event instances, and # repeating empty strings to fill up the table table_data.append(chain([member], events, repeat('', max_n_events-n))) context = {'table_data': table_data} return render(request, 'anwesenheitsapp/statistiken.html', context) and your template to this:
<table> <tr> {% for row in table_data %} {% for col in row %} <td>{{ col }}</td> {% endfor %} {% endfor %} </tr> </table> The strings in the table will be the result of __unicode__() for your member and events, followed by empty cells.
To access all related Events from a Member instance, use event_set.all().
Your template could look something like this:
<table> {% for member in all_members %} <td>{{ member }}</td> {% for event in member.event_set.all %} <td>{{ event }}</td> {% endfor %} {% endfor %} </table> Which should produce this table
| member0 | related_event00 | related_event01 | ... | related_event_0n| | member1 | related_event10 | related_event11 | ... | related_event_1n| | .... | | memberm | related_eventm0 | related_eventm1 | ... | related_event_mn| (n could be different from member to member of course)
-40169813 0 How can I pass a string from a C# DLL into an unmanaged language (e.g. C++)?I've had quite a lot of luck interoperating between Fortran (don't ask! :-) and C# using Robert Giesecke's wonderful "Unmanaged Exports" library. However, one of the things I haven't been able to achieve yet is sending a string from C# to Fortran. The worst of it is that I get no indication of what's wrong. My Fortran application just crashes. I've posted this problem to the most popular Fortran forum I know (here), and so far it has generated a lot of discussion but I'm no closer to solving the problem. I'm thinking now that if I can solve it in C/C++, perhaps I can take that solution over to Fortran more easily.
From all the research I've done, it would seem to me that something like the following should work:
using RGiesecke.DllExport; using System.Runtime.InteropServices; namespace CSharpDll { public class Structures { [StructLayout(LayoutKind.Sequential)] public struct MyStruct { [MarshalAs(UnmanagedType.LPStr)] public string Title; public int SourceNode; public int EndNode; } [DllExport("GetStruct", CallingConvention = CallingConvention.Cdecl)] public static MyStruct GetStruct() { var result = new MyStruct(); result.Title = "This is the title"; result.SourceNode = 123; result.EndNode = 321; return result; } } } Unfortunately, my C/C++ is even rustier than my Fortan. I have no idea how to make this work on that side. Can someone help me write an extremely simple console app in C/C++ that will call the above "GetStruct" method and get the structure including the string?
Note 1: I've tried pretty much every permutation of "UnmanagedType" as well as both "string" and "char[]" with no luck, so whereas I may not have that right in this example, please don't suggest one of those unless you can show that it works. :-)
Note 2: The vast majority of threads I've found around this topic send strings the other way (i.e. from an unmanaged DLL to a managed application rather than from an unmanaged application to a managed DLL). I'm not interested in those, since I have that working like a charm. :-)
-17945901 0 PHP Template - Using extract() and access vars by object. Array is givenI want something like this in my template file:
<ul> <?foreach($friends as $var):?> <li> <?=$var->name?> </li> <?endforeach ?> </ul> I use this in my model.php:
$data = array('friends' => array( array('name' => 'testname'), array('name' => 'testname2') )); // missing code here ? extract($data, EXTR_SKIP); include('template_file.html'); How can I use $var->name to access 'name' as an object in my template file?
$data = array() is set.
Update:
Its because, I dont want to use <?=$var['name']?> in my template.
This is in VSTS 2010
Question: Using WIQL, is it possible to get the list of file differences due to checkins
1) for a given date range
2) for a given folder
-38578707 0 Powershell: Output Variables passed from Manage EngineI'm having some issues with making some changes to an existing working script I have, but I have run into an issue with some variables that are being passed from my Manage Engine Software.
In order to better understand what the issue is i'm attempting to devise a simple script to output the variables to a text file so I can see what Manage Engine is spitting out for certain variables. However the script seems to fail when attempting to execute.
Here is what I am using in an attempt to get to the bottom of this.
Command:
Param( [string]$Department ) $Filepath = "\\fileserver\filename.txt" $Department | out-file -filepath $filepath Any help is greatly appreciated!
-21979274 0 How to programmatically Submit Hive Queries using C# in HDInsight Emulator?I Installed single node HDInsight Emulator in Windows 8 system. I want to programmatically submit hive queries in HDInsight Emulator. Kindly suggest me some ways to submit Hive Queries using C# .
-29587362 0Wow,so excited,I sovled this all by my self,what i do wrong here is that the request header i sent is not included in the nginx config add_header 'Access-Control-Allow-Headers'
complete nginx config:
http { include mime.types; default_type application/octet-stream; access_log /tmp/nginx.access.log; sendfile on; upstream realservers{ #server 192.168.239.140:8080; #server 192.168.239.138:8000; server 192.168.239.147:8080; } server { listen 8888 default; server_name example.com; client_max_body_size 4G; keepalive_timeout 5; location / { add_header Access-Control-Allow-Origin *; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'Access-Control-Allow-Orgin,XMLHttpRequest,Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With'; try_files $uri $uri/index.html $uri.html @proxy_to_app; } location @proxy_to_app{ add_header Access-Control-Allow-Origin *; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'Access-Control-Allow-Orgin,XMLHttpRequest,Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With'; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; #proxy_set_header X-Real-IP $remote_addr; proxy_redirect off; proxy_pass http://realservers; } } } because my request is :
core-ajax auto headers='{"Access-Control-Allow-Origin":"*","X-Requested-With": "XMLHttpRequest"}' url="http://192.168.239.149:8888/article/" handleAs="json" response="{{response}}"></core-ajax> i didnt include the Access-Control-Allow-Origin and XMLHttpRequest header into the nginx config Access-Control-Allow-Headers,so that is the problem.
I hope its useful to whom has the same problem!
-14649163 0 Distinct Query?I have a table that contains a Column with client names. It has about 10-15 distinct clients that appear multiple times in the column. Is there a way that I can run a query that will list all the distinct clients and do the count for each client so that it shows how many times each client appears in the column? I know that in SQL you can use as to assign temporary column, but I'm new to LINQ and have no idea if this is possible.
Any help would be great, thanks.
-13755681 0git add . will add any files in the current directory and any sub-directories. I would imagine that you could also do git add .\relative\path\to\file as well. If the file still resists, force a change (add a new line somewhere in the file where it won't hurt anything) and try again. Sometimes the diff that git runs doesn't detect that the file has changed.
Here's a quick and easy way, so long as your background is a solid color.
HTML:
<p class="myCopy"> <span>My Text goes here</span> </p> CSS:
.myCopy { display: block; height: 10px; border-bottom: solid 1px #000; text-align: center; } .myCopy span { display: inline-block; background-color: #fff; padding: 0 10px; } Adjust the height value of .myCopy to move the line up and down. Change the background color of the inner span to match the primary background color.
EDIT: here's a fiddle - FIDDLE!!!
-36102524 0 Passport.js multiple local strategies and req.userThe client for my web-app wants to totally separate regular users and admins, hence I'm trying to implement two local strategies for passport.js:
passport.use('local', new LocalStrategy({ usernameField: 'email' }, function(email, password, done) { User.findOne({ email: email }, function(err, user) { if (err) return done(err); if (!user) return done(null, false, { message: 'Wrong email or password.' }); if (!user.validPassword(password)) return done(null, false, { message: 'Wrong email or password.' }); done(null, user); }); })); passport.use('admin', new LocalStrategy({ usernameField: 'email' }, function(email, password, done) { Admin.findOne({ email: email }, function(err, admin) { if (err) return done(err); if (!admin) return done(null, false, { message: 'Wrong email or password.' }); if (!admin.validPassword(password)) return done(null, false, { message: 'Wrong email or password.' }); done(null, admin); }); })); passport.serializeUser(function(user, done) { done(null, user.id); }); passport.deserializeUser(function(id, done) { Admin.findById(id, function(err, admin) { if (err) return done(err); if (admin) return done(null, admin); User.findById(id, function(err, user) { done(err, user); }); }); }); And then in my API admin router:
router.post('/', function(req, res, next) { if (typeof req.body.email === 'undefined') return res.json({ success: false, message: 'Email not supplied.' }); if (!validator.isEmail(req.body.email)) return res.json({ success: false, message: 'Wrong email format.' }); if (typeof req.body.password === 'undefined') return res.json({ success: false, message: 'Password not supplied.' }); if (req.body.password.length === 0) return res.json({ success: false, message: 'Password not supplied.' }); passport.authenticate('admin', function(err, admin, info) { if (!admin) return res.json({ success: false, message: info.message }); req.logIn(admin, function(err) { if (err) return res.json({ success: false, message: 'Server error.', reason: err }); console.log('user:'); console.log(req.user); // both users and admins go here console.log('admin:'); console.log(req.admin); // undefined res.json({ success: true }); }); })(req, res, next); }); In fact, I was following the answer here: http://stackoverflow.com/a/21898892/1830420, and Matthew Payne gets two session variables: req.user and req.sponsor. In my case, even if an admin authenticates, it gets written to req.user. Now, trying to implement my client's desire of totally separating users and admins, I want to get req.user and req.admin, but every time it gets written to req.user. I thought changing LocalStrategy name would help, but passport.js seems to ignore both the strategy name and model name.
Any help is very much appreciated.
P.S. I know I can have everyone in User model and write some middleware to protect certain routes based on roles, but then again, unfortunately, I don't get to choose here.
You could extend a custom class from EditText with a method that will store the current text into a private member variable. In your Activity's onResume() method you would then call this method. Whenever you want to reset the EditText's text to its original text, you would then call another simple method that will set the current text to the text stored before.
public class MyEditText extends EditText { private String mStoredText; public MyEditText(Context context) { super(context); } public MyEditText(Context context, AttributeSet attrs) { super(context, attrs); } public void storeText() { mStoredText = getText().toString(); } public void restoreText() { setText(mStoredText); } }
-27161929 0 You should get a debugger working. It would provide you with the answer to your question within seconds, and it's essential for trying to track down these kinds of problems. What seems very mystifying and unclear, when you're trying to interpret the output, will seem very easy when you're stepping through it, and you can see everything.
This will probably lead to pipe() not doing what you expect, you'll check errno, and presumably get a useful answer.
The commenter's advise about avoiding doing stuff in signal handlers is good, as it's not portable. However, most modern OSs are quite permissive, so I'm not sure if that's your problem in this case.
-30259019 0Install Terminal Emulator from Play Store, open the application and type:
getprop ro.build.version.release you will get something like: 4.4.4 for KitKat.
or getprop ro.build.version.sdk for getting the sdk version which will return 19
Declare some variable within a switch and use it externally.
You can't. Variables defined inside the scope would only be visible within that scope.
You have to declare your variable outside the switch statement and then you will be able to use it outside.
I see that you are using var (Implicitly typed variable) and you can't declare it outside of your switch statement, (since that needs to be assigned), You should see: Declaring an implicitly typed variable inside conditional scope and using it outside and the answer from Eric Lippert
I'm confused by your question but I think you want the picture slide effect?
If so, I would recommend using the bootstrap Carousel, should give you what you need.
EDIT:
For the section number 4 just use the CSS scroll effects.
-38801135 0 how to get the start value and end value of a div after dragginghi i have a which is draggable my requirement is 1. iwant the start value and end value of the div after dragging in a text box 2.now its is only drag in right side only i want it dragg also from left side of the div i use some code here but it is not perfect becouse the value is not displaying and the dragging from left is not working midiletable is my parrentdiv
$(function () { var container = $('.middletablediv'), base = null, handle = $('.handle'), isResizing = false, screenarea = screen.width; handle.on('mousedown', function (e) { base = $(this).closest(".scalebar"); isResizing = true; lastDownX = e.clientX; offset = $(this).offset(); xPos = offset.left; }); $(document).on('mousemove', function (e) { // we don't want to do anything if we aren't resizing. if (!isResizing) return; p = parseInt(e.clientX - base.offset().left), // l = parseInt(p * (3 / 11)); base.css('width', p); k = parseInt(xPos - base.offset().left); $("#startvalue").value(k) $("#stopvalue").value(p) }).on('mouseup', function (e) { // stop resizing isResizing = false; }); }); .handle{ position: absolute; top:1px; right: 0; width: 10px; height: 5px; cursor: w-resize; } .middletablediv{ float:left; width:35%; } .scalebar{ margin-top: 13px; height: 7px; position: relative; width:20px; background-color: green; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="middletablediv"> <div id="newvalue1" class="scalebar"> <div class="handle" style="left:0"></div> <div class="handle"></div> </div> </div> <input id="startvalue" type="text">startvalue</input> <input id="stopvalue" type="text" />stopvalue</input> how i solve this issue
-33577880 0 How to deeplink to product page for Amazon Shopping app in Android?Using Intents/Activities, how can I programatically deeplink / launch the Amazon Shopping app to the landing page of a particular product in Android?
-15444495 0The webkit bug mentioned in @Phrogz answer seems to have been fixed in more recent versions, so I found a solution that doesn't require a manual parse is
// from http://bl.ocks.org/biovisualize/1209499 // via https://groups.google.com/forum/?fromgroups=#!topic/d3-js/RnORDkLeS-Q var xml = d3.select("svg") .attr("title", "test2") .attr("version", 1.1) .attr("xmlns", "http://www.w3.org/2000/svg") .node().parentNode.innerHTML; // from http://webcache.googleusercontent.com/search?q=cache:http://phpepe.com/2012/07/export-raphael-graphic-to-image.html // via http://stackoverflow.com/questions/4216927/problem-saving-as-png-a-svg-generated-by-raphael-js-in-a-canvas var canvas = document.getElementById("myCanvas") canvg(canvas, svgfix(xml)); document.location.href = canvas.toDataURL(); which requires https://code.google.com/p/svgfix/ and https://code.google.com/p/canvg/ and uses d3.js to obtain the svg source, which should be doable without d3.js as well (but this takes care of adding required metadata which can lead to problems when missing).
-22508299 0You need a little P/invoke:
add-type -type @' using System; using System.Runtime.InteropServices; using System.ComponentModel; using System.IO; namespace Win32Functions { public class ExtendedFileInfo { public static long GetFileSizeOnDisk(string file) { FileInfo info = new FileInfo(file); uint dummy, sectorsPerCluster, bytesPerSector; int result = GetDiskFreeSpaceW(info.Directory.Root.FullName, out sectorsPerCluster, out bytesPerSector, out dummy, out dummy); if (result == 0) throw new Win32Exception(); uint clusterSize = sectorsPerCluster * bytesPerSector; uint hosize; uint losize = GetCompressedFileSizeW(file, out hosize); long size; size = (long)hosize << 32 | losize; return ((size + clusterSize - 1) / clusterSize) * clusterSize; } [DllImport("kernel32.dll")] static extern uint GetCompressedFileSizeW([In, MarshalAs(UnmanagedType.LPWStr)] string lpFileName, [Out, MarshalAs(UnmanagedType.U4)] out uint lpFileSizeHigh); [DllImport("kernel32.dll", SetLastError = true, PreserveSig = true)] static extern int GetDiskFreeSpaceW([In, MarshalAs(UnmanagedType.LPWStr)] string lpRootPathName, out uint lpSectorsPerCluster, out uint lpBytesPerSector, out uint lpNumberOfFreeClusters, out uint lpTotalNumberOfClusters); } } '@ Use like this:
[Win32Functions.ExtendedFileInfo]::GetFileSizeOnDisk( 'C:\ps\examplefile.exe' ) 59580416 it returns the 'size on disk' that you read in properties file from explore.
-34442373 0If you want to sort by the first number, the approach is:
var desire = ranges.sort(function(a,b){return parseInt(a)-parseInt(b)}); Explanation: parseInt(a) just removes everything after the non-number, i.e. - and returns the number.
If you also want to make it sort by the first number properly if you have ranges starting with the same numbers (i.e. 3-5 and 3-7):
var desire = ranges.sort(function(a,b){ return (c=parseInt(a)-parseInt(b))?c:a.split('-')[1]-b.split('-')[1] }); Explanation: works as the first one until the first numbers are equal; then it checks for the second numbers (thanks Michael Geary for idea!)
If you want to sort by the result of equation, go for
var desire = ranges.sort(function(a,b){return eval(a)-eval(b)}); Explanation: eval(a) just evaluates the expression and passes the result.
Also, as mentioned by h2ooooooo, you can specify the radix to avoid unpredictable behavior (i.e. parseInt(a, 10)).
You need to initialize your new structure with zeros. GetMem does not zero the allocated memory, so the fields of your record initially contain random garbage. You need to call
FillChar(newItem^, sizeof(TAccessoryItem), 0)
after the GetMem, before using the record.
Here's why: When you assign to the string field of the newly allocated but uninitialized record, the RTL sees that the destination string field is not null (contains a garbage pointer) and attempts to dereference the string to decrement its ref count before assigning the new string value to the field. This is necessary on every assignment to a string field or variable so that the previous string value will be freed if nothing else is using it before a new value is assigned to the string field or variable.
Since the pointer is garbage, you get an access violation... if you're lucky. It is possible that the random garbage pointer could coincidentally be a value that points into an allocated address range in your process. If that were to happen, you would not get an AV at the point of assignment, but would likely get a much worse and far more mysterious crash later in program execution because this string assignment to an uninitialized variable has altered memory somewhere else in your process inappropriately.
Whenever you're dealing with memory pointers directly and the type you're allocating contains compiler managed fields, you need to be very careful to initialize and dispose the type so that the compiler managed fields get initialized and disposed of correctly.
The best way to allocate records in Delphi is to use the New() function:
New(newItem); The compiler will infer the allocation size from the type of the pointer (sizeof what the pointer type points to), allocate the memory, and initialize all the fields appropriately for you.
The corresponding deallocator is the Dispose() function:
Dispose(newItem); This will make sure that all the compiler-managed fields of the record are disposed of correctly in addition to freeing the memory used by the record itself.
If you just FreeMem(newItem), you will leak memory because the memory occupied by the strings and other compiler managed fields in that record will not be released.
Compiler managed types include long strings ("String", not "string[10]"), wide strings, variants, interfaces, and probably something I've forgotten.
One way to think about is this: GetMem/FreeMem simply allocate and release blocks of memory. They know nothing about how that block will be used. New and Dispose, though, are "aware" of the type you're allocating or freeing memory for, so they will do any additional work to make sure that all the internal housekeeping is taken care of automatically.
In general, it's best to avoid GetMem/FreeMem unless all you really need is a raw block of memory with no type semantics associated with it.
-32085424 0Guan, have you tried with an earlier version of the JDK (e.g., JDK-1.5?). I realize it's much older, but I'm curious if it's related to using the CLT on JDK 1.8. Just an idea.
Additionally, it would help if we could see the turk.properties file (please don't share your access keys or secret key) to make sure the endpoints are well-formed. Thanks!
-20214496 0 My new anchor tag is not working in .tpl fileI am trying to modify a template which consists of .tpl files instead of .html or .php. There are some anchor tags like this:
<a href="{$vurl}?p=about" class="someclass">About Us</a> but if I try to point to a different page in anchor tag like this:
<a href="{$vurl}?p=newAboutUs" class="someclass">About Us</a> it is not working. I have already created "newAboutUs.tpl" and copied "about.tpl" content and pasted to "newAboutUs.tpl".
But when I click the "About Us" button, nothing is happening.
If I put everything back and try to click the button it is working again.
-4688595 0 How to query more than 5000 records in Flex Salesforce app?I've run into an issue where Salesforce will only return 1000 records to my flex app from a query. I'd like to get more than that (like 5000-10000). Is this possible?
Here is what I have tried (app is an F3WebApplication)
note:this code does work, I just need it to return more results:
app.wrapper.query(query, new mx.rpc.Responder( function(rows:ArrayCollection):void { if(user_list != null){ filteredList = addOwnerData(rows); filteredList = PutChildrenWithParents(filteredList); } else { filteredList = PutChildrenWithParents(rows); } my_accounts_raw = new ArrayCollection(filteredList.toArray()); refreshSearchData(filteredList); }, function():void{_status = "apex error!";} ) ); } I've also tried app.connection.Query to then use queryMore but can't get that to work at all.
Any ideas?
Trying desperately to put a label over another label in netbeans because the one label is acting as the background image and I want the label in the foreground to have a different image.
Every time i drag another label on top, the JFrame gets bigger and the label tries to slot down the side.
Here is what I've got (I want the label where the red circle in the middle is not on the right down the side):
-20239267 0At last, I was able to find what I was looking for. Phew!
$_REQUEST['Body'] retrieves the body of the sms message and I can do whatever I like with that.
Twilio rocks!
-16030872 0Try something like this:
self.array = [[NSMutableArray alloc] init]; MyViewController *vc = self; [MyApp getCampaigns:^(NSArray *response) { [vc.array addObjectsFromArray:response]; }]; This will allow the objective-c compiler to create a strong reference to vc in the block, which will then point to self.
-9602913 0 Where is the "Store" menu in the Visual Studio 11 Beta?Where is the "Store" menu in the Visual Studio 11 Beta? I just downloaded and installed the Ultimate version and there's no "Store" menu like I see in all the video tutorials.
-38962095 0 Image in ListView that goes off-screen loses its state (never set to 'loaded')The situation:
I have a large list of photos and we are loading them in a grid of thumbnails. These thumbnails are each their own component that are loaded in sets of three within the RenderRow function. Here's the Image component in question:
<Image style={styles.image} source={this.state.loaded ? { uri: image.url_small } : imagePlaceholder} onLoad={() => { this.setState({ loaded: true }); }} onLoadStart={() => { this.setState({ loaded: false }); }} /> The issue:
Our issue is that if you are scrolling rapidly, or have a less-than-optimal internet connection, some of the images that begin loading never have the "onLoad" called, presumably because they are no longer visible (because we scrolled beyond them in the list already).
However, when we scroll back to those images, all that is rendered is the placeholder image, and the state of the photo is never set to loaded: true. I've tried messing with the onChangeVisibleRows function on the ListView like so:
onChangeVisibleRows={(visibleRows) => { const visibleRowNumbers = []; for (const row in visibleRows) { visibleRowNumbers.push(row); } this.setState({ visibleRowNumbers }); }} This seems to work as expected and in the RenderRow function I can check if that specific row is visible, and try to re-render and images in that row by passing a isVisible prop to the image component, but the image component still isn't updating when I return true from shouldComponentUpdate when the isVisible prop changes.
But to no avail.
I believe I'm on the right track, but have hit a dead end. Does anyone have an idea how I can force an image component to reload? Or is there some sort of onLoadInterrupted that might be added so that it begins loading again once it is in view?
Use a logic OR to combine your streams into only one stream:
public static void main(String[] args) { Stream<String> stream = Stream.of("abc", "aef", "bcd", "bef", "crf"); stream.filter(s -> s.startsWith("a") || s.startsWith("b")).forEach(System.out::println); }
-6427240 0 i dont understand why, adding an element on the list also fires a list selection.
Somewhere in your code you must be changing the selected index.
Download and test the ListDemo example for How to Use Lists. When you run the code and "Hire" a person, then the list selection event fires (I added a System.out.println(...) to the listener). Then if you comment out:
// list.setSelectedIndex(index); the event is not fired. So you have a problem in your code. Compare your code to the working example code to see what if different.
If you need more help then post a SSCCE that demonstrates the problem.
-25911398 0Probably you forgot about something...
li { display: list-item; } In your code there is display:inline which isn't list item and haven't list styles.
maybe try np.apply_along_axis:
>>> def my_func(a): ... """Average first and last element of a 1-D array""" ... return (a[0] + a[-1]) * 0.5 >>> b = np.array([[1,2,3], [4,5,6], [7,8,9]]) >>> np.apply_along_axis(my_func, 0, b) array([ 4., 5., 6.]) >>> np.apply_along_axis(my_func, 1, b) array([ 2., 5., 8.])
-26605732 0 Add the protocol (http:// or https:// for example), then the handler knows what to do:
System.Diagnostics.Process.Start("http://google.com"); Windows checks the file extension list, and that included protocols too. There it finds http maps to your browser. You can consider to be 'lucky' it detects www. too, but I wouldn't depend on it too much.
You can also build your application for "Any CPU" and dynamically choose which DLL to load.
-37855792 0You're on the right track. You can bind the AlternationCount to the length of your collection then create a style for the default items, and change it for first the rows:
<Style x:Key="differentItemsStyle" TargetType="{x:Type Label}"> <Setter Property="Foreground" Value="Red"></Setter> <Style.Triggers> <DataTrigger Binding="{Binding Path=(ItemsControl.AlternationIndex), RelativeSource={RelativeSource TemplatedParent}}" Value="0"> <Setter Property="Foreground" Value="Green"></Setter> </DataTrigger> <DataTrigger Binding="{Binding Path=(ItemsControl.AlternationIndex), RelativeSource={RelativeSource TemplatedParent}}" Value="1"> <Setter Property="Foreground" Value="Yellow"></Setter> </DataTrigger> </Style.Triggers> </Style> In your example you would have a default style for Option C, D, E which you can overwrite as you wish for Option A and Option B.
Edit In order to make this work for ListBox the binding needs to be changed:
<DataTrigger Binding="{Binding Path=(ItemsControl.AlternationIndex), RelativeSource={RelativeSource AncestorType=ListBoxItem}}" Value="1"> <Setter Property="Foreground" Value="Yellow"></Setter> </DataTrigger> See this answer for more info.
-35868561 0Here is how I would do.
app.js
(function(){ angular.module('app',[]); /* other code like configuration etc */ })(); SomeService.js
(function(){ angular.module('app'); .factory('someService',function(){ return { doSomething: function(){ $('.container-fluid').css('display', 'none'); } }; }); })(); app.run.js
(function(){ angular.module('app') //Inject your service here .run(function($rootScope,someService){ //Look for successful state change. //For your ref. on other events. //https://github.com/angular-ui/ui-router/wiki#state-change-events $rootScope.$on('$stateChangeSuccess', function() { //If you don't wanna create the service, you can directly write // your function here. someService.doSomething(); }); }) })(); Always wrap your angular code within IIFE it wraps everything in closure and prevents leaks as well as provides a layer of security.
Hope this helps!
-24993812 0 How can I write diagonal text in PHPI want to import some timestamps from a table and I want to write them diagonal under the graph. How can I do that?
here is my code, but not for the import data.
header("Content-type: image/png"); $img = imagecreate(100, 75); $bg = imagecolorallocate($img, 255, 255, 0); $black = imagecolorallocate($img, 0, 0, 0); $roles = array('anoniem', 'ingelogd', 'leerling', 'docent', 'rector'); $left = 0; foreach ($roles as $role) { imagestring ($img, 2, 0, $left, $role, $black); $left+= 15; } $img2 = imagerotate($img, 45, $bg); imagedestroy($img); imagepng($img2);
-12124574 0 You can't sort a table by default, but you have to do it programmatically. With a little bit of work you can write a reusable PhaseListener which you can control from your JSF page.
Make sure it only handles a single phase (for example PhaseId.RESTORE_VIEW) and use it to set the sort order using setSortCriteria:
List<SortCriterion> sortCriteria = new ArrayList<SortCriterion>(1); String property = "myProperty"; boolean ascending = true; sortCriteria.add(new SortCriterion(property, ascending)); myCoreTable.setSortCriteria(sortCriteria); Now you only have to add two <f:attribute/>s on your table to pass both the property name and the ascending boolean so you can create a reusable listener for all your tables.
In your <tr:document> you can have a <f:attribute/> with a list of table ID's to process.
Basically what i want to do is grab all CSS that is referenced in an external stylesheet e.g <link rel="stylesheet" href="css/General.css"> and append it to any existing styling for each HTML element in my page. (make all CSS inline)
The reason for this is because i need to call .html() to grab a div and send to server to be made into a PDF. The downside with this tool is that it only recognises inline CSS.
Are there any ways to do this?
Edit: the question that was linked to mine as a "possible duplicate" spoke only of putting everything in the <style> tag. while that may be useful, im mainly concerned with loading into the style="" html atribute
I am not sure about the bootsrap, But here is the generic way of approach to solve your problem.
HTML
<div class="main"> <div>one</div> <div>two</div> <div>three</div> <div>four</div> <div>five</div> <div>six</div> <div>seven</div> <div>eight</div> <div>nine</div> <div>ten</div> <div>eleven</div> <div>twelve</div> <div>thirteen</div> <div>fourteen</div> <div>fifteen</div> </div> CSS
.main div { float: right; width: 70px; } .main div:nth-child(6n + 7) { clear: right; }
-14051119 0 Here's one way using awk:
awk -F "[{}]" '{ for(i=1;i<=NF;i++) if ($i == "ctr") print $(i+1) }' file Or if your version of grep supports Perl-like regex:
grep -oP "(?<=ctr{)[^}]+" file Results:
StaffLine
-34517734 0 So... May be it should be in module Validatable?
...
base.class_eval do validates_presence_of :email, if: :email_required? validates_uniqueness_of :email, allow_blank: true, if: :email_changed? validates_format_of :email, with: email_regexp, allow_blank: true, if: :email_changed? validates_presence_of :password, if: :password_required? validates_confirmation_of :password, if: :password_required? validates_length_of :password, within: password_length, allow_blank: true validates_presence_of :question, if: :question_required? validates_format_of :question, with: answered_regexp, if: :answered_changed? end end ... def email_required? true end def question_required? true end This is not complied solution, but I hope it help You...
-24424720 0Your PHP does not have the LDAP extension installed or enabled. It's needed for AD authentication. Your distribution probably has a separate package for it. Eg. php5-ldap or something.
-4273975 0Have a look at this question, it is essentially asking the same thing - the principle does not change between DataGridView and ListBox. Short answer: it's possible, but convoluted.
My app accesses a spreadsheet from a user account, previously authenticad via the Google Plus Sign in button, all appropriate scopes and credentials have been selected in the Google API console, and I have a logged in GoogleApiClient with which I can access the user profile information.
When I attempt to initialize a SpreadSheetService object:
SpreadsheetService service = new SpreadsheetService("SpreadSheetImport-v1"); I get the exception related to the class com.google.common.collect.Maps:
10-30 13:50:34.280: D/SHEETS(17433): TRYING TO GET SPREADSHEET LIST! 10-30 13:50:34.280: D/AndroidRuntime(17433): Shutting down VM 10-30 13:50:34.280: E/AndroidRuntime(17433): FATAL EXCEPTION: main 10-30 13:50:34.280: E/AndroidRuntime(17433): Process: com.pazodediarada.dc, PID: 17433 10-30 13:50:34.280: E/AndroidRuntime(17433): java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/common/collect/Maps; 10-30 13:50:34.280: E/AndroidRuntime(17433): at com.google.gdata.wireformats.AltRegistry.<init>(AltRegistry.java:118) 10-30 13:50:34.280: E/AndroidRuntime(17433): at com.google.gdata.wireformats.AltRegistry.<init>(AltRegistry.java:100) 10-30 13:50:34.280: E/AndroidRuntime(17433): at com.google.gdata.client.Service.<clinit>(Service.java:555) 10-30 13:50:34.280: E/AndroidRuntime(17433): at com.pazodediarada.dc.SpreadSheetImport.getSpreadSheetDeutschList(SpreadSheetImport.java:356) 10-30 13:50:34.280: E/AndroidRuntime(17433): at com.pazodediarada.dc.SpreadSheetImport.onClick(SpreadSheetImport.java:146) 10-30 13:50:34.280: E/AndroidRuntime(17433): at android.view.View.performClick(View.java:4438) 10-30 13:50:34.280: E/AndroidRuntime(17433): at android.view.View$PerformClick.run(View.java:18422) 10-30 13:50:34.280: E/AndroidRuntime(17433): at android.os.Handler.handleCallback(Handler.java:733) 10-30 13:50:34.280: E/AndroidRuntime(17433): at android.os.Handler.dispatchMessage(Handler.java:95) 10-30 13:50:34.280: E/AndroidRuntime(17433): at android.os.Looper.loop(Looper.java:136) 10-30 13:50:34.280: E/AndroidRuntime(17433): at android.app.ActivityThread.main(ActivityThread.java:5001) 10-30 13:50:34.280: E/AndroidRuntime(17433): at java.lang.reflect.Method.invoke(Native Method) 10-30 13:50:34.280: E/AndroidRuntime(17433): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) 10-30 13:50:34.280: E/AndroidRuntime(17433): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) 10-30 13:50:34.280: E/AndroidRuntime(17433): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.common.collect.Maps" on path: DexPathList[[zip file "/data/app/com.pazodediarada.dc-2.apk"],nativeLibraryDirectories=[/data/app-lib/com.pazodediarada.dc-2, /vendor/lib, /system/lib]] 10-30 13:50:34.280: E/AndroidRuntime(17433): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56) 10-30 13:50:34.280: E/AndroidRuntime(17433): at java.lang.ClassLoader.loadClass(ClassLoader.java:511) 10-30 13:50:34.280: E/AndroidRuntime(17433): at java.lang.ClassLoader.loadClass(ClassLoader.java:469) 10-30 13:50:34.280: E/AndroidRuntime(17433): ... 14 more 10-30 13:50:34.280: E/AndroidRuntime(17433): Suppressed: java.lang.ClassNotFoundException: com.google.common.collect.Maps 10-30 13:50:34.280: E/AndroidRuntime(17433): at java.lang.Class.classForName(Native Method) 10-30 13:50:34.280: E/AndroidRuntime(17433): at java.lang.BootClassLoader.findClass(ClassLoader.java:781) 10-30 13:50:34.280: E/AndroidRuntime(17433): at java.lang.BootClassLoader.loadClass(ClassLoader.java:841) 10-30 13:50:34.280: E/AndroidRuntime(17433): at java.lang.ClassLoader.loadClass(ClassLoader.java:504) 10-30 13:50:34.280: E/AndroidRuntime(17433): ... 15 more 10-30 13:50:34.280: E/AndroidRuntime(17433): Caused by: java.lang.NoClassDefFoundError: Class "Lcom/google/common/collect/Maps;" not found 10-30 13:50:34.280: E/AndroidRuntime(17433): ... 19 more My IDE is Eclipse ADT, I have imported the google api libraries as per Google Sheets Api, both with this method described there or adding external jars, obtaining the same results.
Any ideas?
-7067802 0(EDIT: CKoenig has a nice answer.)
Hm, I didn't immediately see a way to do this either.
Here's a non-type-safe solution that might provide some crazy inspiration for others.
open System.Collections.Generic module Dict = type Dictionary<'K, 'V> with member this.Difference<'K2, 'T when 'K2 : equality>(that:Dictionary<'K2, 'T>) = let dict = Dictionary<'K2,'V>() for KeyValue(k, v) in this do if not (that.ContainsKey(k |> box |> unbox)) then dict.Add(k |> box |> unbox, v) dict open Dict let d1 = Dictionary() d1.Add(1, "foo") d1.Add(2, "bar") let d2 = Dictionary() d2.Add(1, "cheese") let show (d:Dictionary<_,_>) = for (KeyValue(k,v)) in d do printfn "%A: %A" k v d1.Difference(d2) |> show let d3 = Dictionary() d3.Add(1, 42) d1.Difference(d3) |> show let d4 = Dictionary() d4.Add("uh-oh", 42) d1.Difference(d4) |> show // blows up at runtime Overall it seems like there may be no way to unify the types K and K2 without also forcing them to have the same equality constraint though...
(EDIT: seems like calling into .NET which is equality-constraint-agnostic is a good way to create a dictionary in the absence of the extra constraint.)
-22417084 0If you actually add a tip, it works fine
$(".well").attr("title", "This is a tooltip");
-32437204 0 I hope you access your fields by pair of get/set methods. Just make null-checking logic inside getter:
public Second getRelated(){ if( second == null ) return defaultValue; } Please also see this answer http://stackoverflow.com/a/757330/149818
-6578373 0 sleep in emacs lisp (insert (current-time-string)) (sleep-for 5) (insert (current-time-string)) M-x eval-buffer, two time strings are inserted with 5 secs apart
some comint code (that add hook, and start process)
(sleep-for 60) ;delay a bit for process to finish (insert "ZZZ") M-x eval-buffer, "ZZZ" is inserted right away, without any time delay
what might have happened? btw, it's Emacs 23.2 on Win XP
-29052508 0 Sending email Intent with EXTRA_STREAM crashes with GMailI'm trying to send an email from my app with attachment. When the chooser pops up, if I tap on GMail, GMail crashes; if I tap on the default email client of my device, it works perfectly. The attachment is a jpeg taken from the external sd.
Here the code:
filelocation = gv.getPath(); Intent emailIntent = new Intent(Intent.ACTION_SEND); // set the type to 'email' emailIntent.setType("image/jpeg"); String to[] = {"myemailaddress@gmail.com"}; emailIntent.putExtra(Intent.EXTRA_EMAIL, to); // the attachment emailIntent.putExtra(Intent.EXTRA_STREAM, filelocation); // the mail subject emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject"); emailIntent.putExtra(Intent.EXTRA_TEXT, "Body"); emailIntent.setType("message/rfc822"); startActivity(Intent.createChooser(emailIntent, "Send email using:")); Here the logcat:
03-14 19:03:26.081 27428-27428/com.android.myapp W/Bundle﹕ Key android.intent.extra.STREAM expected Parcelable but value was a java.lang.String. The default value <null> was returned. 03-14 19:03:26.111 27428-27428/com.android.myapp W/Bundle﹕ Attempt to cast generated internal exception: java.lang.ClassCastException: java.lang.String cannot be cast to android.os.Parcelable at android.os.Bundle.getParcelable(Bundle.java:1171) at android.content.Intent.getParcelableExtra(Intent.java:4493) at android.content.Intent.migrateExtraStreamToClipData(Intent.java:7032) at android.content.Intent.migrateExtraStreamToClipData(Intent.java:7017) at android.app.Instrumentation.execStartActivity(Instrumentation.java:1548) at android.app.Activity.startActivityForResult(Activity.java:3409) at android.app.Activity.startActivityForResult(Activity.java:3370) at android.support.v4.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:826) at android.support.v4.app.Fragment.startActivity(Fragment.java:896) at com.android.myapp.steps.Passo3$2.onClick(Passo3.java:100) at android.view.View.performClick(View.java:4107) at android.view.View$PerformClick.run(View.java:17160) at android.os.Handler.handleCallback(Handler.java:615) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:155) at android.app.ActivityThread.main(ActivityThread.java:5536) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1074) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:841) at dalvik.system.NativeStart.main(Native Method) Any suggestion? Every help will be greatly appreciated! :)
-13495137 0Here's one way using GNU awk:
awk -F "[()]" 'FNR==NR { a[$(NF-1)]++; next } !(gensub(/(.*),.*/,"\\1","g",$(NF-1)) in a)' File1 File2 Results:
INSERT INTO Queue (course,student,registrationDate) VALUES ('BKE974','3421728825','1368144500'); INSERT INTO Queue (course,student,registrationDate) VALUES ('DQY359','7421758823','1375874278');
-17047305 0 Each time you click, you call this function.
function tableClick(event){ $('#table').click(function(event){ alert(event.target.id); }); } This part:
$('#table').click(function(event){ attaches a click handler to the table. Every time you click you attach a new click handler to the table.
-13562355 0 Predefined subject and body in EmailComposerIs there any way to predefine body and subject of email in emailcomposer ios phonegap plugin? So far i found some group in google groups
window.plugins.emailComposer.showEmailComposer("My Subject","My Plain Text Body", "recip...@email.com,recipient2@email.com", "ccReci...@email.com,ccRecipient2@email.com", "bccRec...@email.com,bccRecipient2@email.com",false); but i'm not sure how to connect that to my html page. I tried
cordova.exec(null, null, "EmailComposer", "showEmailComposer", [args]); in my js file, but that shows emailcomposer page, which is unacceptable. How do i make user enter only email or recipient?
UPD: I didnt look into emailcomposer.js, there is array [args], where i can define everything i need, but i'm not sure how to do that Tried this way, but that didnt help
var args = [toRecipients="example@email.com"];
-37102304 0 Thats because your Tag is Null (or as it's called in VB Nothing). So before you check the length of the Tag, you need to make sure it's not Nothing. e.g with:
If Control.Tag Is Nothing Then ...
-34090237 0 SIP response codes are splitted in 6 classes
1xx: Provisional — request received, continuing to process the request; Provisional responses, also known as informational responses, indicate that the server contacted is performing some further action and does not yet have a definitive response. A server sends a 1xx response if it expects to take more than 200 ms to obtain a final response. Note that 1xx responses are not transmitted reliably. They never cause the client to send an ACK. Provisional (1xx) responses MAY contain message bodies, including session descriptions.
2xx: Success — the action was successfully received, understood, and accepted;
3xx: Redirection — further action needs to be taken in order to complete the request;
4xx: Client Error — the request contains bad syntax or cannot be fulfilled at this server;
5xx: Server Error — the server failed to fulfill an apparently valid request;
6xx: Global Failure — the request cannot be fulfilled at any server.
Here you can find PJSIP struct which holds these codes and SIP codes description
select g.person_id from @person_groups g inner join @tempGroupList l on g.group_id = l.group_id group by g.person_id having count(distinct g.group_id) = (select count(*) from @tempGroupList); To explain slightly. The inner join restricts us to just the groups in question. The group by allows us to calculate the number of different (distinct) groups each person is in. The having filters down to the people in the right number of distinct groups.
If a person can only appear once in each group (i.e. group_id, person_id is a unique combination in @person_groups) then you don't need the distinct.
Most likely Dependency. Associations are normally used to capture some relationship that has meaningful semantics in a domain. So, for example, Secretary 'works for' Manager. Your example is different: you're not capturing meaningful relationships among instances. Therefore Dependency is probably most appropriate.
More importantly though: what are you trying to illustrate? Remember to use UML like any other tool - make it work for you. So, for example, it's fine to show a binary association if (a) it helps you and/or (b) it helps you communicate with other team members. The fact that it doesn't comply with the intended UML usage doesn't matter - as long as you find it useful.
hth.
-8039305 0 Can't get Map/Reduce to work with MongoDBI've got this code:
// construct map and reduce functions $map = new MongoCode(" function() { ". "var key = {date: this.timestamp.getFullYear()+this.timestamp.getMonth()+this.timestamp.getDate()};". "emit(key, {count: 1}); }" ); $reduce = new MongoCode(" function(k, vals) { ". "var sum = 0;". "for (var i in vals) {". "sum += vals[i];". "}". "return sum;". "}" ); $dates = $db->command(array( "mapreduce" => "items", "map" => $map, "reduce" => $reduce, //"query" => array("type" => "sale"), "out" => array("merge" => "distinct_dates") ) ); But get this error when testing:
Array ( [assertion] => map invoke failed: JS Error: TypeError: this.timestamp.getFullYear is not a function nofile_b:0 [assertionCode] => 9014 [errmsg] => db assertion failure [ok] => 0 ) Cron run finished.
Each object in the collection has a timestamp, from which I want to extract a date (Ymd), and put each distinct date in a new collection.
-104890 0 Dealing with the rate of change in software developmentI am primarily a .NET developer, and in that sphere alone there are at any given time probably close to a dozen fascinating emerging technologies, some of them real game-changers, that I would love to delve into.
Sadly, this appears to be beyond the limits of human capacity.
I read an article by Rocky Lhotka (.NET legend, inventor of CSLA, etc) where he mentioned, almost in passing, that last year he felt very terribly overwheled by the rate of change. He made it sound like maybe it wasn't possible to stay on the bleeding edge anymore, that maybe he wasn't going to try so hard because it was futile.
It was a surprise to me that true geniuses like Lhotka (who are probably expected to devote a great deal of their time to playing with the latest technology and should be able to pick things up quickly) also feel the burn!
So, how do you guys deal with this? Do you just chalk it up to the fact that development is vast, and it's more important to be able to find things quickly than to learn it all? Or do you have a continuing education strategy that actually allows you to stay close to the cutting edge?
-7865724 0 How would I use regex to obtain a piece of a link?Current code:
public static void WhoIsOnline(string worldName, WhoIsOnlineReceived callback) { string url = "http://www.tibia.com/community/?subtopic=worlds&world=" + worldName; HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.BeginGetResponse(delegate(IAsyncResult ar) { string html = GetHTML(ar); MatchCollection matches = Regex.Matches(html, @"<TD WIDTH=70%><[^<]*>([^<]*)</A></TD><TD WIDTH=10%>([^<]*)</TD><TD WIDTH=20%>([^<]*)</TD></TR>"); List<CharOnline> chars = new List<CharOnline>(matches.Count); CharOnline co; for(int i = 0; i < matches.Count; i++) { co = new CharOnline(); co.Name = Prepare(matches[i].Groups[1].Value); co.Level = int.Parse(matches[i].Groups[2].Value); co.Vocation = Prepare(matches[i].Groups[3].Value); chars.Add(co); } callback(chars); }, request); } I was using this to scrape the online list, but they have changed their layout and I'm not sure how to change the regex to get the same information.
http://www.tibia.com/community/?subtopic=worlds&world=Libera
The link I am trying to use above.
-20890556 0Build with the static runtime libraries rather than the DLL versions.
Go to Properties, C/C++, Code Generation, Runtime Library and select /MTd or /MT rather than the /MDd and /MD options.
-7073300 0Try using the following attribute
[ServiceKnownType(typeof(List<string>))] If that doesn't work, perhaps try using IList<T> if that is possible in your situation
I just Find a solution to walk-through this problem. i take a instant screenshot and show it. Thanks to Radu Motisan for his tutorial. the solution use JNI instead of other way using external Library.
Here is the link : http://www.pocketmagic.net/?p=1473
-28175581 0 How to compile dependencies using cmake?Given that I have the following file structure,
my_project CMakeLists.txt /include ...headers /src ...source files /vendor /third-party-project1 CMakeLists.txt /third-party-project2 CMakeLists.txt How do I use the third party projects by compiling them according to their CMakeLists.txt files from my own CMake file? I specifically need their include dirs, and potentially any libs they have.
Furthermore, how could I use FIND_PACKAGE to test if the third party projects are installed in the system, and if they don't compile and link against the included ones?
-11781931 0As mentioned in the comments of the laxbreak answer, laxcomma option should actually be used for this particular situation (it has been implemented in the meantime). See http://jshint.com/docs/options/ for details.
I have a relative layout which consists a Button a EditText
At the time of page loading I am initializing the relative layout like this
RelativeLayout bottomLayout; bottomLayout = (RelativeLayout) findViewById(R.id.s_r_l_bottom); RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) bottomLayout .getLayoutParams(); layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, -1); bottomLayout.setLayoutParams(layoutParams ); As a result my relative layout was at the bottom of the screen. Now what I am trying that I also have Button on the top the screen .
By pressing the button I want that the relative layout will be on the center of the screen
For that I have used the following code on button click(The code is executing.I have tested that).But it did not help me.
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) bottomLayout.getLayoutParams(); layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, -1); bottomLayout.setLayoutParams(layoutParams); Can you please help me out to fix this?
-38430119 0Try this:
SELECT * FROM table_name WHERE date_time + INTERVAL 90 DAY <= NOW()
-27112569 0 X-Editable and Bootstrap datatables I've tried with no success to implement x-editable in bootstrap datatables, the reason being when i update an element from x editable, the datatable fails to recognize those changes.. i've tried updating the table, destroying it, hidden tags, but the main problem seems to be that the datatables fails to recognize any change after the initialization.. I add the rows via button click, when they get to the table, i run .editable on those elements. they become editable but the sorting and search of the datatables doesnt work..
Can anyone help me?
-18517317 0Run "Clean" followed by "Rebuild" using Visual Studio. This fixed the problem for me.
-7387540 0RewriteCond %{HTTP_HOST} !^admin\.example.com$ [OR] RewriteCond %{HTTP_HOST} !^login\.example.com$ [OR] RewriteCond %{HTTP_HOST} !^logout\.example.com$ RewriteCond %{HTTP_HOST} -(.{5})\.example.com RewriteRule (.*) http://example.com/something/maybesomethingelse/-%1 I did not test it but I think it works!let me know if not!
-33870111 0 Select2 not selecting first item as defaultI am populating a drop down list in an ASP.Net page using this code
var xhttp xhttp = new XMLHttpRequest(); xhttp.open("GET", "../XMLHttp/XMLHttp_GetRDRegions.aspx?RDDivision=" + encodeURIComponent(document.getElementById('ddlRDDivisions').value), false); xhttp.send(); document.getElementById('ddlRDRegions').options.length = 0; document.getElementById('ddlRDCentres').options.length = 0; document.getElementById('ddlRMNames').options.length = 0; var ddlRDRegions = document.getElementById('ddlRDRegions'); var element = document.createElement('option'); element.text = '--- Please Select an item ---' element.value = '0' ddlRDRegions.options.add(element); When not using Select the new element I am adding is the first selected item in the list, however when applying the Select2 in the javascript too like this.
$('select').select2(); the element is at the top of the list but is not the selected element.
I have tried creating an attribute like this
var att = document.createAttribute("selected"); att.value = "selected"; element.setAttribute(att) which throws an error and this
$(element).attr("selected", "selected") which does nothing.
Any and all help on where I am going wrong would be very much appreciated.
-16882698 0 Strange behaviour of RichFaces a4j.jsFunctionmy problem is simple. Im using RichFaces 4.3.2 final and making programatically dynamic panelMenu. I managed to do that and use setOnClick("menuGroupAction('"+labelOfGroup+"')") to each UIPanelMenuGroup and UIPanelMenuItem. labelOfGroup varies depending on items from DB. menuGroupAction is a4j:jsAction used as:
<h:form> <a4j:jsFunction name="menuGroupAction" actionListener="#{leftMenu.updateCurrent}" render=":contentForm:test" > <a4j:param name="param1" /> </a4j:jsFunction> </h:form> Problem is when i click on the TOP submenu param1 is changing as expected, but when i try to click on any inner submenu onclick is fired BUT with param1 of its top menu, even though the inner submenu has onclick="menuGroupAction('itslabel')". Any idea why is it happening? Im checking which parametter was posted with
String param1 = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("param1");
Another thing, when clicked on UIMenuItem in any submenu there are actually TWO calls of menuGroupAction, one with param of Top menu and another with correct param of menuItem. Thanks for response and sorry for bad english.
UPDATE
heres how i use rich:panelMenu on page
<h:form> <rich:panelMenu binding="#{leftMenu.menuCategories}" groupMode="ajax" itemMode="ajax" bubbleSelection="false" ></rich:panelMenu> </h:form> heres getter for panelMenu model menuCategories
/** * @return the menuCategories */ public UIPanelMenu getMenuCategories() { if(menuCategories == null){ menuCategories = menuService.createCategoriesUIPanelMenu(); } return menuCategories; } and heres how i create UIPanelMenu
public UIPanelMenu createCategoriesUIPanelMenu(){ List<Category> allTopCategories = catOper.getAllTopCategories(); int menulevel = 1; sortByOrderOfCategories(allTopCategories); UIPanelMenu categories = new UIPanelMenu(); categories.setTopGroupClass("button"); for (Category category : allTopCategories) { UIPanelMenuGroup topMenuCategory = new UIPanelMenuGroup(); topMenuCategory.setLabel(category.getName()); topMenuCategory.setOnclick("menuGroupAction('"+category.getName()+"')"); rekursiveCategoriesMenuGroupSetter(topMenuCategory,category,menulevel); categories.getChildren().add(topMenuCategory); } return categories; } private UIPanelMenuGroup rekursiveCategoriesMenuGroupSetter(UIPanelMenuGroup parent, Category category, int menuLevel){ int level = menuLevel+1; List<Category> allTopCategories = (List<Category>) category.getCategoryCollection(); sortByOrderOfCategories(allTopCategories); for (Category child : allTopCategories) { if(!child.getCategoryCollection().isEmpty()){ UIPanelMenuGroup subGroup = new UIPanelMenuGroup(); subGroup.setLabel(child.getName()); subGroup.setLeftIconClass("menuLevel"+level); subGroup.setOnclick("menuGroupAction('"+child.getName()+"')"); parent.getChildren().add(subGroup); rekursiveCategoriesMenuGroupSetter(subGroup,child,level); } else{ UIPanelMenuItem item = new UIPanelMenuItem(); item.setLabel(child.getName()); item.setLeftIconClass("menuLevel"+level); item.setOnclick("menuGroupAction('"+child.getName()+"')"); parent.getChildren().add(item); } } return parent; } UPDATE
Strange i tried it on clean page and come to some interesting news. When theres set default groupMode aka 'client' that when clicked on some inner group there are TWO calls of that action one with top submenu param and one with correct param of innersubmenu (same with server), which is a little step forward i suppose in comparison to calling ONLY with top submenu.
-18937561 0Add padding-left: 0 to your ul style declaration.
#pricing_plan1 ul, #pricing_plan2 ul, #pricing_plan3 ul { list-style: none; font-family: "Helvetica Neue"; border: 1px solid #d9dee1; padding-left: 0px; } <ul> has default left padding, and that's the reason of your code output.
Check jsFiddle demo. Both lists have list-style set to none, but only the second one has additional left-padding: 0. As you can see, the first one has exactly the same problem you're trying to solve.
I am not an expert on javascript, and I am currently trying to breakdown a previous programmer's code.
He has a window called ADD ACCOUNT that opens up, and you can either make your selections via dropdown selects or by dragging and dropping another account directly onto the window.
What I want to do is when the user changes their mind, and they close the window, it should automatically reset all the filters. The user is not actually hitting the reset button. They are just closing the window.
Right now, if they close it and open it back up, the previous selection they made are still there.
I've been looking through the code, and I found this:
var AddAccountWindow = new Ext.Window({ title: 'Add Account', closable:true, closeAction:'hide', y:5, width: 735, height:editPnlHeight-25, plain:true, layout: 'fit', stateful:false, items: AddAcountForm }); Is there anyway I can add a reset feature that will automatically fire when they close the window with the code I provided above?
Or do I have to create another function that will fire on close?
-27223288 0I did following code :
<script src="${resource(dir: 'js', file: 'jquery.zclip.js')}"></script> <script src="${resource(dir: 'js', file: 'jquery.zclip.min.js')}"></script> <script> function copyToClipboard(){ $("#copyLink").zclip({ path: "/js/ZeroClipboard.swf", copy: $("#genCampUrl").val(), afterCopy:function(){ alert('copied'); } }); } </script> <a id="copyLink" onclick="copyToClipboard();">Copy this url</a> On localhost it doesn't work. As the movie needs to be uploaded somewhere. But on server, it works.
-38038098 0 rmarkdown html page loaded with warning messageI have created simple rmarkdown - flexboard html page, using MASS/painters dataset, preview looks fine, but as soon as view in browser, the html page loads with warning, with below below errors.
Please note I have used rpivottable and DT to present painters data. Any guidance would be helpful.
title: "Untitled" output: flexdashboard::flex_dashboard: orientation: columns vertical_layout: fill --- ```{r setup, include=FALSE} library(flexdashboard)``` Column {data-width=650}
### Chart A ```{r} ``` Column {data-width=350} ### Chart B ```{r} ``` ### Chart C ```{r} ``` Webpage error details
User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; chromeframe/15.0.874.121; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; MS-RTC LM 8; InfoPath.3; .NET CLR 1.1.4322) Timestamp: Thu, 23 Jun 2016 10:58:22 UTC
Message: '$' is undefined Line: 833 Char: 5 Code: 0
Message: Object expected Line: 2562 Char: 1 Code: 0
Message: Object expected Line: 2599 Char: 1 Code: 0
You do not see the message from circle because circle is part of the group and thus, only one of the event "dragstart" can be recognized either on the group or the circle, when you try to move circle the event is recognized for the group as circle is part of the group. You can probably add a check inside the function associated with "dragstart" for group to check if the object selected is "circle" and show your message.
-34295014 0 Show/hide subpanels dynamically in Ext JSI have created a view (a panel) with 3 subpanels ... When the view loads , I want a function to run in viewController and based on its outcome , I want subpanel 1 to be visible(subpanel2 to be invisible) or subpanel2 to be visible(subpanel1 to be invisible)
How can I accomplish this ?
-29146275 0You'll need the client-side library to connect to the server. You can fetch it at your domain.com/socket.io/socket.io.js and cache it locally. From there you can access global io and then connect with:
var socket = io.connect(); It may be even better to copy the library into your application and have a background service that fetches the newest version every x days/weeks.
-5861584 0It is possible with TPC inheritance but it will include a lot of complication to your design. For example:
ObjectSet<Tasks> and you will have to use OfType to query only Projects or ServicesTask = across both Project and Service tables (can be achieved by correctly configured identities in database)It will look like:

Another option is using interface on your entity objects instead of parent class. You can define interface in your partial part of entity object and handle retrieving both Projects and Services by yourselves where your UI will expect only list of types implementing your interface.
-35923144 0 Test CharSequences for equality in JUnitThe following test runs successfully:
assertEquals(a.toString(), b.toString()); The following does not:
assertEquals(a, b); a is a StringBuilder, while b is a CharSequence of a different type.
Is there some way to test CharSequences for equality without converting them to Strings first?
I tried to add gif image into a canvas and after adding, gif was static but when I change some other object property, i.e. Kinetic.Text();s setY() property, gif image moved to another step of an animation.
Is any way, how to to add gif image into a layer and then use
stage.toDataURL({ callback: function(dataUrl) { //callback }) }); to save as a gif image? Or does exist any different mechanism how to achieve this effect?
-4429759 0Try changing the order of the handlers (remove then add). In this example I have removed all but the AJAX/script handler.
<system.webServer> <modules runAllManagedModulesForAllRequests="true" /> <handlers> <remove name="WebServiceHandlerFactory-Integrated"/> <remove name="WebServiceHandlerFactory-ISAPI-2.0"/> <remove name="WebServiceHandlerFactory-ISAPI-2.0-64"/> <remove name="WebServiceHandlerFactory-ISAPI-4.0_32bit"/> <remove name="WebServiceHandlerFactory-ISAPI-4.0_64bit"/> <!--<add name="WebServiceHandlerFactory-Integrated-4.0" ...</handlers>
-32398604 0 Add a global boolean, for instance:
private bool isDragAndDrop; Set it to false when loading the form. When the dragAndDrop event is fired you should set isDragAndDrop = true.
When the Click event is fired you check if(!isDragAndDrop) This will or will not execute the code inside the click event based on the value on the isDragAndDrop -variable.
Before leaving the click event you the set isDragAndDrop = false
When using get_template_part, the first parameter defines the base template name (e.g. content, which loads content.php) and the second parameter loads a suffixed version if available. Therefore your call
get_template_part('content', 'single-ourNews'); is looking for a file named content-single-ourNews.php first, then falls back to content.php in case the first one is not available. I'm not sure whether the get_template_part function converts the suffix parameter to something like single-ournews or single-our-news before appending it to the first parameter, be sure to test a few variants of that.
I'm not 100% sure if the function behaves differently or not in child themes and parent themes. One option is to override the parent's single.php in the child theme and modify it directly with
if ($post->post-type === 'ourNews') { get_template_part('content', 'single-ourNews'); } else { get_template_part('content'); } Lastly, WordPress will look for a file single-[cptslug].php before loading a template for a custom post type's single view.
TEX is a typesetting system written by Donald E. Knuth. MiKTEX is an up-to-date implementation of TEX and related programs for Windows (all current variants).
Is there .NET implementation of TEX?
-40130528 0To upload large binary files using CURL you'll need to use --data-binary flag.
In my case it was:
curl -X PUT --data-binary @big-file.iso https://example.com Note: this is really an extended version of @KarlC comment, which actually is the proper answer.
-31379457 0Syntex error in closing of if block syntex.
1 <% if current_user.admin? && !current_user?(user) %> 2 <li><%= link_to "Admin", users_path %></li> 3 </end> Error at line 3, replace line 3 ie </end> with <% end %>
I'm trying to setup a login form for my application and it is the UIPickerView is not showing the row data. What I am seeing is that the numberOfRowsInComponent is being called twice? But titleForRow is only being called once per row.
Debug output:
2011-06-07 11:07:31.096 myECG[19689:207] numberOfRowsInComponent: 2 : 0 2011-06-07 11:07:31.096 myECG[19689:207] numberOfRowsInComponent: 2 : 0 2011-06-07 11:07:31.098 myECG[19689:207] USA : 0 2011-06-07 11:07:31.098 myECG[19689:207] Canada : 0 LoginViewController.h
#import <UIKit/UIKit.h> @interface LoginViewController : UIViewController <UIPickerViewDataSource, UIPickerViewDelegate> { IBOutlet UITextField *emailField; IBOutlet UITextField *passswordField; IBOutlet UIButton *loginButton; IBOutlet UIActivityIndicatorView *loginIndicator; IBOutlet UIPickerView *pickerView; NSMutableArray *sites; } @property (nonatomic, retain) UITextField *emailField; @property (nonatomic, retain) UITextField *passwordField; @property (nonatomic, retain) UIButton *loginButton; @property (nonatomic, retain) UIActivityIndicatorView *loginIndicator; @property (nonatomic, retain) UIPickerView *pickerView; @property (nonatomic, retain) NSMutableArray *sites; -(IBAction) login:(id) sender; @end LoginViewController.m #import "LoginViewController.h" #import "myECGViewController.h"
@implementation LoginViewController @synthesize emailField, passwordField, loginButton, loginIndicator, pickerView, sites; - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } //NSLog(@"%@", sites); return self; } - (void)dealloc { [super dealloc]; } - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } #pragma mark - View lifecycle - (void)viewDidLoad { [super viewDidLoad]; sites = [[NSMutableArray alloc] init]; [sites addObject:@"Canada"]; [sites addObject:@"USA"]; //[pickerView selectRow:1 inComponent:0 animated:YES]; // Do any additional setup after loading the view from its nib. } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return NO; } -(IBAction) login:(id) sender { loginIndicator.hidden = FALSE; [loginIndicator startAnimating]; loginButton.enabled = FALSE; // Do login NSLog(@"E:%@ P:%@", emailField.text, passswordField.text); } -(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView { return 1; } -(NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { NSLog(@"%@ : %d", [sites objectAtIndex:row], component); return [sites objectAtIndex:row]; } - (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component { NSLog(@"numberOfRowsInComponent: %d : %d", [sites count], component); return [sites count]; } -(void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { NSLog(@"Selected: %@", [sites objectAtIndex:row]); } @end Any help is appreciated.
-9268642 0My guess, you need to add i=0; at the beginning.
-21011149 0Do you have the methods for it? If you don't try get the methods out first by using:
print server.system.listMethods() After you found out your method, get the signature so it's easier for you to do a search on it.
-7662456 0From the C++ Standard ( Working Draft ), section 5 on binary operators
Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows: — If either operand is of scoped enumeration type (7.2), no conversions are performed; if the other operand does not have the same type, the expression is ill-formed. — If either operand is of type long double, the other shall be converted to long double. — Otherwise, if either operand is double, the other shall be converted to double. — Otherwise, if either operand is float, the other shall be converted to float.
And also section 4.8
A prvalue of floating point type can be converted to a prvalue of another floating point type. If the source value can be exactly represented in the destination type, the result of the conversion is that exact representation. If the source value is between two adjacent destination values, the result of the conversion is an implementation-defined choice of either of those values. Otherwise, the behavior is undefined
The upshot of this is that you can avoid unnecessary conversions by specifying your constants in the precision dictated by the destination type, provided that you will not lose precision in the calculation by doing so (ie, your operands are exactly representable in the precision of the destination type ).
-7705539 0It might be tricky to implement the same type of interface, but you could have your ListView respond to the contents of a TextBox by handling the TextBox's TextChanged event and filtering the list based on the contents. If you put the list in a DataTable then filtering will be easy and you can repopulate your ListView each time the filter changes.
Of course this depends on how many items are in your list.
-12271011 01) please read tutorial about JTable that's contains TableRowSorter example, issue about RowSorter must be in your code
2) by default you can to use follows definition for ColumnClass,
public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } 3) or you can to hardcode that
@Override public Class<?> getColumnClass(int colNum) { switch (colNum) { case 0: return Integer.class; case 1: return Double.class; case 2: return Long.class; case 3: return Boolean.class; case 4: return String.class; case 5: return Icon.class; default: return String.class; } } 4) or override RowSorter (notice crazy code)

import com.sun.java.swing.Painter; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Graphics2D; import java.util.ArrayList; import java.util.List; import javax.swing.*; import javax.swing.table.*; public class JTableSortingIconsForNimbus extends JFrame { private static final long serialVersionUID = 1L; private JTable table; private JTable table1; private static Icon ascendingSortIcon; private static Icon descendingSortIcon; public JTableSortingIconsForNimbus() { Object[] columnNames = {"Type", "Company", "Shares", "Price"}; Object[][] data = { {"Buy", "IBM", new Integer(1000), new Double(80.50)}, {"Sell", "MicroSoft", new Integer(2000), new Double(6.25)}, {"Sell", "Apple", new Integer(3000), new Double(7.35)}, {"Buy", "Nortel", new Integer(4000), new Double(20.00)} }; DefaultTableModel model = new DefaultTableModel(data, columnNames) { private static final long serialVersionUID = 1L; @Override public Class getColumnClass(int column) { return getValueAt(0, column).getClass(); } }; table = new JTable(model) { private static final long serialVersionUID = 1L; @Override public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { Component c = super.prepareRenderer(renderer, row, column); int firstRow = 0; int lastRow = table.getRowCount() - 1; if (row == lastRow) { ((JComponent) c).setBackground(Color.red); } else if (row == firstRow) { ((JComponent) c).setBackground(Color.blue); } else { ((JComponent) c).setBackground(table.getBackground()); } return c; } }; table.setPreferredScrollableViewportSize(table.getPreferredSize()); JScrollPane scrollPane = new JScrollPane(table); add(scrollPane, BorderLayout.NORTH); table1 = new JTable(model) { private static final long serialVersionUID = 1L; @Override public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { Component c = super.prepareRenderer(renderer, row, column); int firstRow = 0; int lastRow = table1.getRowCount() - 1; if (row == lastRow) { ((JComponent) c).setBackground(Color.red); } else if (row == firstRow) { ((JComponent) c).setBackground(Color.blue); } else { ((JComponent) c).setBackground(table1.getBackground()); } return c; } }; table1.setPreferredScrollableViewportSize(table1.getPreferredSize()); JScrollPane scrollPane1 = new JScrollPane(table1); //UIDefaults nimbusOverrides = new UIDefaults(); //nimbusOverrides.put("Table.ascendingSortIcon", ascendingSortIcon); //nimbusOverrides.put("Table.descendingSortIcon", descendingSortIcon); //table1.putClientProperty("Nimbus.Overrides", nimbusOverrides); //UIManager.getLookAndFeelDefaults().put("Table.ascendingSortIcon", ascendingSortIcon); //UIManager.getLookAndFeelDefaults().put("Table.descendingSortIcon", descendingSortIcon); UIManager.getLookAndFeelDefaults().put("TableHeader[Enabled].ascendingSortIconPainter", new FillPainter1(new Color(255, 255, 191))); UIManager.getLookAndFeelDefaults().put("TableHeader[Enabled].descendingSortIconPainter", new FillPainter1(new Color(191, 255, 255))); SwingUtilities.updateComponentTreeUI(table1); add(scrollPane1, BorderLayout.SOUTH); TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(table.getModel()) { @Override public void toggleSortOrder(int column) { if (column >= 0 && column < getModelWrapper().getColumnCount() && isSortable(column)) { List<SortKey> keys = new ArrayList<SortKey>(getSortKeys()); if (!keys.isEmpty()) { SortKey sortKey = keys.get(0); if (sortKey.getColumn() == column && sortKey.getSortOrder() == SortOrder.DESCENDING) { setSortKeys(null); return; } } } super.toggleSortOrder(column); } }; table.setRowSorter(sorter); table1.setRowSorter(sorter); } static class FillPainter1 implements Painter<JComponent> { private final Color color; public FillPainter1(Color c) { color = c; } @Override public void paint(Graphics2D g, JComponent object, int width, int height) { g.setColor(color); g.fillRect(0, 0, width - 1, height - 1); } } public static void main(String[] args) { try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); ascendingSortIcon = UIManager.getLookAndFeelDefaults().getIcon("Table.ascendingSortIcon"); descendingSortIcon = UIManager.getLookAndFeelDefaults().getIcon("Table.descendingSortIcon"); UIManager.getLookAndFeelDefaults().put("TableHeader[Enabled].ascendingSortIconPainter", new FillPainter1(new Color(127, 255, 191))); UIManager.getLookAndFeelDefaults().put("TableHeader[Enabled].descendingSortIconPainter", new FillPainter1(new Color(191, 255, 127))); } catch (Exception fail) { } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JTableSortingIconsForNimbus frame = new JTableSortingIconsForNimbus(); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } }
-17380924 0 Session data is stored server-side.
Cookie data is stored client-side.
-10053153 0 Exceptions in J2MEI am developing an mobile application using j2me.In that i am using kxml parser.In my application i have to call an url to get the data.When i am calling that url sometimes it showing:
java.lang.IllegalStateException: update of non-existent node Exception. My sample code is:
InputStreamReader isr=null; InputStream rssStream=null; InputStream is = null; HttpConnection conn=null; try { conn = (HttpConnection)Connector.open(rssUrl); rssStream = conn.openInputStream();---------->I think exception is shown here. isr = new InputStreamReader( rssStream ); parser.setInput(isr); parser.nextTag();
-17646349 0 You've definitely hit across an interesting problem with WinPcap. Its protocol driver (NPF) expects to be able to open an adapter whenever it wants. When paired with Wireshark, it will do this frequently — it's typical to see NPF open and close the same adapter dozens of times just while the Wireshark GUI is loading. It's even possible to see NPF have multiple bindings to the same adapter simultaneously.
The rough equivalent of this in NDIS 6.x is the NdisReEnumerateProtocolBindings function. What this does is queue up a workitem to call into your protocol' ProtocolBindAdapterEx handler for each adapter that is marked as bound in the registry, but isn't currently bound in NDIS. (I.e., for each adapter that INetCfg finds a bindpath to that does not already have an open handle.)
However, due to the large impedance between NPF's API and how NDIS regards binding, you'll need to tackle a few issues:
Multiple simultaneous bindings to the same adapter. (This is a rarely-used feature; NPF is one of two protocols that I know use this, so it's not really discussed much in the MSDN documentation.) The only way to get multiple simultaneous bindings in NDIS 6.x is to call NdisOpenAdapterEx twice within the same ProtocolBindAdapterEx call. That's going to be challenging, because NPF's model is to open a new binding whenever an API call comes in from usermode; it doesn't know in advance how many handles will need to be opened.
If another bind request comes in, you can attempt to close all previous handles to that adapter (transparently to the NPF API[!]), call NdisReEnumerateProtocolBindings, then open N+1 handles in your upcoming ProtocolBindAdpaterEx handler. But this is brittle.
You can also try and merge all API calls to the same adapter. If a second bind request comes in, just route it to the pre-existing binding to that adapter. This might be difficult, depending on how NPF's internals work. (I'm not allowed to read NPF source code; I can't say.)
Finally, the cheesy solution is to just allocate two (or three) binding handles always, and keep the extras cached in case Wireshark needs them. This is cheap to implement, but still a bit fragile, since you can't really know if Wireshark will want more handles than you pre-allocated.
Missing INetCfg bindings. NDIS 5.x protocols are allowed to bind to an adapter even if the protocol isn't actually supposed to be bound (according to INetCfg). Wireshark uses this to get itself bound to all sorts of random adapters, without worrying too much about whether INetCfg agrees that NPF should be bound. Once you convert to NDIS 6.x, the rules are enforced strictly, and you'll need to make sure that your protocol's INF has a LowerRange keyword for each type of adapter you want to bind over. (I.e., the NPF protocol should show up in the Adapter Properties dialog box.)
Asynchronous bindings. The NdisReEnumerateProtocolBindings model is that you call it, and NDIS will make an attempt to bind your protocol to all bindable adapters. If the adapter isn't bindable for some reason (perhaps it's in a low-power state, or it's being surprise-removed), then NDIS will simply not call your protocol back. It's going to be tough to know exactly when to give up and return failure to the usermode NPF API, since you don't get a callback saying "you won't bind to this adapter". You may be able to use NetEventBindsComplete, but frankly that's kind of a dodgy, ill-defined event and I'm not convinced it's bulletproof. I'd put in a timeout, then use the NetEvent as a hint to cut the timeout short.
Finally, I just wanted to note that, although you said that you wanted to minimize the amount of churn in WinPcap, you might want to consider repackaging its driver as an NDIS LWF. LWFs were designed for exactly this purpose, so they tend to fit better with NPF's needs. (In particular, LWFs can see native 802.11 traffic, can get more accurate data without going through the loopback hack, and are quite a bit simpler than protocols.)
-19496399 0 Mocha tests timeout if more than 4 tests are run at onceI've got a node.js + express web server that I'm testing with Mocha. I start the web server within the test harness, and also connect to a mongodb to look for output:
describe("Api", function() { before(function(done) { // start server using function exported from another js file // connect to mongo db }); after(function(done) { // shut down server // close mongo connection }); beforeEach(function(done) { // empty mongo collection }); describe("Events", function() { it("Test1", ...); it("Test2", ...); it("Test3", ...); it("Test4", ...); it("Test5", ...); }); }); If Mocha runs more than 4 tests at a time, it times out:
4 passing (2s) 1 failing 1) Api Test5: Error: timeout of 2000ms exceeded at null.<anonymous> (C:\Users\<username>\AppData\Roaming\npm\node_modules\moch\lib\runnable.js:165:14) at Timer.listOnTimeout [as ontimeout] (timers.js:110:15) If I skip any one of the 5 tests, it passes successfully. The same problem occurs if I reorder the tests (it's always the last one that times out). Splitting the tests into groups also doesn't change things.
From poking at it, the request for the final test is being sent to the web server (using http module), but it's not being received by express. Some of the tests make one request, some more than one. It doesn't affect the outcome which ones I skip. I haven't been able to replicate this behaviour outside mocha.
What on earth is going on?
-20503856 0 SQL query: for each state with specific number of sailorsI'm starting to learn to write SQL queries. However, I'm still struggling with that. I had to write a query that gives back for each state that has more than 5 sailors the sailor id and the total number of reservations that he has made. The schemas are as following:
Slr (sid, sname, rating, state) and Reserves (sid, bid, day).
Here's my trial:
Select slr.state, slr.sid, count(*) From slr left join Reserves on slr.sid=reserves.sid Group By s.state Having count(*) >= 5 I know it's not correct, but what can I change ?
-16117467 0checkout ensureIndex This will speed up your search
-950003 0Change:
$('.removeitem').click(function(){ $(this).prev().parent().remove(); return false; }); to:
$('.removeitem').live("click", function(){ $(this).prev().parent().remove(); return false; });
-6627981 0 Redis is fast, but it can't be as fast as a direct memory access. It requires constructing a request, posting it, waiting for a response, decoding that response, and returning that value to your application. Redis runs as a separate process, so you will have to pay this price for inter-process communication even when it is located on the same machine.
That it is only twelve times slower by your benchmark is still impressive.
-2723779 0If you want the file and line numbers, you do not need to parse the StackTrace string. You can use System.Diagnostics.StackTrace to create a stack trace from an exception, with this you can enumerate the stack frames and get the filename, line number and column that the exception was raised. Here is a quick and dirty example of how to do this. No error checking included. For this to work a PDB needs to exist with the debug symbols, this is created by default with debug build.
using System; using System.Diagnostics; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { try { TestFunction(); } catch (Exception ex) { StackTrace st = new StackTrace(ex, true); StackFrame[] frames = st.GetFrames(); // Iterate over the frames extracting the information you need foreach (StackFrame frame in frames) { Console.WriteLine("{0}:{1}({2},{3})", frame.GetFileName(), frame.GetMethod().Name, frame.GetFileLineNumber(), frame.GetFileColumnNumber()); } } Console.ReadKey(); } static void TestFunction() { throw new InvalidOperationException(); } } } The output from the above code looks like this
D:\Source\NGTests\ConsoleApplication1\Program.cs:TestFunction(30,7) D:\Source\NGTests\ConsoleApplication1\Program.cs:Main(11,9)-21943894 0
We can specify output attribute of the java task which will redirect your error and output streams to the file specified as the value of this attribute. Or
You can explore the echo task in Ant through which you will be able to print the messages on the console
More information can be found on :
https://ant.apache.org/manual/Tasks/exec.html. or
http://www.vogella.com/tutorials/ApacheAnt/article.html
-4526260 0You just need to add a parameter to the function you have:
function getBlock($filename){ require_once(YOURBASEPATH . DS . 'layouts' .DS . 'blocks'. DS . $filename .'.php'); }
-34795650 0 Powershell Substring 'Quirk' Seeing 'Exception calling "Substring" with "2" argument(s): "Length cannot be less than zero.' being thrown when running this bit of code inside a script:
$PrinterDriverName = $printer.DriverName $PrinterMake = $PrinterDriverName.Substring(0,$PrinterDriverName.IndexOf(" ")) $PrinterModel = $PrinterDriverName.Substring($PrinterDriverName.IndexOf(" ")).Trim() Yet $PrinterMake and $PrinterModel are being populated. What I'm trying fathom out is when these two lines are ran selectively, no errors are returned. Can someone shed some light as to the substring errors are being produced when running this as part of the script please!? Thanks in advance ... Wayne
-19676950 0when you receive the post you should use
rowid[] instead of rowid
-37297733 0For me the accepted answer throwed an exception so what I did was this.
ArrayAdapter adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, Collections.emptyList()); spinner.setAdapter(adapter);
-3894219 0 Solution:
SELECT tag, COUNT(*)AS tags_count FROM ( SELECT post_n, tag FROM tags ORDER BY post_n DESC LIMIT 20 ) AS temp GROUP BY tag HAVING tags_count>=2 ORDER BY post_n DESC LIMIT 5 Of course need to change limit in the first selection, otherwise there will be plenty to choose from.
P. S. Sorry that is poorly formulated question, my english very bad.
-36737499 0You may want to draw a white rectangle the size of the entire canvas, beneath the actual content of the canvas.
// get the canvas 2d context var ctx = canvas.getContext('2d'); // set the ctx to draw beneath your current content ctx.globalCompositeOperation = 'destination-over'; // set the fill color to white ctx.fillStyle = 'white'; // apply fill starting from point (0,0) to point (canvas.width,canvas.height) // these two points are the top left and the bottom right of the canvas ctx.fillRect(0, 0, canvas.width, canvas.height); You have to apply these lines before generating your toDataUrl() stream.
Idea taken from: http://www.mikechambers.com/blog/2011/01/31/setting-the-background-color-when-generating-images-from-canvas-todataurl/
-6426802 0You want a modal view. All UIViewControllers are able to present a modal view by using the following method:
[self presentModalViewController:yourViewController animated:YES]; Check the Apple reference guides for more information and samples.
-30853179 0Script program:
#!/bin/bash for file in "$@";do echo "$file" done Run program:
path/to/program filename1.* path/to/program filename1.* filename2.* path/to/program filename1.ext1 filename1.ext2 etc...
-33179790 0 I use to think about a reference as an alias for another object. If you apply this to people, the alias is a nickname.
For example, if you have:
Person Robert; Person& Bob = Robert; you only have one person, but you sometimes call him Robert and sometimes call him Bob. But he is still the same person.
Trying to involve Bob's address into this just makes it harder. I find it easier to just consider references at the abstract level - two names for the same thing.
-13727723 0val and text are functions, you must add () to call them and get their results. If you juste write val or text, it's the reference to the function itself (and in js, a function is an object).
myfield.val( mytext.text() ); this will set the value of input field 'myfield' with the text inside the element 'mytext'
Try to do the same in your code
$("#TheForm #LessonNumber1 #LineNumber1 #Speaker").val( $('your_selector').text() );
-2305756 0 Are we facing a situation of Dangling Pointer here? Why and how? Please explain.
It depends on the implementation of Student. If Student looks like this ...
class Student { public: char* m_name; Student(const char* name) { m_name = new char[strlen(name)+1]; strcpy(m_name,name); } ~Student() { delete[] m_name; } }; ... then there's a problem: when you copy a Student then you have two pointers to the same m_name data, and when the two Student instances are deleted then the m_name data is deleted twice, which is illegal. To avoid that problem, Student need an explicit copy constructor, so that a copied Student has a pointer to different m_name data.
Alternatively if Student looks like this ...
class Student { public: std::string m_name; Student(const char* name) : m_name(name) { } }; ... then there's no problem because the magic (i.e. an explicit copy constructor) is implemented inside the std::string class.
In summary, you need an explicit copy constructor (or explicitly no copy constructor, but in either case not just the default constructor) if the class contains a pointer which it allocates and deletes.
-3428771 03: Lastly he asked if it is possible to used Singleton Object with Clusters with explanation and is there any way to have Spring not implement Singleton Design Pattern when we make a call to Bean Factory to get the objects ?
The first part of this question is hard to answer without a technological context. If the cluster platform includes the ability to make calls on remote objects as if they were local objects (e.g. as is possible with EJBs using RMI or IIOP under the hood) then yes it can be done. For example, the JVM resident singleton objects could be proxies for a cluster-wide singleton object, that was initially located / wired via JNDI or something. But cluster-wide singletons are a potential bottleneck because each call on one of the singleton proxies results in an (expensive) RPC to a single remote object.
The second part of the question is that Spring Bean Factories can be configured with different scopes. The default is for singletons (scoped at the webapp level), but they can also be session or request scoped, or an application can define its own scoping mechanism.
-34606142 0 use panGestureRecognizer or touch events to drag and move an item iosI am moving items in the view by touching them to the place where i leave it i am using touch events touchesBegin , touchesMoved , touchesEnd
and in touchesMoved i move the item.frame to the new location and it works with me but then i found a code that use panGestureRecognizer
and then i cant determine what to use
the code to handle pan was
- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer { if (recognizer.state == UIGestureRecognizerStateBegan || recognizer.state == UIGestureRecognizerStateChanged) { CGPoint translation = [recognizer translationInView:self.superview]; CGPoint translatedCenter = CGPointMake(self.center.x + translation.x, self.center.y + translation.y); [self setCenter:translatedCenter]; [recognizer setTranslation:CGPointZero inView:self]; } given that i need the exact coordinates of the point i am touching
-2691167 0A C# null is not the same as a database NULL.
In your insertion code you probably need to pick up that the value is "N/A"/null and then insert a DBNull instead. What does your DB insertion code look like?
-11442677 0The documentation has a pretty decent guide on how to best access the filesystem.
-21733954 0$("#goup").click(function(e) { $("#imgslide > img:first") .slideUp(500,function(e){ $(this).appendTo("#imgslide"); }); $("#imgslide > img:eq(3)").slideToggle({direction:"up"},500); // move the paragraph with the image index sync $("#product_description > div:first") .appendTo("#product_description"); return false; });
-13545991 0 widget_text widget doesn't work with shortcodes Hi all I am having a big issue with the shortcodes not working in text_widget. I have added the appropriate codes
add_filter( 'widget_text', 'shortcode_unautop'); add_filter( 'widget_text', 'do_shortcode'); I am still unsuccessful, is there any troubleshoot techniques I can used or be advised to solve this issue myself?
Also the shortcodes work perfectly in the_content and the_excerpt.
add_filter('the_content', 'do_shortcode'); add_filter('the_excerpt', 'do_shortcode');
-19285906 0 Data binding example extjs sencha I've a grid example that i want to make it look like this url below
http://docs.sencha.com/extjs/4.2.2/#!/example/grid/binding.html
The grid code is :
var grid_modal = Ext.create('Ext.grid.Panel', { width: '100%', height: 450, frame: true, loadMask: true, collapsible: false, title: 'Detail data', store: list_data, columns: [ { header: 'Number', width: 130, sortable: true, dataIndex: 'doc_no', xtype: 'templatecolumn', tpl: '{doc_no}<br/>{pp_id}' }, { header: 'Date.', width: 100, sortable: true, dataIndex: 'pp_date', xtype: 'datecolumn', format:'d-m-Y' }, { header: 'Vendor', width: 160, sortable: true, dataIndex: 'org_order', xtype: 'templatecolumn', tpl: '{org_order}' }], dockedItems: [{ xtype: 'pagingtoolbar', store: list_data, dock: 'bottom', displayInfo: true },{ xtype: 'toolbar', dock: 'top', items: [ { xtype: 'button', cls: 'contactBtn', scale: 'small', text: 'Add', handler: function(){ window.location = './pp/detail/' } },'->','Periode :', set_startdate('sdatepp',start), 's.d', set_enddate('edatepp',end), '-', { xtype : 'textfield', name : 'find_pp', id : 'find_pp', emptyText: 'Keywords' , listeners: { specialkey: function(field, e){ if (e.getKey() == e.ENTER) { onFindPP('find_pp','sdatepp','edatepp') } } } }] }], }); I don't understand how to add data binding to below grid that i make. so it makes look like same as the example on extjs doc. please help me find out how to make the data grid binding. thank you for your attention and help.
-15035182 0It's a Webkit-specific property:
CSS property:
-webkit-user-dragDescription
Specifies that an entire element should be draggable instead of its contents.
Syntax
-webkit-user-drag: auto | element | none;Values
autoThe default dragging behavior is used.
elementThe entire element is draggable instead of its contents.
noneThe element cannot be dragged at all.
It's supported by Chrome 1-17 and Safari 3-5.1: http://www.browsersupport.net/CSS/-webkit-user-drag
-30211717 0I do it this way :
// create your requests $requests[] = $client->createRequest('GET', '/endpoint', ['config' => ['order_id' => 123]]); ... // in your success callback get $id = $event->getRequest()->getConfig()['order_id']
-23738001 0 Find duplicates in excel workbook I have a excel workbook that i want to find all duplicate rows across all the sheets and highlight them. Figured out how todo it in one sheet. Anyone that can help me out?
-37363237 0You should have playing = false;
somewhere in game over method or somewhere else. As I see you haven't such line of code. I ask a question. Where did you change playing to false so that You expect to get
If(!playing) Condition instead of
If(playing) You press the key. Game begins. Now you reach
If(playing) Then the ball get to boundaries and the code reach
if ( ballX > width || ballX < 0 ) { gameover = true; } // if the ball reaches one of the bounderies it will be game over In this situation. Playing var and gameover var both are true. Right? And under
If(playing) You have score() method.so even when gameover is true the score method still is performed.
You can set playing to false under:
if ( ballX > width || ballX < 0 ) { gameover = true; Playing =false ; } Or you can modify the score method like this:
void score () { if (playing && !gameover) { fill(255); textSize(45); textAlign(CENTER); text(scorecounter, width/2,height/4); // keeps the score on the display while playing }
-11202676 0 Unable to get desired output in mysql I am working on a project report which requires some tricky output from a single table.
This is the structure of the table named: daily_visit_expenses 
having data like this:: 
now what i want the output is the combination of these three queries in a single column (any name), the queries are:
SELECT DISTINCT(`cust_1`) FROM `daily_visit_expenses` WHERE user='sanjay' AND `purpose_1`='Sales' SELECT DISTINCT(`cust_2`) FROM `daily_visit_expenses` WHERE user='sanjay' AND `purpose_2`='Sales' SELECT DISTINCT(`cust_3`) FROM `daily_visit_expenses` WHERE user='sanjay' AND `purpose_3`='Sales' I want to get the output from a single query which is the combination of above three queries in a single column like customers which is DISTINCT.
SQL Export:
CREATE TABLE IF NOT EXISTS `daily_visit_expenses` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `user` varchar(255) NOT NULL, `date` date NOT NULL, `status` varchar(50) NOT NULL, `location` varchar(50) NOT NULL, `cust_1` varchar(255) NOT NULL, `cust_2` varchar(255) NOT NULL, `cust_3` text NOT NULL, `cust_4` text NOT NULL, `purpose_1` varchar(20) NOT NULL, `purpose_2` varchar(20) NOT NULL, `purpose_3` varchar(20) NOT NULL, `purpose_4` varchar(20) NOT NULL, `visit_type` varchar(20) NOT NULL, `expenses` bigint(20) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ; INSERT INTO `daily_visit_expenses` (`id`, `user`, `date`, `status`, `location`, `cust_1`, `cust_2`, `cust_3`, `cust_4`, `purpose_1`, `purpose_2`, `purpose_3`, `purpose_4`, `visit_type`, `expenses`) VALUES (5, 'sanjay', '2012-06-15', 'Working', 'Customer', 'S.G.R.S. Chemical & Minral Industries', '', 'fatehpur foundry', '', 'Sales', '', 'Sales', '', 'Outstation', 2323), (8, 'sanjay', '2012-06-25', 'Working', 'Office', '', '', '', '', '', '', '', '', '', 0), (9, 'sanjay', '2012-06-09', 'Working', 'Office', '', '', '', '', '', '', '', '', '', 0), (10, 'sanjay', '2012-06-05', 'Working', 'Customer', 'V.N INTERNATIONAL', 'G.SURGIWEAR', '', '', 'Sales', 'Sales', '', '', 'Outstation', 332), (11, 'sanjay', '2012-06-30', 'Working', 'Customer', 'Ganesh Plywood-Sitapur', '', '', '', 'Service', '', '', '', 'Outstation', 434), (12, 'sanjay', '2012-06-04', 'Absent', '', '', '', '', '', '', '', '', '', '', 0), (13, 'sanjay', '2012-06-06', 'Absent', '', '', '', '', '', '', '', '', '', '', 0), (14, 'sanjay', '2012-06-08', 'Leave', '', '', '', '', '', '', '', '', '', '', 0);
-1173447 0 You will need to use the RegEx.Matches function and iterate through the collection.
-28370580 0well, i found an answer from internet,
<script type="text/javascript"> $(document).ready(function () { $("#<%=InsertBtn.ClientID %>").click(function (e) { var respond = confirm("Press ok if you confirm"); if (respond != true) { e.preventDefault(); } }); }); </script> <asp:Button ID="InsertBtn" runat="server" Text="Insert" OnClick="InsertBtn_Click" /> by using the preventDefault() to cancel the onclick default action
-38177638 0 How to add item to array?The item :
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $loop->post->ID ), 'single-post-thumbnail' ); The array :
$attachment_ids = $product->get_gallery_attachment_ids(); foreach( $attachment_ids as $attachment_id ) { echo '<img src="'.$image_link = wp_get_attachment_url( $attachment_id ).'">'; } I need to add the item $img_url in the beginning of the array.
-2508563 0For anyone else who's doing the same thing here's the code that I got working. Thanks Jeffrey!
Image image = new Image(); BitmapSource tempSource = Window1.GetNextImage(i); CroppedBitmap cb = new CroppedBitmap(tempSource, new Int32Rect(0, 0, Math.Min((int)Window1.totalWinWidth, tempSource.PixelWidth), Math.Min((int)Window1.totalWinHeight, tempSource.PixelHeight))); image.Source = cb; canvas1.Children.Add(image);
-11414265 0 fwrite writes to a FILE*, i.e. a (potentially) buffered stdio stream. It's specified by the ISO C standard. Additionally, on POSIX systems, fwrite is thread-safe to a certain degree.
write is a lower-level API based on file descriptors, described in the POSIX standard. It doesn't know about buffering. If you want to use it on a FILE*, then fetch its file descriptor with fileno, but be sure to manually lock and flush the stream before attempting a write.
Use fwrite unless you know what you're doing.
I recommend just writing a stored procedure (or group of stored procedures) to encapsulate this logic, which would look something like this:
update Customer set isDeleted = 1 where CustomerId = @CustomerId /* Say the Address table has a foreign key to customer */ update Address set isDeleted = 1 where CustomerId = @CustomerId /* To delete related records that also have child data, write and call other procedures to handle the details */ exec DeleteProjectByCustomer(@CustomerId) /* ... etc ... */ Then call this procedure from customerRepository.Delete within a transaction.
In a class i can have as many constructors as I want with different argument types. I made all the constructors as private,it didn't give any error because my implicit default constructor was public But when i declared my implicit default constructor as private then its showing an error while extending the class. WHY?
public class Demo4 { private String name; private int age; private double sal; private Demo4(String name, int age) { this.name=name; this.age=age; } Demo4(String name) { this.name=name; } Demo4() { this("unknown", 20); this.sal=2000; } void show(){ System.out.println("name"+name); System.out.println("age: "+age); } } public class Demo4 { private String name; private int age; private double sal; private Demo4(String name, int age) { this.name=name; this.age=age; } Demo4(String name) { this.name=name; } private Demo4() { this("unknown", 20); this.sal=2000; } void show() { System.out.println("name"+name); System.out.println("age: "+age); } }
-25940124 0 Do powershell parameters need to be at the front of the script? I'm trying to have a script with both executable code and a function, like the following:
function CopyFiles { Param( ... ) ... } // Parameter for the script param ( ... ) // Executable code However, I run into the following error: "The assignment expression is not valid. The input to an assignment operator must be an object that is able to accept assignments, such as a variable or a property"
When I list my function at the end of the file, it says that the function name is undefined. How do I call a powershell function from executable code within the same script?
-22763016 0Download the SDK 7.0.0.27 and install it via UPDI then apply import. SDK fix pack download: http://www-01.ibm.com/support/docview.wss?uid=swg24033882
-13341979 0 Adding OverlayItems to MapView is reallyslow, how to make it faster?In my app there is a MapView, and I add OverlayItems to it, about 500, but it will be more even thousands in the future...
My problem is: When I switch to this Activity, I got a massive 3-4 sec blackout then it switches properly and I can navigate and tap on the map.
Some months ago when the app only contained 50-150 GeoPoints in the mapView there was no blackout. So i think something is wrong with my OverlayItem adding to the mapView, it really slows then the app.
I add my GeoPoints with a simple cycle on Activity startup.
What can i do to make this Activity faster and prevent the blackout?
EDIT:
Thanks to comments, i just realized i call populate() after every addOverlay(MyOverlayItem myoverlay) function call.
I edited the code, now after the cycle i call it only once by:
public void populateNow() { populate(); } But i just got a nice null pointer exception with this... Any ideas?
11-12 15:54:03.398: E/MapActivity(1534): Couldn't get connection factory client 11-12 15:54:03.531: E/AndroidRuntime(1534): FATAL EXCEPTION: main 11-12 15:54:03.531: E/AndroidRuntime(1534): java.lang.NullPointerException 11-12 15:54:03.531: E/AndroidRuntime(1534): at com.google.android.maps.ItemizedOverlay.getIndexToDraw(ItemizedOverlay.java:211) 11-12 15:54:03.531: E/AndroidRuntime(1534): at com.google.android.maps.ItemizedOverlay.draw(ItemizedOverlay.java:240) 11-12 15:54:03.531: E/AndroidRuntime(1534): at com.google.android.maps.Overlay.draw(Overlay.java:179) 11-12 15:54:03.531: E/AndroidRuntime(1534): at com.google.android.maps.OverlayBundle.draw(OverlayBundle.java:42) 11-12 15:54:03.531: E/AndroidRuntime(1534): at com.google.android.maps.MapView.onDraw(MapView.java:530) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.view.View.draw(View.java:6933) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.view.ViewGroup.drawChild(ViewGroup.java:1646) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.view.ViewGroup.drawChild(ViewGroup.java:1644) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.view.View.draw(View.java:6936) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.widget.FrameLayout.draw(FrameLayout.java:357) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.view.ViewGroup.drawChild(ViewGroup.java:1646) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.view.View.draw(View.java:6936) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.widget.FrameLayout.draw(FrameLayout.java:357) 11-12 15:54:03.531: E/AndroidRuntime(1534): at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:1904) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.view.ViewRoot.draw(ViewRoot.java:1527) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.view.ViewRoot.performTraversals(ViewRoot.java:1263) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.view.ViewRoot.handleMessage(ViewRoot.java:1865) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.os.Handler.dispatchMessage(Handler.java:99) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.os.Looper.loop(Looper.java:123) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.app.ActivityThread.main(ActivityThread.java:3687) 11-12 15:54:03.531: E/AndroidRuntime(1534): at java.lang.reflect.Method.invokeNative(Native Method) 11-12 15:54:03.531: E/AndroidRuntime(1534): at java.lang.reflect.Method.invoke(Method.java:507) 11-12 15:54:03.531: E/AndroidRuntime(1534): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842) 11-12 15:54:03.531: E/AndroidRuntime(1534): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600) 11-12 15:54:03.531: E/AndroidRuntime(1534): at dalvik.system.NativeStart.main(Native Method)
-16649558 0 TRAC. Return a javascript variable back to javascript Is there any way to pass a javascript varialbe during process_request in trac 0.11? The code goes like this:
def process_request(self, req): component = req.args.get('component_name') milestones = [] db = self.env.get_db_cnx() cursor = db.cursor() milestones_sql = "SELECT name FROM milestone WHERE component = '" + component+ "'" cursor.execute(milestones_sql) milestones = cursor.fetchall() milestones = itertools.chain(*milestones) db.commit() return 'filter.js', {'milestones':json.dumps(list(milestones))}, 'text/plain' I get arguments, do a SQL query, and want to return result to a script. Not as a string though.
-20632498 0 Provisioning profile issue in IOSMy Provisioning profile is going to expire in two days,so build in the device will not work after that. is there any method to update the old profile and to make work build as usual.
thanks in advance
-1915340 0Ok, I found how to make it. With a UILocalizedIndexedCollation, there is a sample in tableViewSuite.
I followed the source code, then it works perfectly.
-23325687 0The issue had to do with Uniform Server's (WAMP) setup php.ini file
Uniform Server has a SEPARATE file for command line php commands.
The name is php-cli.ini
I added there the following two lines and everything was ok:
extension=php_pdo_mysql.dll extension=php_mbstring.dll
-35350853 0 Angular2 - Different views with different template With $stateProvider and abstract property in Angular 1, I could create different views with different template easily. For example in my application I have Login and Register pages which are using unauthTemplate. I have also Dashboard and Product pages that are using commonTemplate. In Angular 1, here is my states
$stateProvider .state('unauthTemplate', { abstract: true, url: '', controller: 'unauthTemplateController', templateUrl: '/app/common/unauthTemplate.html' }) .state('commonTemplate', { abstract: true, url: '', controller: 'commonTemplateController', templateUrl: '/app/common/commonTemplate.html' }) .state("unauthTemplate.login", { url: "/Login", controller: 'LoginController', templateUrl: '/app/views/login.html' }) .state("unauthTemplate.register", { url: "/Register", controller: 'RegisterController', templateUrl: '/app/views/register.html' }) .state("commonTemplate.dashboard", { url: "/dashboard", controller: 'DashboardController', templateUrl: '/app/views/dashboard.html' }) .state("commonTemplate.product", { url: "/product", controller: 'ProductController', templateUrl: '/app/views/product.html' }) Since there is not "Abstract property" in RouteConfig in Angular2, I could not setup my app's route with the same approach in Angular 1. Can someone help me how can I have different view with different template.
Thanks
-27133796 0 How to count all alphabetical characters in array?So basically my objective is to make a program that takes the user input and reverses it and prints the inverse character back to user as an encoded message. Right now i need to print the statistics of the user entered string. How do i count the amount of occurrences of different letters from the user string. I have this so far.
import java.util.*; public class SecretCodeMachine { public static void main(String[]args) { //object accessing the non static methods SecretCodeMachine a = new SecretCodeMachine(); //input stream Scanner in = new Scanner (System.in); Scanner i = new Scanner (System.in); //prompt the user System.out.println("Please input your secret message."); String input = in.nextLine(); //calls the encodedMessage() method; equals the return value to varaible String encodedMessage = a.encodeMessage(input); //message and prompt System.out.println("Encoded message: " + encodedMessage); System.out.println("Enter the code in here to get the original message back."); String input2 = i.nextLine(); //if statements saying that if the input equals the encoed message... if (input2.equals(encodedMessage)) { //print this System.out.println("Original Message: " + input); } else { //prints when doesnt equal System.out.println("Message not found."); } //closes the input stream i.close(); in.close(); } //method for encoding the string from array public String encodeMessage(String pass) { //passes the parameter string and puts it in an array () char[] toArray = pass.toCharArray(); for (int i = 0; i < toArray.length; i++) { //does the lower case characters if (toArray[i] >= 'a' && toArray[i] <= 'z') { if (toArray[i] - 'a' <= 13) toArray[i] = (char) ('z' - (toArray[i] - 'a')); else toArray[i] = (char) ('a' + ('z' - toArray[i])); } //does the upper case characters else if(toArray[i] >= 'A' && toArray[i] <= 'Z') { if (toArray[i] - 'A' <= 13) toArray[i] = (char) ('Z' - (toArray[i] - 'A')); else toArray[i] = (char) ('A' + ('Z' - toArray[i])); } //if the characters are non alphatbetic else { toArray[i] = toArray[i]; } } //converts the toArray back to new string String encodedMessage = new String(toArray); //returns the encodedMessage string return encodedMessage; } }
So how would i keep a track off all the letters that are entered by the user?
-9321485 0You might not have write permissions to install a node module in the global location such as /usr/local/lib/node_modules, in which case run npm install -g package as root.
Given a template metaprogram (TMP), do C++ compilers produce build statistics that count the number of instantiated classes? Or is there any other way to automatically get this number? So for e.g. the obiquitous factorial
#include <iostream> template<int N> struct fact { enum { value = N * fact<N-1>::value }; }; template<> struct fact<1> { enum { value = 1 }; }; int main() { const int x = fact<3>::value; std::cout << x << "\n"; return 0; } I would like to get back the number 3 (since fact<3>, fact<2>, and fact<1> are instantiated). This example if of course trivial, but whenever you start using e.g. Boost.MPL, compile times really explode, and I'd like to know how much of that is due to hidden class instantiations. My question is primarily for Visual C++, but answers for gcc would also be appreciated.
EDIT: my current very brittle approach for Visual C++ is adding the compile switch from one of Stephan T. Lavavej's videos /d1reportAllClassLayout and doing a grep + word count on the output file, but it (a) increases compile times enormously and (b) the regex is hard to get 100% correct.
-11273400 0Sometimes, It happens, when your byte[] not decode properly after retrieving from database as blob type.
So, You can do like this way, Encode - Decode,
Encode the image before writing to the database:
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); mBitmap.compress(Bitmap.CompressFormat.JPEG, THUMB_QUALITY, outputStream); mByteArray = outputStream.toByteArray(); // write this to database as blob And then decode it like the from Cursor:
ByteArrayInputStream inputStream = new ByteArrayInputStream(cursor.getBlob(columnIndex)); Bitmap mBitmap = BitmapFactory.decodeStream(inputStream); Also, If this not work in your case, then I suggest you to go on feasible way..
We are using GCM for messaging from server to the client app. It is a standard implementation where installation of the client app talks to the gcm server to get the reg id, sends it to our server and our server uses that reg id to push messages to the app. Our requirement is that these push notifications should be instantaneous and as real time as possible.
But the connection between GCM and the client app seems to disappear after a few minutes of inactivity. We have tried several things on our end: 1. Using an alarm manager to keep running a heartbeat intent that sends heartbeats to gcm. This does not work on custom android OSes where cleaning memory forces close of all app alarms. 2. Sending an upstream message from client to gcm in the hope that it establishes connection. 3. Using high priority messages from server to gcm hoping that would force a connection between gcm and app.
None of it has worked so far. Any idea if there's an API in the play services framework on the client side to force establish a connection to gcm if the app determines there is no current connection based on not getting an ACK for an upstream message?
Some research we did: 1. https://productforums.google.com/forum/#!msg/nexus/fslYqYrULto/lU2D3Qe1mugJ
-12273286 0Maybe you need to use exp_continue like-
use Expect; ... ... foreach my $cmd (@cmd_array){ $exp->expect(3, [ qr/($|#)/ => sub { shift->send("$cmd\n"); exp_continue;}] ); } Also, i think the statements inside sub{...} runs only if pattern matches as per qr/($|#)/. Also, I would think that after you type in an input or command you would generally press the return key to execute the command hence the $cmd\n.
If you are just scaffolding, you are answer should be more simple:
<%= form_for @article do |f| %> Your form should work now...
-38988442 0I made SVG log out icon from exit-to-app icon.
Preview:
Also there are several variants on materialdesignicons.com:
-15511073 0You would do something like this:
radio_button = form.Form( form.Radio('details', ['option1', 'option2', 'option3', 'option4']), ) Also, you can just have webpy render an html page and put the radio button html tag into that page. I would suggest that you don't try to learn how to use webpy's templating system if you are new to programming. It is too abstract for a beginner. Instead use webpy to serve your pages and write your pages in a regular manner. Then when you feel comfortable you should consider a nice standalone template engine like Jinja2.
This has also been answered here:
How to use radio buttons in python web.py
-20684820 0Is onClick() supposed to be an event handler for a button click? If so, the signature is wrong.
I believe you are looking for something like this. I have changed it from an ArrayList to a generic List. And initialized it with a collection initializer, and made it accessible from within your function. Please run the code below and let us know if you get exceptions.
List<string> MyList=new List<string>() {"Android", "Blackberry", "Hardcore"}; public void onClick(View view) { MyList.Add("testing"); adapter.notifyDataSetChanged(); }
-5504619 0 ajaxComplete not working on $(window) I'm using jQuery version 1.5.1 and this isn't working for me:
$(window).ajaxComplete(function() { console.log('hello'); }); but this is:
$(document).ajaxComplete(function() { console.log('hello'); }); Why can't I attach the event handler to $(window)?
Note: this code is working with jQuery v1.3.2 but not with v1.5.1
-38680776 0 Remove Repeated Words from Text fileI have a text file, contaning nearly 45,000 words, one word in each line. Thousands of these words appear more than 10 times. I want to create a new file in which there is no repeated word. I used Stream reader but it reads the file only once. How can I get rid of the repeated words. Please help me. Thanks My code was like this
Try File.OpenText(TextBox1.Text) Catch ex As Exception MsgBox(ex.Message) Exit Sub End Try Dim line As String = String.Empty Dim OldLine As String = String.Empty Dim sr = File.OpenText(TextBox1.Text) line = sr.ReadLine OldLine = line Do While sr.Peek <> -1 Application.DoEvents() line = sr.ReadLine If OldLine <> line Then My.Computer.FileSystem.WriteAllText(My.Computer.FileSystem.SpecialDirectories.Desktop & "\Splitted File without Repeats.txt", line & vbCrLf, True) End If OldLine = line Loop sr.Close() System.Diagnostics.Process.Start(My.Computer.FileSystem.SpecialDirectories.Desktop & "\Splitted File without Repeats.txt") MsgBox("Loop terminated. Stream Reader Closed." & vbCrLf)
-27958615 0 Regular expression to match a string starting with some characters and following with some symblos I would like to match a string which starts with character sequence 49. The string i get to evaluate will be like 49/1.0 or 49/2.0 etc. If I use ^49 it is not matching with the string i receive (ie: 49/1.0). My expression matches with the string if I receive 49XX only. I do not sure what are the symbols will follow the 49 character.
How can i define regular expression for this?
-40977687 0 Tools to capture infromation from multiple snmp agentsI am searching a tool to capture information from multiple snmp agents .I went through net-snmp apis for the same but I need a scalable solution .Please lemme know if any tool already exists, If not,Is it good practice to write your own snmp manager from scratch ?
-17910079 0 How to store Unique data and increment the Ratio using a JavaScript ArrayI want to store a random generated data that looks like 1-2-3-4-5-6 using a javascript array.
Each data may contain only the - character and 6 unique numbers from 1 to 49.
I declared the array as: var a = new Array();
Each time a new data is being generated, I store it like: a[data] = 1; where data might be 2-36-33-21-9-41 and 1 represents the ratio;
If the data generated already exists, I must increment the ratio, like: a[data]++;
Why is the length property not available?
I need to refresh the length value on the page each time a new unique data has been generated, maybe at each 1 millisecond.
I can't parse a 1 million array that fast ... each time ...
this is how i insert or update:
if (variante_unice[s]) { variante_unice[s]++; } else { variante_unice[s] = 1; variante_unice_total++; } the code:
window.setInterval( function() { variante++; $("#variante").text(variante); for (j = 1; j <= 49; j++) { $("#v" + j).attr("class", ""); } for (j = 1; j <= 49; j++) { extracted[j] = 0; } ind = 0; s = ''; while (ind < 6) { r = Math.floor((Math.random() * 49) + 1); if (extracted[r] == 0) { //this is where i generate the data if (s === '') { s = r; } else { s += '-' + r; } //console.log(r); extracted[r] = 1; frecvency[r]++; $("#n" + r).attr("class", "green"); $("#v" + r).attr("class", "green"); ind++; //console.log('i'+frecventa[r]); frecventa[r]++; //console.log('d'+frecventa[r]); $("#f" + r).text(frecventa[r]); } } //is the generated data new? if not, increment ratio if (variante_unice[s]) { variante_unice[s]++; } else { variante_unice[s] = 1; variante_unice_total++; } //console.log(variante_unice); //console.log(variante_unice[s]); //console.log(variante_unice.length); //console.log(s); verifica_varianta(); //console.log(extracted); //console.log(frecvency); } , 1);
-34511225 0 Finally I got the very reason of this behavior.
The reason is the overlapping elements.
For those who may stumble on this problem, try my approach on finding the overlapping elements.
Add this to your css file:
body * { border: 1px solid; background: #000000; } Adding that css styles will enable you to see the elements that causes RL to LR swipe because of extra width.
Happy coding!
-40300872 0 S3 static host redirect and strip slugIs it possible to create a static website redirect rule that redirects www.domain1.com/* --> www.domain2.com without maintaining the slug ?
Something like this if wildcard was allowed:
<RoutingRules> <RoutingRule> <Condition> <KeyPrefixEquals>*</KeyPrefixEquals> </Condition> <Redirect> <HostName>www.domain2.com</HostName> <ReplaceKeyPrefixWith>/</ReplaceKeyPrefixWith> </Redirect> </RoutingRule> </RoutingRules>
-30410410 0 Youtube API V3 Java Any possible without invoking browser to upload video Hi I hope someone can help me out here.
I have a Java Application on my local machine,I am trying to upload video to YouTube.
Upload a video to the authenticated user's channel. Use OAuth 2.0 to authorize the request.
It was working good.
The source code getting from Youtube API V3. The class name is com.google.api.services.samples.youtube.cmdline.data.UploadVideo
While I run the application everyday asking very first time invoking default browser once i click approve after that video upload to youtube. Second time not invoking default browser. It was working good.
But I want without invoking browser, Need to upload video to youtube.
Any Idea ? Please share me.
-22087268 0With Visual C++,
newcalls themallocfunction.
This is partially true: the new expressions in your code do call operator new to allocate memory and operator new does indeed call malloc. But the pointer to the initial element that is yielded by the new expression is not necessarily the pointer obtained from malloc.
If you dynamically allocate an array of objects that require destruction (like your CTheClassWith_string type), the compiler needs to keep track of how many elements are in the array so that it can destroy them all when you delete the array.
To keep track of this, the compiler requests a slightly larger block from malloc then stores some bookkeeping information at the beginning of the block. The new expression then yields a pointer to the initial element of the array, which is offset from the beginning of the block allocated by malloc by the bookkeeping information.
I have setup my private registry and also pushed some images in it. It is also secured with certificates and I used kwk docker registry frontend to setup a nice UI for my docker registry but I am facing an issue in kwk frontend that sometimes when I click on "Browse Repositories" on the main page it goes to "localhost/repositories/20"; (searches for 20; which shows nothing obviously). What could be the possible issue. I can't see any image in this frontend.
-19578447 0Update
Use the split method of the String class to split the input string on the space character delimiter so you end up with a String array of words.
Then loop through that array using a modified for loop to print each item of the array.
import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter the sentence"); String sentence = in.nextLine(); showWords(sentence); } public static void showWords(String sentence) { String[] words = sentence.split(' '); for(String word : words) { System.out.println(word); } } }
-28482087 0 Use Regex to Match relative image URLs and then use string replace to make them absolute using Javascript I want to use javascript regex to find all relative URLs and then make them absolute using the string replace function in javascript. I tried to following but it didn't work:(Note: i have tried searching this site but couldn't find the perfect solution)
data = data.replace(/\/\.(jpg|png|gif|bmp)$\/i/gi, "http://example.com" + "$1"); What I am trying to achieve is replace the relative image URLs with their absolute forms in an external data pulled using YQL and JSON. I also found another script that would do the job, but it would only apply to the on page HTML element, and NOT to the content inside the div containing the externally loaded content.
Any method other than the data.replace doesn't seem to work in my case, i tried another script that worked perfectly but only on the on page html, not externally loaded HTML.
This is my first post here. Any help would be appreciated.
-15256840 0 Using Visual Studio 2010 Without Using SolutionsI find myself working for a group with a very large c++ code base that does not use Visual Studio accept as a compiler. We are using make files. I feel totally crippled without the visual studio advanced features such as intellisense, go to definition, and refactoring. Are there any good tricks out there to get Visual Studio 2010 to have these features without the projects and solutions? Or, baring that are there any good VI oriented alternatives?
Thanks
-3040041 0It might be showing in the "Immediate Window" instead due to a setting:
Or somethig like that.
-3259002 0 Need a Perforce DVCS recommendation: git-p4, hg Perfarce, or Something Else?We're getting migrated from Subversion to Perforce at work. I've been using git-svn and it's kept me very productive. I want to keep using a DVCS for my own development.
Which works best with Perforce in your experience, git-p4, Perfarce (hg) or something else I've never heard of?
What works well (and what doesn't)?
-19774733 0 Bundling and not bundling in production and test environments in ASP.NET MVCI am using the ASP.NET Bundling mechanism:
BundleTable.Bundles.Add(new ScriptBundle("~/Scripts/Master-js").Include( "~/Scripts/respond.min.js", "~/Scripts/jquery.form.js", "~/Scripts/jquery.MetaData.js", "~/Scripts/jquery.validate.js", "~/Scripts/bootstrap.js", "~/Scripts/jquery.viewport.js", "~/Scripts/jquery.cookie.js" )); I want this to happen if the build is in release. If the build is in debug, I want the un-minified individual files to load so debugging would be easy.
The only way I have been able to do this is to write the following in my view:
<% if(HttpContext.Current.IsDebuggingEnabled) { Response.Write("<script type='text/javascript' src='../../Scripts/respond.min.js'></script>"); Response.Write("<script type='text/javascript' src='../../Scripts/jquery.form.js'></script>"); Response.Write("<script type='text/javascript' src='../../Scripts/jquery.MetaData.js'></script>"); Response.Write("<script type='text/javascript' src='../../Scripts/jquery.validate.js'></script>"); Response.Write("<script type='text/javascript' src='../../Scripts/bootstrap.js'></script>"); Response.Write("<script type='text/javascript' src='../../Scripts/jquery.viewport.js'></script>"); Response.Write("<script type='text/javascript' src='../../Scripts/jquery.cookie.js'></script>"); } else { Scripts.Render("~/Scripts/Master-js"); } %> As you can see, I am repeating myself here. Is there a better way?
-36260142 0Q1.What should be the resolution of the image for supporting all screen sizes for iPhone and iPad in landscape or portrait?
Regarding to @heximal
You can set "Scale to fill" mode for your image view and provide any image size (size of you xib, for example).
Q2.Should I be again providing images of different resolutions for different screen sizes and orientations for iPhone and iPad like LaunchImage asset?
Create new image set in assets and provide just 3 images for your launch screen -@1x @2x @3x
I am using Listview to display products list from database. OnPage Load products gets load properly but when I try to switch page using datapager pagination it gives this error
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index at System.Collections.ArrayList.get_Item(Int32 index) at System.Web.UI.WebControls.DataKeyArray.get_Item(Int32 index) at shop.products_ItemDataBound(Object sender, ListViewItemEventArgs e)
Thing is if I use ItemDataBound then only I get this error. Else paginations works fine.
<asp:ListView ID="products" runat="server" DataKeyNames="ID" OnPagePropertiesChanging="OnPagePropertiesChanging"> <ItemTemplate> content </ItemTemplate> <LayoutTemplate> <div id="itemPlaceholderContainer" runat="server" style=""> <div runat="server" id="itemPlaceholder" /> </div> <div class="datapager"> <asp:DataPager ID="DataPager1" ClientIDMode="Static" runat="server" PageSize="12" PagedControlID="products" ViewStateMode="Enabled"> <Fields> <asp:NextPreviousPagerField ButtonType="Link" ShowFirstPageButton="false" ShowPreviousPageButton="False" ShowNextPageButton="false" ButtonCssClass="nextPre" /> <asp:NumericPagerField ButtonType="Link" ButtonCount="10" /> <asp:NextPreviousPagerField ButtonType="Link" ShowNextPageButton="true" ShowLastPageButton="false" ShowPreviousPageButton="false" ButtonCssClass="nextPre" /> </Fields> </asp:DataPager> <div class="clear"></div> </div> </LayoutTemplate> <EmptyDataTemplate> <strong>No Items Found....</strong> </EmptyDataTemplate> </asp:ListView> Item DataBound
private void products_ItemDataBound(object sender, ListViewItemEventArgs e) { try { if (e.Item.ItemType == ListViewItemType.DataItem) { ListViewDataItem itm = (ListViewDataItem)e.Item; string productID = products.DataKeys(itm.DataItemIndex)("ID"); query = "SELECT stock_status FROM products WHERE ID = '" + productID + "'"; DataTable dt = this.GetData(query); if (dt.Rows.Count > 0) { ((Label)e.Item.FindControl("checkReadyStock")).Text = dt.Rows(0)("stock_status").ToString; if (((Label)e.Item.FindControl("checkReadyStock")).Text == "Ready Stock") { ((Image)e.Item.FindControl("readyStock")).Visible = true; } } } } catch (Exception ex) { Response.Write(ex); } } DataPager
protected void OnPagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e) { (products.FindControl("DataPager1") as DataPager).SetPageProperties(e.StartRowIndex, e.MaximumRows, false); products.DataSource = ViewState("Data"); products.DataBind(); }
-1015743 0 I did use Win32::GUI once for such a simple project. The main window had a menu, a text-box and a few buttons and checkboxes. It worked.
Excerpt from the method that sets up the GUI (just to give you an idea):
my @menu_items = ( '&File' => 'File', ' > &Open' => { -name => 'FileOpen', -onClick => sub { $self->onFileOpen(@_) }, }, ' > &Close' => { -name => 'FileClose', -onClick => sub { $self->onFileClose(@_) }, }, ' > E&xit' => { -name => 'FileExit', -onClick => sub { $self->onFileExit(@_) }, }, '&Help' => 'Help', ' > &About' => { -name => 'About', -onClick => sub { $self->onHelpAbout(@_) }, }, ); $self->set_main_menu( Win32::GUI::MakeMenu(@menu_items) ); my $window = $self->set_main_window( Win32::GUI::Window->new( -menu => $self->get_main_menu, -name => 'Main', -sizable => 0, -resizable => 0, -hasmaximize => 0, -maximizebox => 0, -title => $self->get_program_name, -onTerminate => sub { -1 }, -onTimer => sub { $self->onTimer(@_) }, ), ); $self->set_log_field( $window->AddTextfield( -name => 'Log', -font => Win32::GUI::Font->new( -name => 'LogFont', -face => 'Courier New', -size => 9, ), -multiline => 1, -wantreturn => 1, -autovscroll => 1, -vscroll => 1, -readonly => 1, ), ); $self->get_log_field->MaxLength(40000); $self->set_status_bar( $window->AddStatusBar( -name => 'Status', -text => $self->get_program_name, ), );
-13742775 0 Save and load elements from webpage I have in my webpage a series of elements, for example videos or other media:
<div id = "text"> </div> <video height="240" width="412" id="video" controls="controls"> </video> I change with JavaScript the original status of these elements and I use Popcorn.js for create a synchronization events, for example:
var video = document.getElementById('video'); video.src = $("#url").val(); //Change src value var popcorn = Popcorn( "#video" ); popcorn.footnote({ //Create a synchronization event; I add a footnote start: 2, stop: 5, text: 'Hello World!!!', target: 'text', }); So now, my problem is that I want save these elements with their events. And after I want to have the possibility to load (in the my webpage) this elements for continue to change them again. How can I save/load in this case?
-33905632 0 background image too large and out of focusThis is my code
<style type="text/css"> body { background-size:cover; background-image:url('Orange.jpg'); background-repeat:no-repeat; background-attachment: fixed; background-size: 100% auto; } </style> The background image is way too large, zoomed in, and out of focus Please help
Thanks, Duncan
-2009441 0Assuming you are talking about the creation of dynamic objects:
You'll obviously need a library to support this, unless you want to get into Reflection.Emit yourself - LinFu supported this in version 1:
http://code.google.com/p/linfu/
However, it's a feature that was dropped before version 2 I seem to remember.
-27746239 0You need to actually perform the query against your DB:
$stuidcheck="SELECT status FROM valid_stuid WHERE id='".$stuid."'"; if($stuidcheck == "used") All this does is to give the string $stuidcheck the value "SELECT...", but you need to do something like:
$result=mysql_query($stuidcheck); $row=mysql_fetch_assoc($result); if ($row['status'] == "used") Or something like that (my PHP is a bit rusty, but you'll find thousands of code examples for this).
-18763433 0 I need a very basic understanding of what static meansI am a java newbie, and despite searching everywhere, I cannot find a basic definition for what static actually does. Could somebody please tell me what it means? Also, please phrase your answer as if I do not even know what java is, no programming language examples please? Huge thanks. EDIT: so my understanding is that when you have a static variable inside of a constructor,
i.e. you have class test{ static int a = 5; public test(){ } } and then
test test1 = new test(); test test2 = new test(): , test1.a would equal 5, and test2.a would also equal 5. If you changed test1.a = 6 however, test2.a would also equal 6?
Important point: always call function on super when you reimplement. This solved my problem:
- (void)layoutSubviews { [super layoutSubviews]; self.contentView.frame = CGRectMake(50, 0, self.frame.size.width - 100, sub.thumbnail.size.height + 20); }
-23277387 1 Redis publish from a csv. No error but No data received Below is my script which inserts data from a csv located on one server into Redis on another server. If it worked..
I don't get an error but I don't show any data received on the redis side either. So Iam not sure which is worse.
#!/opt/python/bin/python import csv import redis from redis import StrictRedis reader = csv.reader(open("/opt/xyzxyz.csv")) header = reader.next() client = redis.StrictRedis(host='XXXXXXXXX.XX.XXX.X.XXX', port=6379, db=0) for row in reader: key = "xyzxyz:%s" % (row[0], ) doc = dict(zip(header, row)) client.publish(key, doc) Any thoughts on what I am missing from the above process? Or if there is something I am not doing on the redis side?
This is my first time working with Redis so it is kinda new to me.
-1642548 0I'm not sure if I expressed my problem very well, but now I've found the solution.
In my .proj file, I reference my custom task with the following syntax...
<UsingTask AssemblyFile="..\lib\MyCompany.MSBuild\MyCompany.MSBuild.dll" TaskName="CreateDatabase" /> My CreateDatabase task relies on various 3rd-party assemblies. However, some of these are only referenced via reflection, so weren't included by default in the folder "..\lib\MyCompany.MSBuild".
I had been trying to get the task to work by placing the required assemblies in the same directory as the .proj file invoking the task.
However, what I should have been doing was putting the assemblies in the referenced task directory "..\lib\MyCompany.MSBuild\".
Simple!
-25893575 0Java has a pool of Integer constants between -128 and 128. Integer values in that range don't take up any additional space.
Integer values outside that range take as much space as an object header + 4 bytes. How big that is depends on your JVM and settings. Look at http://sourceforge.net/projects/sizeof or https://code.google.com/p/memory-measurer if you want to programmatically measure the size.
Edit: Note that Integer i = new Integer(10); will not use the object constant pool. That's why you should always use Integer.valueOf(x) instead of new Integer(x) when instantiating. Note also that autoboxing already does the right thing, so Integer i = 10 will also use the constant pool.
Use the following steps:
go to window--Preferences--Android
then give your android sdk path
in my case:
like:/home/ravindmaurya/AndroidTa/adt-bundle-linux-x86_64-20130729/sdk
then press apply
-9785092 0 Redirect to a particular tab<ul class="tabs" style="background: "> <li><a href="javascript:tabSwitch('tab_1', 'content_1');" id="tab_1" class="active">Payment Gateway Basics</a></li> <li><a href="javascript:tabSwitch('tab_4', 'content_4');" id="tab_4" >Contact Us</a></li> </ul> These are my tabs, once I submit a form in the "contact us" tab, it goes back to the first tab. Can anyone tell me how to stay in the same tab?
I'm using PHP server side switching, I'm using JavaScript.
(I used href not onclick in the listing. Stack Overflow doesn't allow to use more href so I changed it into onclick, before this post was edited).
jQuery.Deferred objects provide a very elegant way to do this (I know you're not using jQuery 1.5: I'm just giving you a reason to upgrade ;-):
Assuming we have two scripts co-operating like the following:
// defines utilities var util = util || { loaded: $.Deferred() }; (function(){ $.extend(util, { msg: "Hello!" }); util.loaded.resolve(); })(); ... and:
// uses them var util = util || { loaded: $.Deferred() }; util.loaded.then(function(){ alert(util.msg); }); ... the alert will always fire after the first script has had a chance to define it's utilities no matter the order they load in. This has advantages over the setTimeout and event based approaches in that it's easier to have multiple dependencies (using $.when), doesn't use polling, and you don't have to worry about handling the order-of-loading explicitly.
The only thing that's kind of gross is that all of the modules have to include:
var util = util || { loaded: $.Deferred() }; ... and $.extend() it to make sure that they use the same deferred.
The problem is the where clause - you are giving it an expression that will evaluate to a string expression, but the where clause is used to specify conditions that must be satisfied to return records.
You need to rewrite the where clause to specify records to be selected.
You haven't specified Joomla version so I'm assuming 1.6/7/2.5 in my answer.
Short Answer: If you're using Joomla!'s default .htaccess then all you have to do is create a Joomla! menu to each of your components views with the right alias eg. portal for your default component access ie. ?option=com_tmportal.
This is what the default .htaccess does it passes all of the elements after the base URL to index.php to help select the component and view.
Longer Answer When you create a component for Joomla! you specify the menu settings for each view using an XML file usual the same name as the view file in it's view/tmpl/ directory.
Typically the url to a specific view & task in a component would look like these:
?option=com_mycomponent ?option=com_mycomponent&view=userdetails ?option=com_mycomponent&view=userdetails&task=main Joomla!'s framework will automatically use the view & task params to get your components correct controller and view (or sub-view). I'm not sure that it does anything with the module param that you have in your URL's so I'd guess you're trapping and processing that yourself.
The on_register is a basic module function of ?MODULE. If the gen_server is a singleton server, you can send the name to it using gen_server:call(?MODULE, {name, Name}) or gen_server:cast(?MODULE, {name, Name}).
So the result would look like:
on_register(SID, JID, INFO) -> {_, _, _, _, Name, _, _} = JID, gen_server:call(?MODULE, {name, Name}), ok.
-35053279 0 Based on this comment:
Trying .\SQLEXPRESS in SQL Server Management Studio Express throws an error that says that "This version of Microsoft SQL Server Management Studio Express can only be used to connect to SQL Server 2005 servers". So this is the problem, I think.
.\SQLEXPRESS is the correct server name, but you have the wrong version of client tools (SQL Server Management Studio). To find out the version of SQL you are connecting to, there are a number of suggestions here: https://www.mssqltips.com/sqlservertip/1140/how-to-tell-what-sql-server-version-you-are-running/
But since you can't connect yet the easiest thing to do is go searching for sqlserver.exe, right click, properties, version. If you have multiple version you need take note of the folder that it's in and check the SQLExpress one. You can also check in services.
Once you've worked out the version, download and install just the management tools for that version.
-37186302 0 Putting CreateElementNS in a function (SVG Groups, shapes etc)I am trying to turn this code right here:
var group = function(n){ n = document.createElementNS(svg, "g" ); } Am I doing it right? I have also tried with 'Return n = doc...' but that doesn't seem to work either.
At the moment I just have allot of lines like this;
e.g1 = document.createElementNS(svg, "g" ); t2 = "translate("+e.x+" "+e.y+"), rotate("+e.z+" "+0+" "+0+")"; e.g1.setAttributeNS(null, "transform", t2); e.g1.setAttributeNS(null,"fill", "url(#gradient)"); e.g1.setAttributeNS(null,"stroke", "none"); e.g1.setAttributeNS(null,"stroke-width", e.a*0.03); document.getElementById("mySVG").appendChild(e.g1); Would prefer it to look more like this..
group(e.g1); t2 = "translate("+e.x+" "+e.y+"), rotate("+e.z+" "+0+" "+0+")"; transform(e.g1, t2); fill(e.g1, url(#gradient)); stroke(e.g1, #000); strokewidth(e.g1, (e.a*0.03)); append(e.g1); Thanks, shorter code is what I need!
-33047711 0Yes, Browser-Sync has snippet-mode for the case in which a proxy won't work. The general usage is to just cut and paste a snippet into the body of your pages and you'll get the injecting/reloading support. However this is a lot of perpetual manual work.
I came up with a convention to eliminate the manual work.
First add to your Web.config:
<configuration> <appSettings> <add key="IncludeBrowserSync" value="true" /> <!--...--> </appSettings> <!--...--> </configuration> Then add to your Web.Release.config:
<appSettings> <add key="IncludeBrowserSync" value="false" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" /> </appSettings> This allows us to not worry about accidentally deploying the snippet.
Create in the Shared Views folder a BrowserSync.cshtml:
@using System.Configuration @if (ConfigurationManager.AppSettings["IncludeBrowserSync"]?.ToLower().Contains("t") ?? false) { <!-- BrowserSync:SNIPPET--> <script type='text/javascript' id="__bs_script__"> //<![CDATA[ document.write("<script async src='http://HOST:PORT/browser-sync/browser-sync-client.js'><\/script>".replace("HOST", location.hostname).replace("PORT", parseInt(location.port) + 1)); //]]> </script> <!-- BS:BrowserSyncs:END--> } As you can see for the snippet, its going to be a little different from what browser sync tells you to cut and paste. The main difference is that it's not going to include the version number (so npm can update browser-sync without breaking your snippet) and it's using a convention for the port number to be one above what IISExpress is serving.
Now add @Html.Partial("BrowserSync") right above the </body in any _layout.html you have.
Finally to make this all work in your gulpfile.js with a serve task for browse-sync.
var gulp = require('gulp'); var browserSync = require('browser-sync').create(); ... var dllName = "<YourProjectName>.dll"; var iisPort = <YourPortNumber>; gulp.task('serve', ['default'], function () { browserSync.init({ port: iisPort + 1; }); gulp.watch("<your wildchar to find your editable css files>", ['compile-minimize-css']); /*...*/ gulp.watch("Views/**/*.cshtml").on('change', browserSync.reload); gulp.watch("bin/"+dllName).on('change', browserSync.reload); }); Enjoy automatic refreshes after you start serve in the task runner!
If it will always be a div, and you know the element's ID:
$("#myElement div[data-custom-property]:first") Otherwise, this will work, too, though it's best to be as specific as possible:
$("[data-custom-property]:first")
-21426905 0 Do this:
params[:list].each do |hash| hash['id'] # => 3 hash['status'] # => true end
-9684565 0 Your best bet appears to be 'CEESITST', as it appears to exist in z/OS COBOL. I found an example using that as well as the other bit manipulation programs.
http://esj.com/articles/2000/09/01/callable-service-manipulating-binary-data-at-the-bit-level.aspx
-11330347 1 Python XML comparisonI have 2 files each with a list of items which all have 3 properties. What is the quickest way to compare these files and list the differences, i.e. the items that are not in both files.
For the items to be the same, all 3 properties have to agree. Also the files were in XML.
-14885885 0Actually it was straight-forward selenium code:
click link="Change..." pause 200 click //ul[contains(@id,'fruit-switcher')]//ul[contains(@class,'dropdown-menu')]/li[3]/a click link="Change..." pause 600 click //ul[contains(@id,'fruit-switcher')]//a[contains(text(),'Bananas')]
-31551380 0 You can change the room speed in the room settings, this is the number of steps per second. This property can also be accessed and changed mid-game with the room_speed global.
You can also access the actual screen update speed with the fps read-only global. Note: screen fps is totally independent from the draw event, which happens at the end of each step.
If bitarray can't be installed, the 1d solution in Dot Product in Python without NumPy can be used with the same nested comprehension (http://stackoverflow.com/a/35241087/901925). This does not take advantage of the 0/1 nature of the data. So basically it's an exercise in nested iterations.
def dot1d(a,b): return sum(x*y for x,y in zip(a,b)) def dot_2cmp(a): return [[dot1d(r,c) for c in a] for r in a] itertools.product can be used to iterate over the row and column combinations, but the result is a 1d list, which then needs to be grouped (but this step is fast):
def dot2d(a): aa=[dot1d(x,y) for x,y in itertools.product(a,a)] return [aa[i::len(a)] for i in range(len(a))] testing:
a=[[1,0,1,0],[0,1,0,1],[0,0,1,1],[1,1,0,0]] In [246]: dot2d(a) Out[246]: [[2, 0, 1, 1], [0, 2, 1, 1], [1, 1, 2, 0], [1, 1, 0, 2]] In [247]: dot_2cmp(a) Out[247]: [[2, 0, 1, 1], [0, 2, 1, 1], [1, 1, 2, 0], [1, 1, 0, 2]] In [248]: np.dot(np.array(a),np.array(a).T).tolist() Out[248]: [[2, 0, 1, 1], [0, 2, 1, 1], [1, 1, 2, 0], [1, 1, 0, 2]] In timings on a larger list, the 2 list operations take the same time. The array version, even with the in/out array conversion is considerably faster.
In [254]: b=np.random.randint(0,2,(100,100)).tolist() In [255]: timeit np.dot(np.array(b),np.array(b).T).tolist() 100 loops, best of 3: 5.46 ms per loop In [256]: timeit dot2d(b) 10 loops, best of 3: 177 ms per loop In [257]: timeit dot_2cmp(b) 10 loops, best of 3: 177 ms per loop The result is symmetric, so it might be worth the effort to skip the duplicate calculations. Mapping them back on to the nested list will be more work than in numpy.
In [265]: timeit [[dot1d(r,c) for c in b[i:]] for i,r in enumerate(b)] 10 loops, best of 3: 90.1 ms per loop For what it's worth I don't consider any of these solutions 'more Pythonic' than the others. As long as it is written in clear, running, Python it is Pythonic.
-3966342 0No, I don't believe there is. In a standard Subversion workflow, it's quite rare to need to type the full URL -- most operations are on an already-checked-out working copy -- and in any case, if you're working with branches and tags, the URL would change between invocations.
That's not to say that the idea isn't any use, just that it's not useful enough for the developers to have added it.
If, like me, you have difficulty remembering what the URL was for a working copy you want to work with, svn info will give it to you.
I am new in IOS developing. In Main.storyoard, I added a new viewcontroller, assigned it to a new class LoginViewController and provided a storyboard-ID loginview. In the LoginViewController class, after successful login I tried the following code to call the default viewcontroller having storyboard-ID webview.
NSString *storyboardName = @"Main"; UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil]; UIViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"webview"]; [self presentViewController:vc animated:YES completion:nil]; During debugging I got the following exception
2016-05-04 18:37:11.020 gcmexample[2690:86862] bool _WebTryThreadLock(bool), 0x7fa5d3f3d840: Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now... 1 0x11328d34b WebThreadLock 2 0x10e5547dd -[UIWebView _webViewCommonInitWithWebView:scalesPageToFit:] 3 0x10e555179 -[UIWebView initWithCoder:] 4 0x10e7b5822 UINibDecoderDecodeObjectForValue 5 0x10e7b5558 -[UINibDecoder decodeObjectForKey:] 6 0x10e5e1483 -[UIRuntimeConnection initWithCoder:] 7 0x10e7b5822 UINibDecoderDecodeObjectForValue 8
0x10e7b59e3 UINibDecoderDecodeObjectForValue 9 0x10e7b5558 -[UINibDecoder decodeObjectForKey:] 10 0x10e5e06c3 -[UINib instantiateWithOwner:options:] 11 0x10e3b9eea -[UIViewController _loadViewFromNibNamed:bundle:] 12 0x10e3ba816 -[UIViewController loadView] 13 0x10e3bab74 -[UIViewController loadViewIfRequired] 14 0x10e3bb2e7 -[UIViewController view] 15 0x10eb65f87 -[_UIFullscreenPresentationController _setPresentedViewController:] 16 0x10e38af62 -[UIPresentationController initWithPresentedViewController:presentingViewController:] 17 0x10e3cdc8c -[UIViewController _presentViewController:withAnimationController:completion:] 18 0x10e3d0f2c -[UIViewController _performCoordinatedPresentOrDismiss:animated:] 19 0x10e3d0a3b -[UIViewController presentViewController:animated:completion:] 20 0x10d065eed 34-[LoginViewController btnSign_in:]_block_invoke 21 0x10fd3f6b5 __75-[__NSURLSessionLocal taskForClass:request:uploadFile:bodyData:completion:]_block_invoke 22 0x10fd51a02 __49-[__NSCFLocalSessionTask _task_onqueue_didFinish]_block_invoke 23 0x10d1dc304 __NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK 24 0x10d118035 -[NSBlockOperation main] 25 0x10d0faf8a -[__NSOperationInternal _start:] 26 0x10d0fab9b __NSOQSchedule_f 27 0x11057f49b _dispatch_client_callout 28 0x1105658ec _dispatch_queue_drain 29 0x110564e0d _dispatch_queue_invoke 30 0x110567a56 _dispatch_root_queue_drain 31 0x1105674c5 _dispatch_worker_thread3
Does anyone know whats the error here? Please help.
-31528441 0 How to to filter by media subtype using NSPredicate with PHFetchOptionsHow do I filter by media subtype using NSPredicate with PHFetchOptions? I'm trying to exclude slow mo (high frame rate) and time lapse videos. I keep getting strange results when I try to use the predicate field of PHFetchOptions.
My phone has a bunch (120+) regular videos, and one slow mo video. When I run the example from Apple's docs, I get the correct result back: 1 slow mo video.
PHFetchOptions *options = [PHFetchOptions new]; options.predicate = [NSPredicate predicateWithFormat:@"(mediaSubtype & %d) != 0 || (mediaSubtype & %d) != 0", PHAssetMediaSubtypeVideoTimelapse, PHAssetMediaSubtypeVideoHighFrameRate]; But I'm trying to exclude slow mo, rather than select it. However if I negate the filter condition, I get zero results back:
options.predicate = [NSPredicate predicateWithFormat:@"(mediaSubtype & %d) == 0", PHAssetMediaSubtypeVideoHighFrameRate]; <PHFetchResult: 0x1702a6660> count=0 Confusingly, the Apple docs list the name of the field as mediaSubtypes (with an "s"), while their sample predicate is filtering on mediaSubtype (without an "s").
Trying to filter on mediaSubtypes produces an error:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can't do bit operators on non-numbers' Has anyone been able to make heads or tails of this predicate?
-34670951 0 php bootstrap error with modalI have the below scripts running but once I add a remote file link for the modal, it will not update.
Any help will be appreciated.
I'm modifying the class.crud.php file to include this line
removing
<a href="edit-data.php?edit_id=<?php print($row['id']); ?>"><i class="glyphicon glyphicon-edit"></i></a> replacing with
<a data-toggle="modal" class="btn btn-info" href="edit-data.php?edit_id=<?php print($row['id']); ?>" data-target="#myModal"><i class="glyphicon glyphicon-edit"></i></a> INDEX.PHP
<?php include_once 'dbconfig.php'; ?> <?php include_once 'header.php'; ?> <div class="clearfix"></div> <div class="container"> <table class='table table-bordered table-responsive'> <tr> <th>#</th> <th>First Name</th> <th>Last Name</th> <th>E - mail ID</th> <th>Contact No</th> <th colspan="2" align="center">Actions</th> </tr> <?php $query = "SELECT * FROM tblUsers"; $records_per_page=10; $newquery = $crud->paging($query,$records_per_page); $crud->dataview($newquery); ?> <tr> <td colspan="7" align="center"> <div class="pagination-wrap"> <?php $crud->paginglink($query,$records_per_page); ?> </div> </td> </tr> </table> </div> <!-- Modal --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> </div> <!-- /.modal-content --> </div> <!-- /.modal-dialog --> </div> <!-- /.modal --> <?php include_once 'footer.php'; ?> CLASS.CRUD.PHP
public function update($id,$fname,$lname,$email,$level_id) { try { $stmt=$this->db->prepare("UPDATE tblUsers SET firstname=:fname, lastname=:lname, email=:email, level_id=:contact WHERE id=:id "); $stmt->bindparam(":fname",$fname); $stmt->bindparam(":lname",$lname); $stmt->bindparam(":email",$email); $stmt->bindparam(":contact",$level_id); $stmt->bindparam(":id",$id); $stmt->execute(); return true; } catch(PDOException $e) { echo $e->getMessage(); return false; } } public function delete($id) { $stmt = $this->db->prepare("DELETE FROM tblUsers WHERE id=:id"); $stmt->bindparam(":id",$id); $stmt->execute(); return true; } /* paging */ public function dataview($query) { $stmt = $this->db->prepare($query); $stmt->execute(); if($stmt->rowCount()>0) { while($row=$stmt->fetch(PDO::FETCH_ASSOC)) { ?> <tr> <td><?php print($row['id']); ?></td> <td><?php print($row['firstname']); ?></td> <td><?php print($row['lastname']); ?></td> <td><?php print($row['email']); ?></td> <td><?php print($row['level_id']); ?></td> <td align="center"> <a href="edit-data.php?edit_id=<?php print($row['id']); ?>"><i class="glyphicon glyphicon-edit"></i></a> </td> <td align="center"> <a href="delete.php?delete_id=<?php print($row['id']); ?>"><i class="glyphicon glyphicon-remove-circle"></i></a> </td> </tr> <?php } } else { ?> <tr> <td>Nothing here...</td> </tr> <?php } } EDIT-DATA.PHP
<?php include_once 'dbconfig.php'; if(isset($_POST['btn-update'])) { $id = $_GET['edit_id']; $fname = $_POST['firstname']; $lname = $_POST['lastname']; $email = $_POST['email']; $level_id = $_POST['level_id']; if($crud->update($id,$fname,$lname,$email,$level_id)) { $msg = "<div class='alert alert-info'> <strong>WOW!</strong> Record was updated successfully <a href='index.php'>HOME</a>! </div>"; } else { $msg = "<div class='alert alert-warning'> <strong>SORRY!</strong> ERROR while updating record ! </div>"; } } if(isset($_GET['edit_id'])) { $id = $_GET['edit_id']; extract($crud->getID($id)); } ?> <?php include_once 'header.php'; ?> <div class="clearfix"></div> <div class="container"> <?php if(isset($msg)) { echo $msg; } ?> </div> <div class="clearfix"></div> <br /> <div class="modal-header" id="myModal"> <form method='post'> <div class="form-group"> <label for="email">First Name:</label> <input type='text' name='firstname' class='form-control' value="<?php echo $firstname; ?>" required> </div> <div class="form-group"> <label for="email">Last Name:</label> <input type='text' name='lastname' class='form-control' value="<?php echo $lastname; ?>" required> </div> <div class="form-group"> <label for="email">Email:</label> <input type='text' name='email' class='form-control' value="<?php echo $email; ?>" required> </div> <div class="form-group"> <label for="email">Level ID:</label> <input type='text' name='level_id' class='form-control' value="<?php echo $level_id; ?>" required> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary" name="btn-update">Save changes</button> </div> </form> </div>
-5420072 0 Lasso is an interpreted programming language with PHP-like syntax, and a commercial server geared towards database-driven web applications. Its current stable release is 9.2, with 9.3 in development, while the legacy version is also maintained as 8.6. Information about Lasso releases is available at http://www.lassosoft.com/.
Documentation and Community
The LassoGuide site is the official location for Lasso 9's documentation, while a language reference for all versions is at LassoDocs, and an active archive of the LassoTalk mailing list is also available.
-22997038 0You have a space on the end of your variable, and you've set IFS so that it's not being removed as part of word splitting. Here's a simplified test case that exibits your problem:
IFS=$'\r\n' value=$(echo "hello - world" | cut -d - -f 1) [ $value = hello ] && echo "works" || echo "fails" The simplest solution is to cut your variables before the first space, rather than after the space but before the dash:
boolser=($(getsebool -a | grep $serv | cut -d ' ' -f1))
-23147907 0 select * from (select id,subject_id FROM table group by subject_id)tempalias where subject_id=1 select * from (select id,subject_id FROM table group by subject_id)tempalias where subject_id=2
-19598200 0 re.sub does not perform the substitution in-place. It returns a new string with the result of the substitution. You are free to reassign to the original variable name if you like, of course.
So what you want is
page = re.sub("&", '', page)
-38617868 0 The commits are outputted by the git svn clone command, preceded by an r. The last commit that is outputted is the problematic one.
The next example shows what the git svn clone command outputs when begin procesing the Subversion revision 15 as the Git commit 373fb1...:
r15 = 373fb1de430a6b1e89585425f276aae0058c3deb (refs/remotes/svn/trunk) git svn clone command using the -r (revision) optionUse this method:
git svn clone -r 0:<problematic_revision - 1> <repo URL> git svn clone -r <problematic_revision - 1>:problematic_revision <repo URL> git svn clone -r <problematic_revision>:HEAD <repo URL> Supposing the revision 15 as the problematic one, and the repo in /tmp/svn/repo/, the solution would be:
git svn clone -r 0:14 file:///tmp/svn/repo/ git svn clone -r 14:15 file:///tmp/svn/repo/ git svn clone -r 15:HEAD file:///tmp/svn/repo/
-6817303 0 Don't do it.
It's very likely that your server will never become compromised, and that your application will be mostly secure, blah blah blah, that's not the point. It is possible for a server to become partially compromised (too many vectors of attack, what if the php json_encode function became compromised on your server?).
The simple solution is not to trust anything sent by anyone. Modern browsers have native JSON parsers, and www.json.org provides a long list of JSON parsers for various different languages. The JS versions will fall back on the native implementation for speed.
What all this means is that there's no good reason to use eval for JSON parsing.
Here is a Class that I wrote and used at several places look thru the methods to see what you can use..
using System; using System.Text; using System.Collections; using System.DirectoryServices; using System.Diagnostics; using System.Data.Common; namespace Vertex_VVIS.SourceCode { public class LdapAuthentication { private String _path; private String _filterAttribute; public LdapAuthentication(String path) { _path = path; } public bool IsAuthenticated(String domain, String username, String pwd) { String domainAndUsername = domain + @"\" + username; DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd); try { //Bind to the native AdsObject to force authentication. // Object obj = entry.NativeObject; DirectorySearcher search = new DirectorySearcher(entry); search.Filter = "(SAMAccountName=" + username + ")"; search.PropertiesToLoad.Add("cn"); SearchResult result = search.FindOne(); if (null == result) { return false; } //Update the new path to the user in the directory. _path = result.Path; _filterAttribute = (String)result.Properties["cn"][0]; } catch (Exception ex) { throw new Exception("Error authenticating user. " + ex.Message); } return true; } public String GetName(string username) { String thename = null; try { DirectoryEntry de = new DirectoryEntry(_path); DirectorySearcher ds = new DirectorySearcher(de); ds.Filter = String.Format("(SAMAccountName={0})", username); ds.PropertiesToLoad.Add("displayName"); SearchResult result = ds.FindOne(); if (result.Properties["displayName"].Count > 0) { thename = result.Properties["displayName"][0].ToString(); } else { thename = "NA"; } } catch (Exception ex) { throw new Exception("Error Getting Name. " + ex.Message); } return thename.ToString(); } public String GetEmailAddress(string username) { String theaddress = null; try { DirectoryEntry de = new DirectoryEntry(_path); DirectorySearcher ds = new DirectorySearcher(de); ds.Filter = String.Format("(SAMAccountName={0})", username); ds.PropertiesToLoad.Add("mail"); SearchResult result = ds.FindOne(); theaddress = result.Properties["mail"][0].ToString(); de.Close(); } catch (Exception ex) { throw new Exception("Error Getting Email Address. " + ex.Message); } return theaddress.ToString(); } public String GetTitle(string username) { String thetitle = null; try { DirectoryEntry de = new DirectoryEntry(_path); DirectorySearcher ds = new DirectorySearcher(de); ds.Filter = String.Format("(SAMAccountName={0})", username); ds.PropertiesToLoad.Add("title"); SearchResult result = ds.FindOne(); result.GetDirectoryEntry(); if (result.Properties["title"].Count > 0) { thetitle = result.Properties["title"][0].ToString(); } else { thetitle = "NA"; } } catch (Exception ex) { throw new Exception("Error Getting the Title. " + ex.Message); } return thetitle.ToString(); } public String GetPhone(string username) { String thephone = null; try { DirectoryEntry de = new DirectoryEntry(_path); DirectorySearcher ds = new DirectorySearcher(de); ds.Filter = String.Format("(SAMAccountName={0})", username); ds.PropertiesToLoad.Add("mobile"); SearchResult result = ds.FindOne(); result.GetDirectoryEntry(); if (result.Properties["mobile"].Count > 0) { thephone = result.Properties["mobile"][0].ToString(); } else { thephone = "NA"; } } catch (Exception ex) { throw new Exception("Error Getting Phone Number. " + ex.Message); } return thephone.ToString(); } public String GetGroups() { DirectorySearcher search = new DirectorySearcher(_path); search.Filter = "(cn=" + _filterAttribute + ")"; search.PropertiesToLoad.Add("memberOf"); StringBuilder groupNames = new StringBuilder(); try { SearchResult result = search.FindOne(); int propertyCount = result.Properties["memberOf"].Count; String dn; int equalsIndex, commaIndex; for (int propertyCounter = 0; propertyCounter < propertyCount; propertyCounter++) { dn = (String)result.Properties["memberOf"][propertyCounter]; equalsIndex = dn.IndexOf("=", 1); commaIndex = dn.IndexOf(",", 1); if (-1 == equalsIndex) { return null; } groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1)); groupNames.Append("|"); } } catch (Exception ex) { throw new Exception("Error obtaining group names. " + ex.Message); } return groupNames.ToString(); } public bool IsUserGroupMember(string strUserName, string strGroupString) { bool bMemberOf = false; ResultPropertyValueCollection rpvcResult = null; try { DirectoryEntry de = new DirectoryEntry(_path); DirectorySearcher ds = new DirectorySearcher(de); ds.Filter = String.Format("(SAMAccountName={0})", strUserName); ds.PropertiesToLoad.Add("memberOf"); SearchResult result = ds.FindOne(); string propertyName = "memberOf"; rpvcResult = result.Properties[propertyName]; foreach (Object propertyValue in rpvcResult) { if (propertyValue.ToString().ToUpper() == strGroupString.ToUpper()) { bMemberOf = true; break; } } } catch (Exception ex) { throw new Exception("Error Getting member of. " + ex.Message); } return bMemberOf; } } }
-35584973 0 The drawing setup is quite involved, but the actual calls required to draw are fairly straightforward. From the tri.c (which draws a 2D triangle):
// ... vkCmdBeginRenderPass(demo->draw_cmd, &rp_begin, VK_SUBPASS_CONTENTS_INLINE); vkCmdBindPipeline(demo->draw_cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, demo->pipeline); vkCmdBindDescriptorSets(demo->draw_cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, demo->pipeline_layout, 0, 1, & demo->desc_set, 0, NULL); VkViewport viewport = {}; viewport.height = (float) demo->height; viewport.width = (float) demo->width; viewport.minDepth = (float) 0.0f; viewport.maxDepth = (float) 1.0f; vkCmdSetViewport(demo->draw_cmd, 0, 1, &viewport); VkRect2D scissor = {}; scissor.extent.width = demo->width; scissor.extent.height = demo->height; scissor.offset.x = 0; scissor.offset.y = 0; vkCmdSetScissor(demo->draw_cmd, 0, 1, &scissor); VkDeviceSize offsets[1] = {0}; vkCmdBindVertexBuffers(demo->draw_cmd, VERTEX_BUFFER_BIND_ID, 1, &demo->vertices.buf, offsets); vkCmdDraw(demo->draw_cmd, 3, 1, 0, 0); vkCmdEndRenderPass(demo->draw_cmd); // ... This snippet assumes that you've already gotten the VkPipeline (which include shaders, etc.), VkBuffer (for the vertex buffer), and the VkCommandBuffer in appropriate states. It's the vkCmdDraw that actually issues the command to draw, once the containing VkCommandBuffer is executed.
I am currently working on my own SMTP server and I can successfully send email arounds from various programs and web pages such as Outlook, PHP and Pear Mail.
The next stage I need to do is to try and send an attachment via my SMTP server. I have tried doing a LAN trace of my server while sending an attachment via PHP to another SMTP server and I can see I get the follwing from the client:
DATA fragment, 661 bytes I'm not sure if this is related to the attachment or not.
If it is, is this just telling the SMTP server how long the file is and then I should just write a base 64 encoded string onto the network stream and write it to a file to be used for sending the email on.
Thanks for any help you can provide.
-20111305 0The regex you can use is like this:
/SIP\/(\d+)@PBX/ This finds:
text SIP followed by a / (which is escaped so it isn't interpreted as the end of the regex) followed by one or more digits (captured in a group delineated with parens) followed by the text @PBX And, then you pull out the first matched group if there's a match.
And, if you have nothing else to go on other than it's in a <td> in your page, then you can use this generic code that looks at all <td> elements in the page. Ideally, you would use the structure of the page to more clearly target the appropriate <td> cells.
var tds = document.getElementsByTagName("td"); var regex = /SIP\/(\d+)@PBX/; for (var i = 0; i < tds.length; i++) { var matches = tds[i].innerHTML.match(regex); if (matches) { var number = parseInt(matches[1], 10); // process the number here } } Working demo: http://jsfiddle.net/jfriend00/vDwfs/
If the HTML is not in your page, but in a string, then you can just use the same regex to search for it in the HTML string. You could bracket it with <td> and </td> if that seems wise based on your context.
var matches, number; var regex = /SIP\/(\d+)@PBX/g; while (matches = regex.exec(htmlString)) { number = parseInt(matches[1], 10); // process the number here }
-9323308 0 When a assembly' s AssemblyVersion is changed, If it has strong name, the referencing assemblies need to be recompiled, otherwise the assembly does not load! If it does not have strong name, if not explicitly added to project file, it will not be copied to output directory when build so you may miss depending assemblies, especially after cleaning the output directory.
-21427745 0I solved the same issue with UIViewController categories that is in the common included file. So each UIviewController in its init function calls [self setMyColor].
This is my code:
@interface ColorViewController : UIViewController - (void) setMyColor; @end
-27015318 0 How to set order of SQL-response? I've got a mule flow that queries a SQL-server database and then converts the response to JSON and then writes the JSON comma separated to file.
My problem is that the order of the column in the written file doesn't match the order of the fields in the query. How tho define the order of columns in a query answer?
The JSON to CSV conversion is like this:
public class Bean2CSV { /** * @param args * @throws JSONException */ public String conv2csv(Object input) throws JSONException { if (!input.equals(null)){ String inputstr = (String)input; JSONArray jsonArr = new JSONArray(inputstr); String csv = CDL.toString(jsonArr); csv = csv.replace(',', ';'); System.out.println(inputstr); //csv System.out.println(csv); //csv return csv; } else return "";} } and here is the flow
<?xml version="1.0" encoding="UTF-8"?> <mule xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:json="http://www.mulesoft.org/schema/mule/json" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns:file="http://www.mulesoft.org/schema/mule/file" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.mulesoft.org/schema/mule/jdbc" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:core="http://www.mulesoft.org/schema/mule/core" version="CE-3.4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/json http://www.mulesoft.org/schema/mule/json/current/mule-json.xsd http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule- http.xsd http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/current/mule-file.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.mulesoft.org/schema/mule/jdbc http://www.mulesoft.org/schema/mule/jdbc/current/mule-jdbc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring- beans-current.xsd http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd"> <context:property-placeholder location="classpath:cognos_import.properties" ignore-resource-not-found="true"/> <spring:beans> <spring:bean id="dataSource" name="dataSource" class="org.enhydra.jdbc.standard.StandardDataSource" destroy-method="shutdown"> <spring:property name="driverName" value="net.sourceforge.jtds.jdbc.Driver"/> <spring:property name="user" value="${dbusername}"/> <spring:property name="password" value="${dbpassword}"/> </spring:bean> <spring:bean id="changeDB" class="ChangeDatabase"> <spring:property name="serverip" value="${dbserverip}"/> <spring:property name="serverport" value="${dbserverport}"/> <spring:property name="dbprefix" value="${dbprefix}"/> </spring:bean> </spring:beans> <jdbc:connector name="db_conn" dataSource-ref="dataSource" validateConnections="false" pollingFrequency="5000" doc:name="Database"> <jdbc:query key="readbal" value="SELECT #[header:INBOUND:company] as company, AcNo as Konto , R2 as Avd, #[header:INBOUND:period] as Period, sum(AcAm) as Saldo FROM AcTr WHERE (AcYrPr <= #[header:INBOUND:period]) and (AcNo < 3000) GROUP BY AcNo,R2 ORDER BY AcNo,R2;"/> <jdbc:query key="readres" value="SELECT #[header:INBOUND:company] as company, AcNo as Konto , R2 as Avd, #[header:INBOUND:period] as Period, sum(AcAm) as Saldo FROM AcTr WHERE (AcYrPr <= #[header:INBOUND:period]) and (AcYrPr >= #[header:INBOUND:starttid]) and (AcNo >= 3000) GROUP BY AcNo,R2 ORDER BY AcNo,R2"/> <jdbc:query key="readiclr" value="SELECT #[header:INBOUND:company] as company, AcTr.AcNo as Konto , AcTr.R2 as Avd, #[header:INBOUND:period] as Period, sum(AcTr.AcAm) as Saldo,sum(AcTr.CurAm) as ValutaBel, AcTr.Cur as Valuta, AcTr.R1 as FtgID FROM AcTr LEFT JOIN Actor ON AcTr.R1=Actor.R1 WHERE (AcTr.AcYrPr <= #[header:INBOUND:period]) and (AcTr.AcYrPr >= #[header:INBOUND:starttid]) and Actor.SAcSet=2 and (AcTr.AcNo=3019 or AcTr.AcNo=3099 or AcTr.AcNo=3199 or AcTr.AcNo=3299 or AcTr.AcNo=3499 or AcTr.AcNo=3519 or AcTr.AcNo=3599 or AcTr.AcNo=3699 or AcTr.AcNo=3799 or AcTr.AcNo=3919 or AcTr.AcNo=3999 or AcTr.AcNo=4299 or AcTr.AcNo=4399 or AcTr.AcNo=4599 or AcTr.AcNo=4699 or AcTr.AcNo=4799 or AcTr.AcNo=5099 or AcTr.AcNo=5299 or AcTr.AcNo=5499 or AcTr.AcNo=5699 or AcTr.AcNo=5799 or AcTr.AcNo=5999 or AcTr.AcNo=6099 or AcTr.AcNo=6399 or AcTr.AcNo=6499 or AcTr.AcNo=6999 or AcTr.AcNo=7999 or AcTr.AcNo=8399 or AcTr.AcNo=8499) and AcTr.Sup<>0 GROUP BY AcTr.AcNo,AcTr.R2,AcTr.R1,AcTr.Cur"/> <jdbc:query key="readickr" value="SELECT #[header:INBOUND:company] as company, AcTr.AcNo as Konto , AcTr.R2 as Avd, #[header:INBOUND:period] as Period, sum(AcTr.AcAm) as Saldo,sum(AcTr.CurAm) as ValutaBel, AcTr.Cur as Valuta, AcTr.R1 as FtgID FROM AcTr LEFT JOIN Actor ON AcTr.R1=Actor.R1 WHERE (AcTr.AcYrPr <= #[header:INBOUND:period]) and (AcTr.AcYrPr >= #[header:INBOUND:starttid]) and Actor.CAcSet=2 and (AcTr.AcNo=3019 or AcTr.AcNo=3099 or AcTr.AcNo=3199 or AcTr.AcNo=3299 or AcTr.AcNo=3499 or AcTr.AcNo=3519 or AcTr.AcNo=3599 or AcTr.AcNo=3699 or AcTr.AcNo=3799 or AcTr.AcNo=3919 or AcTr.AcNo=3999 or AcTr.AcNo=4299 or AcTr.AcNo=4399 or AcTr.AcNo=4599 or AcTr.AcNo=4699 or AcTr.AcNo=4799 or AcTr.AcNo=5099 or AcTr.AcNo=5299 or AcTr.AcNo=5499 or AcTr.AcNo=5699 or AcTr.AcNo=5799 or AcTr.AcNo=5999 or AcTr.AcNo=6099 or AcTr.AcNo=6399 or AcTr.AcNo=6499 or AcTr.AcNo=6999 or AcTr.AcNo=7999 or AcTr.AcNo=8399 or AcTr.AcNo=8499) and AcTr.Cust<>0 GROUP BY AcTr.AcNo,AcTr.R2,AcTr.R1,AcTr.Cur"/> <jdbc:query key="readiclb" value="SELECT #[header:INBOUND:company] as company, AcTr.AcNo as Konto, AcTr.R2 as Avd, #[header:INBOUND:period] as Period, sum(AcTr.AcAm) as Saldo, sum(AcTr.CurAm) as ValutaBel, AcTr.Cur as Valuta, AcTr.R1 as FtgID FROM AcTr LEFT JOIN Actor ON AcTr.R1=Actor.R1 WHERE (AcTr.AcYrPr <= #[header:INBOUND:period]) and Actor.SAcSet=2 and AcTr.Sup<>0 and (AcTr.AcNo=1511 or AcTr.AcNo=2441) GROUP BY AcTr.AcNo,AcTr.R2,AcTr.R1,AcTr.Cur"/> <jdbc:query key="readickb" value="SELECT #[header:INBOUND:company] as company, AcTr.AcNo as Konto, AcTr.R2 as Avd, #[header:INBOUND:period] as Period, sum(AcTr.AcAm) as Saldo, sum(AcTr.CurAm) as ValutaBel, AcTr.Cur as Valuta, AcTr.R1 as FtgID FROM AcTr LEFT JOIN Actor ON AcTr.R1=Actor.R1 WHERE (AcTr.AcYrPr <= #[header:INBOUND:period]) and Actor.CAcSet=2 and AcTr.Cust<>0 and (AcTr.AcNo=1511 or AcTr.AcNo=2441) GROUP BY AcTr.AcNo,AcTr.R2,AcTr.R1,AcTr.Cur"/> </jdbc:connector> <file:connector name="output" outputPattern=" #[function:datestamp:dd-MM-yy-hh-mm-ss]#[header:INBOUND:company].txt" autoDelete="false" outputAppend="true" streaming="false" validateConnections="false" doc:name="File"/> <message-properties-transformer name="delete-content-type-header" doc:name="Message Properties"> <delete-message-property key="Content-type"/> </message-properties-transformer> <message-properties-transformer name="add-csv-content-type-header" doc:name="Message Properties"> <add-message-property key="Content-Type" value="text/csv"/> </message-properties-transformer> <message-properties-transformer name="add-filename" doc:name="Message Properties"> <add-message-property key="Content-Disposition" value="attachment; filename=testfil.txt"/> </message-properties-transformer> <flow name="CD-test1Flow1" doc:name="CD-test1Flow1"> <http:inbound-endpoint exchange-pattern="request-response" host="localhost" port="8082" doc:name="HTTP"/> <not-filter doc:name="Not"> <wildcard-filter pattern="*favicon*" caseSensitive="true"/> </not-filter> <logger message="Log1 #[message.getPayload()]! " level="INFO" doc:name="Logger1"/> <http:body-to-parameter-map-transformer doc:name="Body to Parameter Map"/> <component class="ValidationService3x" doc:name="Java"/> <echo-component doc:name="Echo"/> <set-variable variableName="Filename" value=" #[function:datestamp:dd-MM-yy-hh-mm-ss]-#[header:INBOUND:company]-#[header:INBOUND:period]" doc:name="FilenameVar"/> <component doc:name="Java"> <spring-object bean="changeDB"/> </component> <all doc:name="All"> <processor-chain> <jdbc:outbound-endpoint exchange-pattern="request-response" queryKey="readbal" connector-ref="db_conn" doc:name="DB"/> <expression-filter expression="payload.size() > 0" doc:name="not empty"/> <json:object-to-json-transformer doc:name="Object to JSON"/> <component class="Bean2CSV" doc:name="Java"/> <echo-component doc:name="Echo"/> <file:outbound-endpoint path="${outputfolder}" outputPattern="#[flowVars['Filename']]-bal.csv" connector-ref="output" doc:name="File"/> </processor-chain> <processor-chain> <jdbc:outbound-endpoint exchange-pattern="request-response" queryKey="readres" connector-ref="db_conn" doc:name="DB100-ickr"/> <expression-filter expression="payload.size() > 0" doc:name="not empty"/> <json:object-to-json-transformer doc:name="Object to JSON"/> <component class="Bean2CSV" doc:name="Java"/> <echo-component doc:name="Echo"/> <file:outbound-endpoint path="${outputfolder}" outputPattern="#[flowVars['Filename']]-res.csv" connector-ref="output" doc:name="File"/> </processor-chain> <processor-chain> <jdbc:outbound-endpoint exchange-pattern="request-response" queryKey="readiclb" connector-ref="db_conn" doc:name="DB100-ickr"/> <expression-filter expression="payload.size() > 0" doc:name="not empty"/> <json:object-to-json-transformer doc:name="Object to JSON"/> <component class="Bean2CSV" doc:name="Java"/> <echo-component doc:name="Echo"/> <file:outbound-endpoint path="${outputfolder}" outputPattern="#[flowVars['Filename']]-icb.csv" connector-ref="output" doc:name="File"/> </processor-chain> <processor-chain> <jdbc:outbound-endpoint exchange-pattern="request-response" queryKey="readickb" connector-ref="db_conn" doc:name="DB100-ickr"/> <expression-filter expression="payload.size() > 0" doc:name="not empty"/> <json:object-to-json-transformer doc:name="Object to JSON"/> <component class="Bean2CSVnotfirstline" doc:name="Java"/> <echo-component doc:name="Echo"/> <file:outbound-endpoint path="${outputfolder}" outputPattern="#[flowVars['Filename']]-icb.csv" connector-ref="output" doc:name="File"/> </processor-chain> <processor-chain> <jdbc:outbound-endpoint exchange-pattern="request-response" queryKey="readiclr" connector-ref="db_conn" doc:name="DB100-ickr"/> <expression-filter expression="payload.size() > 0" doc:name="not empty"/> <json:object-to-json-transformer doc:name="Object to JSON"/> <component class="Bean2CSV" doc:name="Java"/> <echo-component doc:name="Echo"/> <file:outbound-endpoint path="${outputfolder}" outputPattern="#[flowVars['Filename']]-icr.csv" connector-ref="output" doc:name="File"/> </processor-chain> <processor-chain> <jdbc:outbound-endpoint exchange-pattern="request-response" queryKey="readickr" connector-ref="db_conn" doc:name="DB100-ickr"/> <expression-filter expression="payload.size() > 0" doc:name="not empty"/> <json:object-to-json-transformer doc:name="Object to JSON"/> <component class="Bean2CSVnotfirstline" doc:name="Java"/> <echo-component doc:name="Echo"/> <file:outbound-endpoint path="${outputfolder}" outputPattern="#[flowVars['Filename']]-icr.csv" connector-ref="output" doc:name="File"/> </processor-chain> </all> <set-payload value="Nu är 100 tankat till #[flowVars['Filename']] " doc:name="Set Payload"/> <http:response-builder doc:name="HTTP Response Builder"/> </flow>
-277622 0 To store a photo in AD, you can use the jpegPhoto attribute (see formal description in MSDN). Here is a way to do it using VBScript, and here's one to do it using VB.NET.
I'm not sure Outlook 2007 makes use of this value (my guess is - it does not), but it's worth a try. My guess is even that Outlook does not care about the jpegPhoto if you put someone from the GAL to your personal address book. Anyway, this should be easy enough to test.
If all else fails, you are stuck with either making clear that it doesn't work or building a custom form that reads the value.
-24365117 0Using this simple method, I was able to call stored procedures in MVC application
public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText, SqlParameter[] commandParameters) { using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); using (SqlCommand command = new SqlCommand()) { command.Connection = connection; command.CommandTimeout = 0; command.CommandType = commandType; command.CommandText = commandText; if (commandParameters != null && commandParameters.Length > 0) command.Parameters.AddRange(commandParameters); return FillData(command, connection); } } }
-32504135 0 So this is how sourcemaps work in Gulp: Each element you select via gulp.src gets transferred into a virtual file object, consisting of the contents in a Buffer, as well as the original file name. Those are piped through your stream, where the contents get transformed.
If you add sourcemaps, you add one more property to those virtual file objects, namely the sourcemap. With each transformation, the sourcemap gets also transformed. So, if you initialize the sourcemaps after concat and before uglify, the sourcemaps stores the transformations from that particular step. The sourcemap "thinks" that the original files are the output from concat, and the only transformation step that took place is the uglify step. So when you open them in your browser, nothing will match.
It's better that you place sourcemaps directly after globbing, and save them directly before saving your results. Gulp sourcemaps will interpolate between transformations, so that you keep track of every change that happened. The original source files will be the ones you selected, and the sourcemap will track back to those origins.
This is your stream:
return gulp.src(sourceFiles) .pipe(sourcemaps.init()) .pipe(plumber()) .pipe(concat(filenameRoot + '.js')) .pipe(gulp.dest(destinationFolder)) // save .js .pipe(uglify({ preserveComments: 'license' })) .pipe(rename({ extname: '.min.js' })) .pipe(sourcemaps.write('maps')) .pipe(gulp.dest(destinationFolder)) // save .min.js sourcemaps.write does not actually write sourcemaps, it just tells Gulp to materialize them into a physical file when you call gulp.dest.
The very same sourcemap plugin will be included in Gulp 4 natively: http://fettblog.eu/gulp-4-sourcemaps/ -- If you want to have more details on how sourcemaps work internally with Gulp, they are in Chapter 6 of my Gulp book: http://www.manning.com/baumgartner
-13903732 0There are multiple issues that should be looked at:
@Async, for instance. Then your transaction is not beholden to network connectivity or browser/HTTP timeouts.At the end of the day, ORMs will always be slower than base SQL. Consider swtiching over to base SQL, maybe concatenating SQL statements so that you have fewer database trips, or using a stored proc, passing bactches of data to the proc and have it run the inserts.
-32066647 0I tried replacing the path of the input and output by one without any space and it now works ! Here is the code I ended up using :
using Ghostscript.NET.Rasterizer; private void button6_Click(object sender, EventArgs e) { int desired_x_dpi = 96; int desired_y_dpi = 96; string inputPdfPath = @"D:\Public\temp\rasterizer\FOS.pdf"; string outputPath = @"D:\Public\temp\rasterizer\output\"; using (var rasterizer = new GhostscriptRasterizer()) { rasterizer.Open(inputPdfPath); for (var pageNumber = 1; pageNumber <= rasterizer.PageCount; pageNumber++) { var pageFilePath = Path.Combine(outputPath, string.Format("Page-{0}.png", pageNumber)); var img = rasterizer.GetPage(desired_x_dpi, desired_y_dpi, pageNumber); img.Save(pageFilePath + "ImageFormat.Png"); } } }
-23492287 0 Problems with upgrading Jekyll I want to upgrade Jekyll to 1.5.1 in order to get some of the latest features, but I'm running into some trouble.
My current version is 1.2.1 and which jekyll returns /usr/bin/jekyll. Rubygems is at 2.2.2. I'm on OSX 10.9.2.
When I simply run gem update jekyll it tells me that there is nothing to update. When I run gem uninstall jekyll it returns nothing, even with -V on. which jekyll keeps pointing at usr/bin/jekyll and gem install -v 1.5.1 then gives me compile errors, I guess because there is still an old copy of Jekyll installed.
The following is the output of gem list:
*** LOCAL GEMS *** actionmailer (4.0.0, 3.2.12) actionpack (4.0.0, 3.2.12) activeadmin (0.6.0) activemodel (4.0.0, 3.2.12) activerecord (4.0.0, 3.2.12) activerecord-deprecated_finders (1.0.3) activeresource (3.2.12) activesupport (4.0.0, 3.2.12) arbre (1.0.1) archive-tar-minitar (0.5.2) arel (4.0.1, 3.0.2) atomic (1.1.14) bcrypt-ruby (3.0.1) bourbon (3.1.8) builder (3.1.4, 3.0.4) bundler (1.3.5) CFPropertyList (2.2.0) coffee-rails (4.0.1, 3.2.2) coffee-script (2.2.0) coffee-script-source (1.6.3, 1.6.2) commander (4.1.5) country-select (1.1.1) devise (2.2.4) erubis (2.7.0) execjs (2.0.2, 1.4.0) faraday (0.8.7) fastercsv (1.5.5) fb-channel-file (0.0.2) formtastic (2.2.1) has_scope (0.5.1) hashie (2.0.5) highline (1.6.20) hike (1.2.3) httpauth (0.2.0) httpclient (2.3.4.1) i18n (0.6.5, 0.6.4) inherited_resources (1.4.0) jbuilder (1.5.2) journey (1.0.4) jquery-rails (3.0.4, 3.0.1, 2.3.0) json (1.8.1, 1.8.0) jwt (0.1.8) kaminari (0.14.1) kgio (2.8.1, 2.8.0) libxml-ruby (2.6.0) liquid (2.5.5) mail (2.5.4, 2.4.4) meta_search (1.1.3) mime-types (1.25, 1.24, 1.23) minitest (4.7.5) multi_json (1.8.2, 1.7.9, 1.7.7, 1.7.6) multipart-post (1.2.0) net-ssh (2.7.0) net-ssh-gateway (1.2.0) net-ssh-multi (1.2.0) newrelic_rpm (3.6.8.168) nokogiri (1.5.10, 1.5.6) oauth2 (0.8.1) omniauth (1.1.4) omniauth-facebook (1.4.1) omniauth-oauth2 (1.1.1) open4 (1.3.0) orm_adapter (0.4.0) pg (0.17.0, 0.14.1) polyamorous (0.5.0) polyglot (0.3.3) rack (1.5.2, 1.4.5) rack-cache (1.2) rack-ssl (1.3.3) rack-test (0.6.2) rails (4.0.0, 3.2.12) rails_12factor (0.0.2) rails_serve_static_assets (0.0.1) rails_stdout_logging (0.0.3) railties (4.0.0, 3.2.12) raindrops (0.12.0, 0.11.0) rake (10.1.0, 10.0.4) rdoc (3.12.2) responders (0.9.3) rhc (1.15.6) rubygems-update (2.2.2) sass (3.2.12, 3.2.10, 3.2.9) sass-rails (4.0.1, 3.2.6) sdoc (0.3.20) sitemap_generator (4.3.1) sprockets (2.10.0, 2.2.2) sprockets-rails (2.0.1) sqlite3 (1.3.8, 1.3.7) thor (0.18.1) thread_safe (0.1.3) tilt (1.4.1) treetop (1.4.15, 1.4.14) turbolinks (1.3.0) tzinfo (0.3.38, 0.3.37) uglifier (2.3.0, 2.1.2, 2.1.1) unicorn (4.6.3, 4.6.2) warden (1.2.1) This is the error I get when trying to run sudo gem install jekyll after deleting /usr/bin/jekyll:
Building native extensions. This could take a while... /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby extconf.rb creating Makefile make "DESTDIR=" clean make "DESTDIR=" compiling porter.c porter.c:359:27: warning: '&&' within '||' [-Wlogical-op-parentheses] if (a > 1 || a == 1 && !cvc(z, z->k - 1)) z->k--; ~~ ~~~~~~~^~~~~~~~~~~~~~~~~~~~ porter.c:359:27: note: place parentheses around the '&&' expression to silence this warning if (a > 1 || a == 1 && !cvc(z, z->k - 1)) z->k--; ^ ( ) 1 warning generated. compiling porter_wrap.c linking shared-object stemmer.bundle clang: error: unknown argument: '-multiply_definedsuppress' [-Wunused-command-line-argument-hard-error-in-future] clang: note: this will be a hard error (cannot be downgraded to a warning) in the future make: *** [stemmer.bundle] Error 1 ERROR: Error installing jekyll: ERROR: Failed to build gem native extension. Any ideas?
-32600403 0Pass that particular id in your remote url like remote: "../admin/checkEmail.php?data=email&id=23" say your particular id be 23
and in your checkEmail.php you can write query like
"SELECT email FROM table_name WHERE email='".$_GET['email']."' AND id!='".$_GET['id']."'" same way you can do for username also
-16811250 0Before you do a git push you have to do a git pull. Other person's work has to be merged with your code first and then you can push your changes to the repository. git pull will keep your updated code as it is and only add/update code (meaning that git will merge code) from the last commit (other person's code).
In case where both of the developers have worked on the same piece of code then git will show conflicts which have to be resolved first.
-36760435 0I have started messenger development 2 days ago.I was able to access localhost from any where over internet by using ngrok http://ngrok.com give it a try .
-29800942 0query is empty because you are checking
`if (isset($_POST['EntryId1']))` instead of `if (isset($_POST['search']) && $_POST['search']=='EntryId1')` and switch case would be b`enter code here`etter in this scenario.
-577809 0 Is the layout of structs defined by the C++ standard? I would suppose that it is compiler dependent.
-22339059 0When you update the div, for instance:
$("selector for the div").html("the updated markup"); ...the next line of code doesn't run until the div has been updated. At that point, the DOM updates have been completed. Normally that's good enough. If you want to be sure that those updates have been rendered (shown to the user), you can yield back to the browser using setTimeout, like this:
// ...do the updates... setTimeout(function() { // They've almost certainly been rendered. }, 0); The delay won't be 0ms, but it'll be very brief. That gives the browser a moment to repaint (if it needs it, which varies by browser).
-28494181 0This is probably related to a known issue in ui-router since angular 1.3.4 or so. See here for workarounds: https://github.com/angular-ui/ui-router/issues/600
I also had this issue, and could fix it by using the other version of .otherwise which takes a function:
replace:
$urlRouterProvider.otherwise("/home"); with:
$urlRouterProvider.otherwise( function($injector, $location) { var $state = $injector.get("$state"); $state.go("home"); });
-38734065 0 brew install automake Than you can use aclocal
-9466009 0Something like this (tested in Octave):
x = [1 3 7]; max(abs(x - [x(2:end) x(1)]))
-22506713 0 A jQuery selector will never return null, so you have recursion until the stack overflows. Try this instead:
if (selector.next().length) {
-14813321 0 That is because the latand lng are sub keys of each item in the array:
"geometry" : { "location" : { "lat" : -33.8698080, "lng" : 151.1971550 } } Thus you must retreive the full path:
location.latitude = [[dico valueForKeyPath:@"geometry.location.lat"] doubleValue]; location.longitude = [[dico valueForKeyPath:@"geometry.location.lng"] doubleValue];
-23523793 0 Unzip your sdk zip somewhere, copy entire contents of tools directory, replace it with your actual sdk tools folder contents.
Restart eclipse if required.
-8070712 0Magento-Debug to navigate Magento's modules and layouts: https://github.com/madalinoprea/magneto-debug
-22971679 0What about using
if(ddlCountry.SelectedIndex != 0)
-7305324 0 This is very slow & incorrect way to create string from seq of characters. The main problem, that changes aren't propagated - ref creates new reference to existing string, but after it exits from function, reference is destroyed.
The correct way to do this is:
(apply str seq) for example,
user=> (apply str [\1 \2 \3 \4]) "1234" If you want to make it more effective, then you can use Java's StringBuilder to collect all data in string. (Strings in Java are also immutable)
-37745709 0X509EncodedKeySpec(key) or PKCS8EncodedKeySpec(key) constructors take private/public keys in encoded format. Unencoded key bytes can be converted this way:
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("secp192r1"); ECPrivateKeySpec ecPrivateKeySpec = new ECPrivateKeySpec(new BigInteger(1, privateKeyBytes), spec); ECNamedCurveSpec params = new ECNamedCurveSpec("secp192r1", spec.getCurve(), spec.getG(), spec.getN()); java.security.spec.ECPoint w = new java.security.spec.ECPoint(new BigInteger(1, Arrays.copyOfRange(publicKeyBytes, 0, 24)), new BigInteger(1, Arrays.copyOfRange(publicKeyBytes, 24, 48))); PublicKey publicKey = factory.generatePublic(new java.security.spec.ECPublicKeySpec(w, params));
-32295700 0 SQLite uses a more general dynamic type system. Please look at the storage classes that must have each value stored in a SQLite database: https://www.sqlite.org/lang.html 1. onCreate
"CREATE TABLE" + SENSORS_TABLE_NAME + "(" + SENSORS_COLUMN_ID + "INTEGER PRIMARY KEY AUTO INCREMENT," +
look at: creat table --> column-def --> column-constraint AUTOINCREMENT is only one key-word
SENSORS_COLUMN_NAME + "STRING" + SENSORS_COLUMN_1 + "STRING," +
https://www.sqlite.org/datatype3.html There is no datatype STRING and also not, if you look at the affinity name examples. Take TEXT, or, if you wan't to give the length, VARCHAR(length)
SENSORS_COLUMN_2 + "FLOAT," + SENSORS_COLUMN_3 + "FLOAT," + SENSORS_COLUMN_4 + "FLOAT," +
"FLOAT" is all right and it converted into "REAL"
SENSORS_COLUMN_STATUS + "BOOLEAN)"
SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers 0 (false) and 1 (true).(1.1 Boolean Datatype) I think, your statement may be:
db.execSQL("CREATE TABLE" + SENSORS_TABLE_NAME + "(" + SENSORS_COLUMN_ID + "INTEGER PRIMARY KEY AUTOINCREMENT," + SENSORS_COLUMN_NAME + "TEXT" + SENSORS_COLUMN_1 + "TEXT," + SENSORS_COLUMN_2 + "FLOAT," + SENSORS_COLUMN_3 + "FLOAT," + SENSORS_COLUMN_4 + "FLOAT," + SENSORS_COLUMN_STATUS + "INTEGER )" ); "setVersion" and "setLocale" in onCreate I do not know if that's necessary. In the constructor you have giver the version 1: super(context, DATABASE_NAME, null, 1); Please look at reference/android/database/sqlite/SQLiteOpenHelper Better is to take a string for the version, becourse an upgrate was taken when you have a new version.
public static final int DB_VERSION = 1;
And than:
super(context, DATABASE_NAME, null, DB_VERSION);
-5597225 0 There are no C++ libraries for what you're trying to do (unless you're going to link with a half of Mozilla or WebKit), but you can consider using Java with HTMLUnit.
And for those suggesting regular expressions, an obligatory reference.
-38243599 1 Python openpyxl comment shape propertyI'm trying to set properties of comments (mainly the shape) in excel by openpyxl, but I cannot find examples. I'd like to set it with something like:
ws.cell(column = x, row = y).comment.NEEDED_METHOD_HERE = ... If you have good examples or any idea what is the exact method, please share it with me, thank you in advance!
-15410129 0id is a global field, just do this:
document.getElementById("lat").innerHTML = "31"; document.getElementById("lon").innerHTML = "71"; instead of what you have written.
-26153930 0 Can we assign an attribute name for a Class even that attribute is a column in a different table?Ok, here is my DB
Member Table memberID- Name -... 1 - Tom 2 - Mary ... Event table eventID - address 1 - 122NY... 2 - 23 Cali ... PaidMember table orderNumber - eventID - memberID 1 - 1 - 2 1 - 1 - 3 ..
Note: each Event can have many members and each members can be in many event. However, only PaidMember is allowed to participate an event.
SO, here is how I design classes:
public class Member{ private String name; private int memberID; //all Set and Get methods here } public class Event{ private int eventID; private String address; //all set and get methods here } My question is that, can I put private int orderNumber into Member? but the orderNumber is depended on a particular event
public class Member{ private String name; private int memberID; private int orderNumber; //all Set and Get methods here } or should I create PaidMember class? I am thinking to do like this but not sure if it is ok
public class PaidMember{ private Member member; private Event event; private int orderNumber; //all Set and Get methods here }
-40706125 0 My navigate method doesn't work javafx I have program in javafx.
Its a note program and I have button switch to another scene but it doesn't work don't know why. When I click, I got a run time error, it was working well.
This is the main controller:
package notetakingapp; public class ListNotesUIController implements Initializable { @FXML private TableView<Note> tableView; @FXML private TableColumn<Note, String> titleColmun; @FXML private TableColumn<Note, String> descriptionColumn; @FXML private TextField searchNotes; @FXML private Label totalNotes; @Override public void initialize(URL url, ResourceBundle rb) { FilteredList<Note> filteredData = new FilteredList<>(data, n -> true); tableView.setItems(filteredData); totalNotes.setText("" + data.size() + " Notes"); titleColmun.setCellValueFactory(new PropertyValueFactory<>("title")); descriptionColumn.setCellValueFactory(new PropertyValueFactory<>("description")); searchNotes.setOnKeyReleased(e -> { filteredData.setPredicate(n -> { if (searchNotes.getText() == null || searchNotes.getText().isEmpty()) { return true; } return n.getTitle().contains(searchNotes.getText()) || n.getDescription().contains(searchNotes.getText()); }); }); } @FXML private void handleAddNewNoteAction(ActionEvent event) throws IOException { navigate(event, "AddEditUI.fxml"); totalNotes.setText("" + data.size() + " Notes"); } @FXML private void handleEditNotesAction(ActionEvent event) throws IOException { tempNote = tableView.getSelectionModel().getSelectedItem(); navigate(event, "AddEditUI.fxml"); } protected static ObservableList<Note> data = FXCollections.<Note>observableArrayList( new Note("Note 1", "Description of note 41"), new Note("Note 2", "Description of note 32"), new Note("Note 3", "Description of note 23"), new Note("Note 4", "Description of note 14")); protected static Note tempNote = null; protected void navigate(Event event, String FXMLDocName) throws IOException { Parent root = FXMLLoader.load(getClass().getResource(FXMLDocName)); Scene scene = new Scene(root); NoteTakingApp.appStage.setScene(scene); } @FXML private void handleDeleteAction(ActionEvent event) { int getIndex = tableView.getSelectionModel().getSelectedIndex(); data.remove(getIndex); totalNotes.setText("" + data.size() + " Notes"); } } This is the controller what I want to go:
package notetakingapp; public class AddEditUIController implements Initializable { @FXML private TextField noteTitle; @FXML private TextArea noteDescription; @FXML private Label noteTitleLabel; @FXML private Label noteDescriptionLabel; @Override public void initialize(URL url, ResourceBundle rb) { noteTitle.setText(tempNote.getTitle()); noteDescription.setText(tempNote.getDescription()); } @FXML private void handleCancleAction(ActionEvent event) throws IOException { navigate(event, "ListNotesUI.fxml"); } @FXML private void handleSaveAction(ActionEvent event) throws IOException { if ((noteTitle.getText().trim().isEmpty()) && noteDescription.getText().trim().isEmpty()) { noteTitleLabel.setTextFill(Color.BLUE); noteTitleLabel.setText(" * Note Title: (Required)"); noteDescriptionLabel.setTextFill(Color.BLUE); noteDescriptionLabel.setText(" * Note Description: (Required)"); } else { data.add(new Note(noteTitle.getText(), noteDescription.getText())); navigate(event, "ListNotesUI.fxml"); } } protected void navigate(Event event, String FXMLDocName) throws IOException { Parent root = FXMLLoader.load(getClass().getResource(FXMLDocName)); Scene scene = new Scene(root); NoteTakingApp.appStage.setScene(scene); } @FXML private void handleBackToNotesAction(ActionEvent event) throws IOException { navigate(event, "ListNotesUI.fxml"); } @FXML private void handleClearAction(ActionEvent event) { noteTitle.setText(""); noteDescription.setText(""); } } and this is my start method:
static Stage appStage = new Stage(); @Override public void start(Stage stage) throws Exception { appStage = stage; Parent root = FXMLLoader.load(getClass().getResource("ListNotesUI.fxml")); Scene scene = new Scene(root); appStage.setScene(scene); appStage.setResizable(false); appStage.setTitle("P'Note-Taking Application v1.0"); appStage.show(); }
-9888669 0 $this->html = preg_replace('~//\s*?<!\[CDATA\[\s*|\s*//\]\]>~', '', $this->html); should work but haven't really tested it.
-21270 0The easiest way is to simply select both fields by selecting the first field, and then while holding down the Ctrl key selecting the second field. Then clicking the key icon to set them both as the primary key.
-7136921 1 How can I create a tuple where each of the members are compared by an expression?Well, here is the thing:
I have the following Haskell code, this one:
[ (a, b, c) | c <- [1..10], b <- [1..10], a <- [1..10], a ^ 2 + b ^ 2 == c ^ 2 ] Which will returns
[(4,3,5),(3,4,5),(8,6,10),(6,8,10)] For those who aren't familiar with this, I'll explain:
tuple (a,b,c), where each of these "definitions" (a,b,c) receive a list (1 up to 10) and his members are compared by the a ^ 2 + b ^ 2 == c ^ 2 ? expression (each member).How can I do the same (one line if possible) in Python/Ruby?
P.S.: they are compared in lexicographical order.
-38101257 0 Angular 2 how to remove pasted content from inputI'm trying to do some stuff with a pasted string, which works, but when I try to remove the content I can't seem to do it since the pasted content isn't getting bound to the model of the input.
How can you clear the input of the pasted content?
I tried binding the content to the model and then removing the model but that will still leave the actual pasted content in the event object so it's not a solution.
Also tried clearing the input directly using input.value = '' but without luck.
Markup:
<input #input [(ngModel)]="newTag[labelKey]" (paste)="onPaste($event)"> Function:
onPaste(e: any) { let content = e.clipboardData.getData('text/plain'); // Do stuff // Then clear pasted content from the input }
-21003773 0 Well SOAP uses XML as its data format. Not JSON. I would imagine that the issue is that you are getting XML back from the service and the "special characters" you're referring to are coming from that.
-649377 0Here is the full list of overloadable operators from MSDN.
--- EDIT ---
In response to your comment, I believe what you want is here. Search for Table 6-1.
-27305831 0I know this is a late answer, but if you can always use sanitize-html It's written for node, but pretty sure you could run browserify against the library (or your code for that matter).
Note, it uses lodash, so if you are already using it, then you may want to adjust the package.
This example is more than you're looking for... I use this library in order to cleanup input code, converting to markdown for storage in the db from here, I re-hydrate via marked.
// convert/html-to-filtered-markdown.js 'use strict'; var sanitize = require('sanitize-html') //https://www.npmjs.org/package/sanitize-html ,toMarkdown = require('to-markdown').toMarkdown ; module.exports = function convertHtmlToFilteredMarkdown(input, options) { if (!input) return ''; options = options || {}; //basic cleanup, normalize line endings, normalize/reduce whitespace and extra line endings var response = (input || '').toString().trim() .replace(/(\r\n|\r|\n)/g, '\n') //normalize line endings .replace(/“/g, '"') //remove fancy quotes .replace(/”/g, '"') //remove fancy quotes .replace(/‘/g, '\'') //remove fancy quotes .replace(/’/g, '\'') //remove fancy quotes ; //sanitize html input response = sanitize(response, { //don't allow table elements allowedTags: [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul', 'ol', 'nl', 'li', 'b', 'i', 'strong', 'em', 'strike', 'code', 'hr', 'br', 'div', 'table', 'thead', 'caption', 'tbody', 'tr', 'th', 'td', 'pre' ], //make orderd lists transformTags: { 'ol': 'ul' } }).replace(/\r\n|\r|\n/g,'\n') //normalize line endings; if (!options.tables) { response = response.replace(/[\s\n]*\<(\/?)(table|thead|tbody|tr|th|td)\>[\s\n]*/g, '\n\n') //replace divs/tables blocks as paragraphs } //cleanup input further response = response .replace(/[\s\n]*\<(\/?)(div|p)\>[\s\n]*/g, '\n\n') //divs and p's to simple multi-line expressions .replace(/\>#/g, '\n\n#') //cleanup #'s' after closing tag, ex: <a>...</a>\n\n# will be reduced via sanitizer .replace(/\\s+\</,'<') //remove space before a tag open .replace(/\>\s+\n?/,'>\n') //remove space after a tag close .replace(/\&?nbsp\;?/g,' ') //revert nbsp to space .replace(/\<\h[12]/g,'<h3').replace(/\<\/\h[12]/g,'</h3') //reduce h1/h2 to h3 ; //convert response to markdown response = toMarkdown(response); //normalize line endings response = response .replace(/(?:^|\n)##?[\b\s]/g,'\n### ') //reduce h1 and h2 to h3 .replace(/(\r\n|\r|\n)/g, '\n') //normalize line endings .trim() return response + '\n'; }
-13508149 0 Where to Async in PagerAdatper My fragment activity used this adapter to display all the result in a listview. The page will have a title tab and each tab will have the list result.
Now the list result I read from internal storage and each time I swipe to next page it will have slight lag or delay, so I am thinking implementing ASYNCTask inside this pageradapter so the experience will be better but I have no idea where to implement. Could you guys point me out??
public class ViewPagerAdapter extends PagerAdapter { public ViewPagerAdapter( Context context ) { //This is where i get my title for (HashMap<String, String> channels : allchannel){ String title = channels.get(KEY_TITLE); titles[acc] = title; acc++; } scrollPosition = new int[titles.length]; for ( int i = 0; i < titles.length; i++ ) { scrollPosition[i] = 0; } } @Override public String getPageTitle( int position ) { return titles[position]; } @Override public int getCount() { return titles.length; } @Override public Object instantiateItem( View pager, final int position ) { String filename = null; ListView v = new ListView( context ); final ArrayList<HashMap<String, String>> items = new ArrayList<HashMap<String, String>>(); DatabaseHandler db = new DatabaseHandler(context); filename = openFile("PAGE1"); //OpenFile function is read file from internal storage switch(position){ case 0: filename = openFile("PAGE1"); break; case 1: filename = openFile("PAGE2"); break; case 2: filename = openFile("PAGE3"); break; } try{ //Use json to read internal storage file(Page1/Page2) and display all the result on the list } }catch(Exception e){ } ListAdapter listadapter=new ListAdapter(context, items); v.setAdapter( listadapter ); ((ViewPager)pager ).addView( v, 0 ); return v; } @Override public void destroyItem( View pager, int position, Object view ) { ( (ViewPager) pager ).removeView( (ListView) view ); } @Override public boolean isViewFromObject( View view, Object object ) { return view.equals( object ); } @Override public void finishUpdate( View view ) { } @Override public void restoreState( Parcelable p, ClassLoader c ) { if ( p instanceof ScrollState ) { scrollPosition = ( (ScrollState) p ).getScrollPos(); } } @Override public Parcelable saveState() { return new ScrollState( scrollPosition ); } @Override public void startUpdate( View view ) { } }
-1561112 0You can use this (C#) code example. It returns a value indicating the compression type:
1: no compression
2: CCITT Group 3
3: Facsimile-compatible CCITT Group 3
4: CCITT Group 4 (T.6)
5: LZW
public static int GetCompressionType(Image image) { int compressionTagIndex = Array.IndexOf(image.PropertyIdList, 0x103); PropertyItem compressionTag = image.PropertyItems[compressionTagIndex]; return BitConverter.ToInt16(compressionTag.Value, 0); }
-34649826 0 You probably want something like this:
.factory('countries', function($http){ var list = []; $http.get('../test.json').success(function(data, status, headers) { angular.copy(data, list); }) return { list: list } }; Then you can bind to the list like this:
.controller('View2Ctrl', function ($scope, countries){ $scope.countries = countries.list; }); An alternative, equally valid approach is this:
.factory('countries', function($http){ return { list: function() { return $http.get('../test.json'); } } }; Then in your controller:
.controller('View2Ctrl', function ($scope, countries){ $scope.countries = []; countries.list().success(function(data) { $scope.countries = data; }); }); Remember that $http.get('../test.json') is already a promise, which is why you can return it without any unnecessary promise/resolve handling.
I figured out that Jitsi and CSipSimple send their INTERNET IP-address instead of sending their VPN IP-address in SDP during INVITE request Altghough CSipSimple has the parameter "Allow SDP NAT rewrite" in Expert mode of account setup. And it should be ticked to avoid this problem. But Jitsi does not have such option
-37253636 0If you are using any IDE for developing Apps then always run that App in sudo mode . for eg . If you are using webstorm then always run it's webstorm.sh in file as follows.
-5610550 0sudo bash /opt/webstorm/bin/webstorm.sh
Search the Sqlalchemy documentation for enabling the logging of the generatef d SQL statements and Sql responses. This will usually give you all related information for further debugging.
-9508116 0 Regex for String with possible escape charactersI had asked this question some times back here Regular expression that does not contain quote but can contain escaped quote and got the response, but somehow i am not able to make it work in Java.
Basically i need to write a regular expression that matches a valid string beginning and ending with quotes, and can have quotes in between provided they are escaped.
In the below code, i essentially want to match all the three strings and print true, but cannot.
What should be the correct regex?
Thanks
public static void main(String[] args) { String[] arr = new String[] { "\"tuco\"", "\"tuco \" ABC\"", "\"tuco \" ABC \" DEF\"" }; Pattern pattern = Pattern.compile("\"(?:[^\"\\\\]+|\\\\.)*\""); for (String str : arr) { Matcher matcher = pattern.matcher(str); System.out.println(matcher.matches()); } }
-40977930 0 As furas suggested in his comment, you could store the counter in the session or perhaps a database. You could also store it as a hidden input field on the form.
In your template:
<input type="hidden" name="counter" value="{{ counter }}"> In your view:
counter = request.form.get('counter', type=int) or 0 return render_template('accounts/test/medium.html', word=word, output=scribble_normalized, counter=counter+1)
-14601496 0 How to get Media controls in Webview in android? I am having Webview in android & currently playing youtube video from the Url. top of the webview, there is an actionbar. I want actionbar to be hidden when video is playing & actionbar to show when video is onPause. is there any way to get the current state of video playing inside the webview. or I can call mediaControls class in webview. Here is my code for webview:
mVideoView.getSettings().setJavaScriptEnabled(true); mVideoView.getSettings().setPluginsEnabled(true); mVideoView.getSettings().setAllowFileAccess(true); mVideoView.setWebChromeClient(new ChromeClient()); mVideoView.setWebViewClient(webViewClient); mVideoView.loadUrl("http://www.youtube.com/embed/" + video_id);
-38616639 0 Redirect back with changeset i'm working with programming phoenix book examples more specific:
def create(conn, %{"user" => user_params}) do changeset = User.registration_changeset(%User{}, user_params) case Repo.insert(changeset) do {:ok, user} -> conn |> put_flash(:info, "#{user.username} created!") |> redirect(to: user_path(conn, :index)) {:error, changeset} -> render(conn, "new.html", changeset: changeset) end end when the form has errors instead of using render(conn, "new.html", changeset: changeset)
i want to redirect back with changeset the following code works:
{:error, changeset} -> conn |> put_flash(:error, "Error") |> redirect(to: user_path(conn, :new)) but it doesn't contains the changeset which is important i think.Another thing is that instead of render users/new it renders users route.
Any ideas?
-40464837 0 How to use addFormatters in WebMvcConfigurerAdapter@Configuration @EnableWebMvc // <mvc:annotation-driven /> public class WebApplicationConfig extends WebMvcConfigurerAdapter { @Override public void addFormatters(FormatterRegistry registry) { registry.addConverter(new EmailConverter()); } } I add a Converter in FormatterRegistry,but I don't know how to use it, can someone help me out?
Assuming Test is a Controller and Page is an Action
RouteTable.Routes.Add(new Route { Url = "[controller]/[action]/[id]" Defaults = new { action = "Index", id (string) null }, RouteHandler = typeof(MvcRouteHandler) }); but routing is very much context dependent. You need to look into your other routes and ensure that this route is placed in the right order.
-24441734 0please see fiddle
http://fiddle.jshell.net/RrD74/
html:
<select id="mySelect"> <option name="xxx" value="1">text opt 1</option> <option name="xxx" value="2">text opt 2</option> <option name="xxx" value="3">text opt 3</option> </select> js:
$(function () { $("#mySelect").change(function () { alert($("#mySelect option:selected").text()); }); });
-1114690 0 How to get user input in Clojure? I'm currently learning clojure, but I was wondering how to get and store user input in a clojure program. I was looking at the clojure api and I found a function called read-line, however I'm not sure how to use it if it's the right function to use...
Anyhow, how do you get user input in clojure ?
-20281787 0The <style> ... </style> belongs in the <head></head>, not in <body> tag
First, find the hash you want to your submodule to reference. then run
~/supery/subby $ git co hashpointerhere ~/supery/subby $ cd ../ ~/supery $ git add subby ~/supery $ git commit -m 'updated subby reference' that has worked for me to get my submodule to the correct hash reference and continue on with my work without getting any further conflicts.
-34425307 0 Finding label-value pairs and capturing value JqueryI need to find values associated with labels that partly match a string. The block of source looks like this:
<dt> Loose Ones </dt> <dd> 8.00 </dd> <dt> Loose Fives </dt> <dd> 15.00 </dd> <dt> Envelope Ones </dt> <dd> 0.00 </dd> <dt> Envelope Fives </dt> 25.00 <dd> I want to find all labels that contain 'Loose' and capture the associated value then total it into a value. Jquery must have a way to do this.
-16399587 0 Remote post to webpage from windows serviceNOTE: This question has been edited what was originally asked
I'm developing a windows service that, daily, queries a web service for data, compares that to currently existing data and then posts it to the client's webpage.
The code for the remote post executes fine, but updates never happen on the client's web page...
Imports Microsoft.VisualBasic Imports System.Collections.Specialized Public Class RemotePost Public Property Inputs As New NameValueCollection() Public Property URL As String Public Property Method As String = "post" Public Property FormName As String = "_xclick" Public Sub Add(ByVal name As String, ByVal value As String) _Inputs.Add(name, value) End Sub Public Sub Post() Dim client as New WebClient() client.Headers.Add("Content-Type", "application/x-www-form-urlencoded") Dim responseArray = client.UploadValues(URL, Method, Inputs) End Sub End Class I believe the reason for this is that the post generated by the above code is different to what the form itself posts manually.
Here's an example of a post generated by the above code:
POST http://www.thisdomain.com/add-event/ HTTP/1.1 Content-Type: application/x-www-form-urlencoded Host: thisdomain.com Content-Length: 116 Expect: 100-continue Connection: Keep-Alive no_location=0&event_name=Cycle-Fix+MTB+Tour+-+3+Days+ABC&event_start_date=2013%2f04%2f06&location_state=Eastern+Cape And here's an example of a post generated on the page itself:
POST http://www.thisdomain.com/add-event/ HTTP/1.1 Host: thisdomain.com Connection: keep-alive Content-Length: 2844 Cache-Control: max-age=0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Origin: http://thisdomain.com User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31 Content-Type: multipart/form-data; boundary=----WebKitFormBoundary8u14QB8zBLGQeIwu Referer: http://thisdomain.com/add-event/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8 Accept-Charset: UTF-8,*;q=0.5 Cookie: wp-settings-1=m5%3Do%26editor%3Dtinymce%26libraryContent%3Dbrowse%26align%3Dleft%26urlbutton%3Dnone%26imgsize%3Dfull%26hidetb%3D1%26widgets_access%3Doff; wp-settings-time-1=1367827995; wordpress_test_cookie=WP+Cookie+check; wordpress_logged_in_8d8e9e110894b9cf877af3233b3a007b=admin%7C1368089227%7C69a33748ee5bbf638a315143aba81313; devicePixelRatio=1 ------WebKitFormBoundary8u14QB8zBLGQeIwu Content-Disposition: form-data; name="event_name" test event ------WebKitFormBoundary8u14QB8zBLGQeIwu Content-Disposition: form-data; name="event_start_date" 2013-05-07 ------WebKitFormBoundary8u14QB8zBLGQeIwu Content-Disposition: form-data; name="event_start_time" 01:00 AM ------WebKitFormBoundary8u14QB8zBLGQeIwu Content-Disposition: form-data; name="event_end_time" 02:15 AM ------WebKitFormBoundary8u14QB8zBLGQeIwu Content-Disposition: form-data; name="recurrence_freq" daily ------WebKitFormBoundary8u14QB8zBLGQeIwu Content-Disposition: form-data; name="recurrence_interval" ------WebKitFormBoundary8u14QB8zBLGQeIwu Content-Disposition: form-data; name="recurrence_byweekno" 1 ------WebKitFormBoundary8u14QB8zBLGQeIwu Content-Disposition: form-data; name="recurrence_byday" 0 ------WebKitFormBoundary8u14QB8zBLGQeIwu Content-Disposition: form-data; name="recurrence_days" 0 ------WebKitFormBoundary8u14QB8zBLGQeIwu Content-Disposition: form-data; name="location_latitude" 38.0333333 ------WebKitFormBoundary8u14QB8zBLGQeIwu Content-Disposition: form-data; name="location_longitude" -117.23333330000003 ------WebKitFormBoundary8u14QB8zBLGQeIwu Content-Disposition: form-data; name="location_name" test ------WebKitFormBoundary8u14QB8zBLGQeIwu Content-Disposition: form-data; name="location_address" test ------WebKitFormBoundary8u14QB8zBLGQeIwu Content-Disposition: form-data; name="location_town" test ------WebKitFormBoundary8u14QB8zBLGQeIwu Content-Disposition: form-data; name="location_state" Georgia Clearly there's a lot more happening with the form's post than is the case with mine. Unfortunately, I'm afraid I don't understand all of it.
I have the following concerns about these differences:
Can anyone explain what exactly the differences here are and how I can emulate the form's post as per my requirement?
-39022161 0 Ionic avoid gray-out items on hover...I have the next list of carss whose header is clickable so it can be toggled on and off. Nevertheless, whenever I click on one of them, it turns gray. I would like to change this behavior and keep color unchanged.
<div class="list"> <div ng-repeat="event in searchResultEvents"> <div class="card"> <div class="item item-avatar item-icon-right" ng-click="toggleEvent(event)"> <img src={{event.icon}}> <i class="icon" style="font-size: 18px;" ng-class="isEventShown(event) ? 'ion-chevron-up' : 'ion-chevron-down'" ng-style="{ background: backgroundForEvent(event), color: 'grey' }"></i> <h2><b>{{event.title}}</b></h2> <p><span>{{event.dayOfWeek}} {{event.dateTime.getDate()}}</span> - <span style="color:forestgreen">{{event.dateTime.toTimeString().substr(0,5)}}h</span></p> </div> <div class="item item-body" ng-hide="!isEventShown(event)"> <div> <p ng-bind-html="event.description | hrefToJS"></p> </div> <div> <br /> <div> <i class="icon ion-map balanced" style="font-size: 25px;"></i> <p ng-bind-html="event.place | hrefToJS" style="display:inline"></p> I have tried this:
Changing background color of Ionic list item on hover in CSS
But no luck. Perhaps this is not the CSS or I am not putting it where it belongs. I have tried adding it to ionic.app.scss (I am using SCSS instead of plain CSS).
I have made some SCSS changes on that file before and it seemed to work... what am I doing wrong now?.
Thanks in advance
-39217790 0Yes, you can using the flexible box model's order css property. Be aware that the parent element must have display:flex set
ul { display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -moz-flex; display: -webkit-flex; display: flex; -moz-flex-flow: wrap; -webkit-flex-flow: wrap; flex-flow: wrap; } ul li { width: 100% } ul li:nth-of-type(1) { order: 2; } ul li:nth-of-type(2) { order: 3; } ul li:nth-of-type(3) { order: 4; } ul li:nth-of-type(4) { order: 5; } ul li:nth-of-type(5) { order: 1; } <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> Also be aware that not all browsers support the flexible box model as outlined here...http://caniuse.com/#feat=flexbox
However, there are quite a few polyfills out there you can use to bring support for older browsers if you need to support older browsers
-7299400 0 Interpolate missing values in a MySQL tableI have some intraday stock data saved into a MySQL table which looks like this:
+----------+-------+ | tick | quote | +----------+-------+ | 08:00:10 | 5778 | | 08:00:11 | 5776 | | 08:00:12 | 5778 | | 08:00:13 | 5778 | | 08:00:14 | NULL | | 08:00:15 | NULL | | 08:00:16 | 5779 | | 08:00:17 | 5778 | | 08:00:18 | 5780 | | 08:00:19 | NULL | | 08:00:20 | 5781 | | 08:00:21 | 5779 | | 08:00:22 | 5779 | | 08:00:23 | 5779 | | 08:00:24 | 5778 | | 08:00:25 | 5779 | | 08:00:26 | 5777 | | 08:00:27 | NULL | | 08:00:28 | NULL | | 08:00:29 | 5776 | +----------+-------+ As you can see, there are some points where no data is available (quote is NULL). What I would like to do is a simple step interpolation. This means each NULL value should be updated with the last value available. The only way I managed to do this is with cursors, which is pretty slow due to the large amount of data. I'm basically searching something like this:
UPDATE table AS t1 SET quote = (SELECT quote FROM table AS t2 WHERE t2.tick < t1.tick AND t2.quote IS NOT NULL ORDER BY t2.tick DESC LIMIT 1) WHERE quote IS NULL Of course this query will not work, but this is how it should look like.
I would appreciate any ideas on how this can be solved without cursors and temp tables.
-15028375 0DS_RECURSE doesn't exist. It was a flag in a prerelease version of Windows 95 that was removed before RTM. All the docs that refer to it talk about "Don't use it", which is now very easy to do because you can't use something that doesn't exist.
See the setAutoresizingMask: method of NSView and the associated resizing masks.
-17491417 0 PrimeFaces PickList : two String fields filterI was wondering if it's possible to have a two fields filter with a picklist of primefaces. I tried this but it's not working. I would like to filter on firstname and name but they are in two different fields.
<p:pickList value="#{bean.usersDualModel}" var="user" itemValue="#{user}" itemLabel="#{user.firstname} #{user.name}" converter="user" showSourceFilter="true" showTargetFilter="true" filterMatchMode="contains" > <p:column> <h:outputText value="#{user.firstname} #{user.name}" /> </p:column> </p:pickList> Thanks
-6339367 0Thanks for the reply..
I got below command working to meet my scenario for now.. but trying to see if there is any direct command to find the latest ID of a file on remote server...
git log 'branch-name' -- 'file-name'
which displaying log messages with ID, Author and Date.. I am fetching the top first line with unix pipe head command.
-36755909 0git log 'branch-name' -- 'file-name' | head -1
Just from what you have provided, I can't tell you why it won't work. I do not have a screensaver to test that with (that I know of). But I'm able to do all four of these with Notepad opening a text file:
Separate ProcessStartInfo
ProcessStartInfo procInfo = new ProcessStartInfo("notepad.exe", "c:\\test.txt"); Process proc = Process.Start(procInfo); proc.WaitForExit(); Separate ProcessStartInfo with Properties
ProcessStartInfo procInfo = new ProcessStartInfo(); procInfo.Arguments = "c:\\test.txt"; procInfo.FileName = "notepad.exe"; Process proc = Process.Start(procInfo); proc.WaitForExit(); Inline ProcessStartInfo
Process proc = Process.Start(new ProcessStartInfo("notepad.exe", "c:\\test.txt")); proc.WaitForExit(); No PSI, Just Process
Process proc = Process.Start("notepad.exe", "c:\\test.txt"); proc.WaitForExit(); You may want to go with the first one so that you can breakpoint on the "Process proc..." line and examine the properties of procInfo. The Arguments property should show the 2nd value (in my case, c:\\test.txt), and the FileName property should be the path to what you are executing (mine is notepad.exe).
EDIT: I added the separate one with properties so you can really see explicit setting.
I have worked out an example using the 3D Text screensaver:
string scrPath = @"C:\Windows\System32\ssText3d.scr"; ProcessStartInfo procInfo = new ProcessStartInfo(); procInfo.FileName = scrPath; procInfo.Verb = "config"; procInfo.UseShellExecute = false; Process proc = Process.Start(procInfo); proc.WaitForExit(); I didn't use the Arguments. Instead, I used the Verb. This requires UseShellExecute to be set to false. I got the expected configuration dialog instead of the screensaver running.
More About Verbs
This is where the verbs are for screen savers. 
You can also define custom verbs: Register an Application to Handle Arbitrary File Types
-8066121 0 Guid in Querystring is being transformed somehowI am not sure why this is occuring but here are a few details that may help to find a solution:
This is the line in PageModify.aspx building the query string:
Response.Redirect(string.Format("Editor.aspx?id={0}", pageId, CultureInfo.CurrentCulture)); This is the output of the query string when all goes correctly:
https://example.com/Editor.aspx?id=1dfz342b-3a4d-4255-8054-93916324afs6 This is what is viewed in the browser when redirected to Editor.aspx:
https://example.com/Editor.aspx?id=1dfz342b-3a4d-xxxxxxxxxxxxxxx324afs6 Of course we get an invalid guid error when this line runs:
_PageEditId= new Guid(Request.QueryString["id"]); Has anyone seen this? Could it be IIS settings? Nothing special is being done here and everyone's systems has the same baseline. It occurs to inside and outside customers.
-22285610 0 Trouble making css :last-child work for meObviously I must be doing something wrong, but I can't figure out what's wrong with this, it's driving me crazy.
The selector I'd LIKE to use is: .menu ul li:last-child > a
The 'unique selector' that firefox gives me is .menu > ul:nth-child(1) > li:nth-child(5) > a:nth-child(1)
the HTML is:
<div class='menu'> <ul><li><a href=''>Home</a></li> <li><a href='1'>Link 1</a></li> <li><a href='2'>Link 2</a></li> <li><a href='3'>Link 3</a></li> <li><a href='4'>Link 4</a></li> <ul> </div> How is li:last-child > a not selecting 'Link 4'? I am really quite confused, so thanks in advance for the upcoming lesson.
I have a Formtype. In this Formtype I get over the options-Array in the buildForm function a key additionalName. I want to add this value to the FormType Name (in Symfony3 BlockPrefix). But how can I set this?
class AdultType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $additionalName = $options['additionalName']; $builder ->add('account', TextType::class,array( 'label' => 'account', 'required' => false, )) ; } /** * @param OptionsResolver $resolver */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'My\Bundle\WebsiteBundle\Model\Adult', 'csrf_protection' => true, 'cascade_validation' => true, 'name' => "" )); } /** * @return string */ public function getBlockPrefix() { //Here I need the $options['additionalName'] return 'my_bundle_websitebundle_adult_'.$options['additionalName']; } I tried allready to set a variable private $additionalName; on the top of the class, set it in the buildForm function and get access to it with $this->additionalName in the getBlockPrefix Function. But the value in getBlockPrefix is empty. SO I think the getBlockPrefix is called before the buildForm.
The Type is beeing called from another form:
$builder->add('adult', AdultType::class, array( 'additionalName' => $options['name'] )); Thanks for any help!
-26536986 0p = 0.0000000000000000000001 s = str(p) print(format(p, "." + s.split("e")[-1][1:]+"f")) if "e" in s else print(p)
-27966745 0 backtrack on virtualbox not getting ip address i am trying to use backtrack5 on my virtualbox and set my adapter to bridged so that backtrack can have connection to the internet. But its not getting an ip even though its requesting for one when ever it boots. I read on other forums that some dhcp servers are configured not to give more than one ip to one mac addrees.so I used ipconfig / release to release the host ip so that my guest can obtain an ip but still its not working.when I set the adapter to NAT, it picks up an IP address from VB no problem but that does not connect me to the internet. Can anybody help me?
-24844161 0The unspecified behavior is not for the programmer to use (for the contrary if, for the programmer to known what it need to look with care and avoid), the unspecified behavior, as all the others: undefined, implementation defined, etc... are for the compiler writer to take advantage of (for example Order of evaluation of subexpressions have unspecified behavior, for that you should not pass any subexpression with side-effects in the evaluations, and assuming that you take care of this, the compiler reorder the evaluation of subexpression as more efficient it can, some subexpression can contain same calculation that can be reused and many other optimization can take advantage of the knowledge that can do evaluated in the best order it can find.
-10207317 0 Set the Read-only property of a FileI am trying to set the read-only property of a File, but it doesn't seem to work. Could someone please help me to understand why.
Here is my code...
public class Main { public static void main(String[] args) { File f = new File("c:/ulala.txt"); if (!f.setReadOnly()) { System.out.println("Grrr! Can't set file read-only."); return; } } }
-33620015 0 Replace your jquery code with code below as you are creating the anchor tags with ajax and for the code those does not exists so just load the anchor click event inside success function of your ajax call and it will work :
$(function() { $.ajax({ url: "http://linktoapi&callback=myMethod", timeout: 2000, jsonpCallback: "myMethod", jsonp: false, dataType: "jsonp", success: function(data) { var newContent = ''; for (var i = 0; i < data.listing.length; i++) { newContent += '<p class="property-details">' + '<a href="' + data.listing[i].listing_id + '">' + data.listing[i].displayable_address + '</a></p>'; } $('#content').html(newContent).hide().fadeIn(400); $('.property-details a').on('click', function(e) { e.preventDefault(); $('#content').html("test").hide().fadeIn(400); }); }, error: function() { $content.html('<div class="container">Please try again soon.</div>'); } }); });
-22602656 0 I think you have started multiple thread on the same object
you should use synchronized block to run thread-safe code,
synchronized(this){ long currentTime = System.nanoTime(); long targetFPS = 1000; long delta; while(GameConstants.running) { delta = System.nanoTime() - currentTime; if(delta/1000000000 >= 1) { System.out.println(delta); currentTime = System.nanoTime(); } } } After Updating Source Code
Yeah! here, you are calling run() method and start both...
game.start(); game.run(); remove calling run method explicitly, you will get desired result :)
-39103868 0 Xamarin iOS project need suggestionI am developing a survey app using Xamarin and Mvvmcross. Can some one help with suggesting a way to build a View to display questionnaire. These questionnaire will be supplying from my View Model as a List of question with Question Text, Answer options. Based on a flag I need to prompt the questionnaire with input type as drop down or Text boxes. Number of questions can be vary.
In Android I achieved it using MvxGridView and Layout templates. But not sure how to do it in iOS.
-36908911 0You could bootstrap asynchronously after your request(s) complete(s). Here is a sample:
var app = platform(BROWSER_PROVIDERS) .application([BROWSER_APP_PROVIDERS, appProviders]); var service = app.injector.get(CompaniesService); service.executeSomething().flatMap((data) => { var companiesProvider = new Provider('data', { useValue: data }); return app.bootstrap(appComponentType, [ companiesProvider ]); }).toPromise(); See this question for more details:
and the corresponding plunkr: https://plnkr.co/edit/ooMNzEw2ptWrumwAX5zP?p=preview.
-18716263 0 Blogger API v.3 - can't transfer the data to the post (javascript)New post created with out data - http://yatsynych.blogspot.com/. Problem on object body_data?
My source:
function makeApiCallBlogger() { gapi.client.setApiKey('AIzaSyDFnBwpKVqjMm9NJ4L0Up5Y_bYpsaJdC6I'); gapi.client.load('blogger', 'v3', function() { var body_data = { "kind": "blogger#post", "blog": { "id": "********" }, "title": "A new post", "content": "With <b>exciting</b> content..." } var request = gapi.client.blogger.posts.insert({ "blogId": '********', "body": body_data}); request.execute(function(response) { alert(response.toSource()); }); }); }
-22677583 0 You probably want to pad it with 0 bytes. Fill your newtitle buffer with zeroes before copying the string into it, then write that buffer to the file:
char newtitle[80]; memset(newtitle, '\0', 80); strncpy(newtitle, title, 80); fwrite(newtitle, sizeof(char), 80, fp); You can pass whatever ASCII character you want into memset(), to pad it with. But with binary files you'll generally use '\0'.
I think EMD is good solution to resolve cross-bin problem compares with bin to bin method. However, as some mentions, EMD is very long time. Could you suggest to me some other approach for cross-bin?
-40314623 0 Method that returns DataReader -- will it cause resource leaks?Say I have the following code:
private AdomdDataReader ExecuteReader(string query) { var conn = new AdomdConnection(ConnectionString); conn.Open(); var cmd = new AdomdCommand(query, conn); cmd.Parameters.Add("Foo", "Bar"); return cmd.ExecuteReader(CommandBehavior.CloseConnection); } Then in usage, you'd wrap the reader in a using statement:
using (var reader = ExecuteReader("...")) ... This would be in contrast to manually opening a connection and executing a reader each time:
using(var conn = new AdomdConnection(ConnectionString)) { conn.Open(); using(var cmd = new AdomdCommand(query, conn)) { cmd.Parameters.Add("Foo", "Bar"); var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); ... } } So I'm basically just trying to reduce boilerplate for reading many similar queries from a database. Am I exposing myself to resource leaks by doing so?
-12746372 0 TDD for a new Java application - Where should I start?Goal : testing TDD in a typical enterprise Java environment.
Context :
Frameworks used (even if it's overkill, I practice project based learning) :
My project is a simple billing system which would help freelancers create, edit and print/send bills to customers.
Once my project is created and configured, I don't know where to start. Let's say my first my first feature is to create a bill with a unique number and a title.
Question : What should I test first ?
Thanks in advance for your answers,
Cheers
-2996559 0You can use unsafe and pointers. But your particular case would say a bit more about what direction you should head.
Sure, the function like sprintf is sprintf. You can put functions in the stash and call them from TT, and if you want them to be available all the time you can add them to the TEMPLATE_VARS in your view.
Regular expressions are like the sort function in Perl. You think it's pretty simple because it's just a single command, but in the end, it uses a lot of processing power to do the job.
There are certain things you can do to help out:
.*). The wretched truth is that after decades of writing in Perl, I've never masted the deep dark secrets of regular expression parsing. I've tried many times to understand it, but that usually means doing research on the Web, and ...well... I get distracted by all of the other stuff on the Web.
And, it's not that difficult, any half decent developer with an IQ of 240, and a penchant for sadism should easily be able to pick it up.
@David W.: I guess I'm confused on backtracking. I had to read your link several times but still don't quite understand how to implement it (or, not implement it) in my case. – user522962
Let's take a simple example:
my $string = 'foobarfubar'; $string =~ /foo.*bar.*(.+)/; my $result = $1; What will $result be? It will be r. You see how that works? Let's see what happens.
Originally, the regular expression is broken into tokens, and the first token foo.* is used. That actually matches the whole string:
"foobarfubar" =~ /foo.*/ However, if the first regular expression token captures the whole string, the rest of the regular expression fails. Therefore, the regular expression matching algorithm has to back track:
"foobarfubar" =~ /foo.*/ #/bar.*/ doesn't match "foobarfuba" =~ /foo.*/ #/bar.*/ doesn't match. "foobarfub" =~ /foo.*/ #/bar.*/ doesn't match. "foobarfu" =~ /foo.*/ #/bar.*/ doesn't match. "foobarf" =~ /foo.*/ #/bar.*/ doesn't match. "foobar" =~ /foo.*/ #/bar.*/ doesn't match. ... "foo" =~ /foo.*/ #Now /bar.*/ can match! Now, the same happens for the rest of the string:
"foobarfubar" =~ /foo.*bar.*/ #But the final /.+/ doesn't match "foobarfuba" =~ /foo.*bar.*/ #And the final /.+/ can match the "r"! Backtracking tends to happen with the .* and .+ expression since they're so loose. I see you're using non-greedy matches which can help, but it can still be an issue if you are not careful -- especially if you have very long and complex regular expressions.
I hope this helps explain backtracking.
The issue you're running into isn't that your program doesn't work, but that it takes a long, long time.
I was hoping that the general gist of my answer is that regular expression parsing isn't as simple as Perl makes it out to be. I can see the command sort @foo; in a program, but forget that if @foo contains a million or so entries, it might take a while. In theory, Perl could be using a bubble sort and thus the algorithm is a O2. I hope that Perl is actually using a more efficient algorithm and my actual time will be closer to O * log (O). However, all this is hidden by my simple one line statement.
I don't know if backtracking is an issue in your case, but you're treating an entire webpage output as a single string to match against a regular expression which could result in a very long string. You attempt to match it against another regular expression which you do over and over again. Apparently, that is quite a process intensive step which is hidden by the fact it's a single Perl statement (much like sort @foo hides its complexity).
Thinking about this on and off over the weekend, you really should not attempt to parse HTML or XML with regular expressions because it is so sloppy. You end up with something rather inefficient and fragile.
In cases like this may be better off using something like HTML::Parser or XML::Simple which I'm more familiar with, but doesn't necessarily work with poorly formatted HTML.
Perl regular expressions are nice, but they can easily get out of our control.
-2745680 0 FFmpeg bitrate issueI'm dealing with a very big issue about bit rate , ffmpeg provide the -b option for the bit rate and for adjustment it provide -minrate and -maxrate, -bufsize but it don't work proper. If i'm giving 256kbps at -b option , when the trans-coding finishes , it provide the 380kbps. How can we achieve the constant bit rate using ffmpeg. If their is +-10Kb it's adjustable. but the video bit rate always exceed by 50-100 kbps.
I'm using following command
ffmpeg -i "demo.avs" -vcodec libx264 -s 320x240 -aspect 4:3 -r 15 -b 256kb \ -minrate 200kb -maxrate 280kb -bufsize 256kb -acodec libmp3lame -ac 2 \ -ar 22050 -ab 64kb -y "output.mp4" When trans-coding is done, the Media Info show overall bit rate 440kb (it should be 320kb).
Is their something wrong in the command. Or i have to use some other parameter? Plz provide your suggestion its very important.
-21397773 0You can get the values with use of ID. But ID should be Unique.
<body> <h1>Adding 'a' and 'b'</h1> <form> a: <input type="number" name="a" id="a"><br> b: <input type="number" name="b" id="b"><br> <button onclick="add()">Add</button> </form> <script> function add() { a = $('#a').val(); b = $('#b').val(); var sum = a + b; alert(sum); } </script> </body>
-20385910 0 Why don't you simply use static variables ?
HttpContext is dependent on ASP.NET pipeline. In a host-agnostic model (OWIN or self-hosted) you don't have access to it.
Application storage in HttpApplicationState is only useful if you need to access the current HttpContext. If it's not necessary, you should simply use static properties.
Moreover, HttpApplicationState was initially created for backward compatibility with classic ASP.
public static class StaticVariables { public static object SomeInfo { get; set; } } See also Singleton and HttpApplicationState and http://forums.asp.net/t/1574797.aspx
-34413771 0Actually the work of proximity is to detect other devices like windows phone , or windows computer through NFC.It detect those devices which has NFC tags
Here is the link for your reference https://msdn.microsoft.com/library/windows/apps/jj207060(v=vs.105).aspx#BKMK_Requiredcapabilities
and there is no clear explanation on any of the website about the detection of human body or any object that comes near the phone like when the screen turns off while getting it near to our ears may be we can use light sensors to detect object nearby.
I think that this sensor does not have a API and is provided by default by windows phone API if we use the calling API classes
-16018398 0The compiler seems to place the casting from const char& to char on the same level as upcasting std::ostringstream to std::ostream when the overload resolution comes.
The solution could be to template the type of operator<< to avoid the upcasting:
namespace _impl { template <typename T, typename Y> Y& operator<<(Y& osstr, const T& val) { return osstr; } }
-14797735 0 Memcache - How to prevent frequent cache rebuilds? I have been working for Memcache for the last week or so, I have managed to work out how to set keys/delete keys. This is fine but Im still attempting to work out how to do the same for a while loop of results.
For example I will have a while loop of posts, from within the logic the function will check to see if Memcache is set, if not it will collect the results and create the key. My question is this, If I have set the looped data into a set key and display the set key (Newest First) Then what happens when a new post is inserted? I understand I can set a time limit on the set key, but as the content will/could be added whenever it seems that setting a limit could still display old posts. So my question is how would I be able to update the set key.
The only way I can think of a possible solution is for when a user inserts a new post, this deletes the key, and when the all posts is viewed again this is when the key gets set again. But this seems rather counter productive, just as if there are 10's of users submitting posts then all the posts will be set over and over again (Doesn't really seem beneficial)
I hope this makes sense, any help or guidance would be appreciated.
-14874357 0 How to use regex to match all element in document.doctype.internalSubsetBy using document.doctype.internalSubset, I have the following string, say str:
<!ENTITY owl "http://www.w3.org/2002/07/owl#" > <!ENTITY xsd "http://www.w3.org/2001/XMLSchema#" > <!ENTITY rdfs "http://www.w3.org/2000/01/rdf-schema#" > <!ENTITY rdf "http://www.w3.org/1999/02/22-rdf-syntax-ns#" > Then, I use regex to extract the result:
result = regex.exec(str); My expected output is an array in which:
result[0] = owl "http://www.w3.org/2002/07/owl#" result[1] = xsd "http://www.w3.org/2001/XMLSchema#" ... result[3] = rdf "http://www.w3.org/1999/02/22-rdf-syntax-ns#" So, I create this regex:
var regex = /(?:<!ENTITY(.*?)>)*/g; And here is the result, of course, it's not I want:
owl "http://www.w3.org/2002/07/owl#" Can anyone help me to figure out the errors, and how to fix all of them ?
Note that I can use s.indexOf() to get the position of <!ENTITY and >, and then, use s.subString() to get the same result, but I'm learning regex now, so I want to use regex.
--------------Update---------------
Thanks to Supr, I can finally figure out the error, it seems to me that, in this case, "*" doesn't mean "match one or many time", so instead of using /(?:<!ENTITY(.*?)>)*/g, we'll use this one: /(?:<!ENTITY(.*?)>)/g (supress the *) and then loop over the string until we get all result. Here is the source:
var str = '<!ENTITY owl "http://www.w3.org/2002/07/owl#" >' + '<!ENTITY xsd "http://www.w3.org/2001/XMLSchema#" >' + '<!ENTITY rdfs "http://www.w3.org/2000/01/rdf-schema#" >' + '<!ENTITY rdf "http://www.w3.org/1999/02/22-rdf-syntax-ns#" >' var regex = /(?:<!ENTITY(.*?)>)/g; var results = []; while ((result = regex.exec(str)) != null) { results.push(result[1]); } console.log(str); console.log("-------------------------------"); for (var i = 0; i < results.length; i++) { document.write(results[i] + "<br>"); } For testing: http://jsfiddle.net/nxhoaf/jZpHv/
By the way, here is my solution using s.indexOf() and recursion:
var str = '<!ENTITY owl "http://www.w3.org/2002/07/owl#" >' + '<!ENTITY xsd "http://www.w3.org/2001/XMLSchema#" >' + '<!ENTITY rdfs "http://www.w3.org/2000/01/rdf-schema#" >' + '<!ENTITY rdf "http://www.w3.org/1999/02/22-rdf-syntax-ns#" >' var getNamespace = function(input) { var result = []; // Store the final result var temp = []; // Store the temporary result // Non trivial case if ((input != null) && (input.length != 0)) { // Get the begin and and index to extract the entity's content var begin = input.indexOf("<!ENTITY"); var end = input.indexOf(">"); if ((begin == -1) || (end == -1) || (begin >= end)) { // not found return null; } // Fix the begin index begin = begin + "<!ENTITY".length; // Get the content and save it to result variable var item = input.substring(begin, end); // ok, get one item // As end > begin, item is always != null item = item.trim(); // Normalize result.push(item); // Continue searching with the rest using // recursive searching temp = getNamespace(input.substring(end + 1)); // Ok, collect all of data and then return if (temp != null) { for (var i = 0; i < temp.length; i++) { result.push(temp[i]); } } return result; } else { // Trivial case return null; } } // Parse it to get the result result = getNamespace(str); console.log("*************"); for (var i = 0; i < result.length; i++) { document.write(result[i] + "<br>"); } you can test it here: http://jsfiddle.net/nxhoaf/FNFuG/
-9781359 0 Magento product zoom filesCan someone please tell me what are the Javascript files for default Magento Product Zoom extension. On my site its not working and seems I am missing some files.
please reply.
-6716585 0 Postr Wall To Fans Page Using Graph APII am trying to post wall through my application with Facebook Graph API to user's fan page. Please give me ideas how can I past wall to the fan page using Graph API and without using the access token of fans page .
Thanks in advance!
-5041432 0 Mvc 3 Razor : Using Sections for Partial View?I defined a section in partial view and I want to specify the content of section from view. But I can't figure out a way. In asp.net user controls, we can define asp:placeholders, and specify the content from aspx where user control lies. I'll be glad for any suggestion.
Thanks
[edit] Here is the asp.net user control and I want to convert it to razor partial view
User control:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="SpryListView.ascx.cs" Inherits="SpryListView" %> <div spry:region="<%=this.SpryDataSetName%>" id="region<%=this.ID%>" style="overflow:auto;<%=this.DivStyle%>" > <table class="searchList" cellspacing="0" style="text-align:left" width="100%"> <thead> <tr> <asp:PlaceHolder ID="HeaderColumns" runat="server"></asp:PlaceHolder> </tr> </thead> </table> User control code:
public partial class SpryListView : System.Web.UI.UserControl { private string spryDataSetName ; private string noDataMessage = "Aradığınız kriterlere uygun kayıt bulunamadı."; private bool callCreatePaging; private string divStyle; private ITemplate headers = null; private ITemplate body = null; [TemplateContainer(typeof(GenericContainer))] [PersistenceMode(PersistenceMode.InnerProperty)] public ITemplate HeaderTemplate { get { return headers; } set { headers = value; } } [TemplateContainer(typeof(GenericContainer))] [PersistenceMode(PersistenceMode.InnerProperty)] public ITemplate BodyTemplate { get { return body; } set { body = value; } } public string DivStyle { get { return divStyle; } set { divStyle= value; } } public string NoDataMessage { get { return noDataMessage; } set { noDataMessage = value; } } public string SpryDataSetName { get { return spryDataSetName; } set { spryDataSetName = value; } } public bool CallCreatePaging { get { return callCreatePaging; } set { callCreatePaging = value; } } void Page_Init() { if (headers != null) { GenericContainer container = new GenericContainer(); headers.InstantiateIn(container); HeaderColumns.Controls.Add(container); GenericContainer container2 = new GenericContainer(); body.InstantiateIn(container2); BodyColumns.Controls.Add(container2); } } public class GenericContainer : Control, INamingContainer { internal GenericContainer() { } } protected void Page_Load(object sender, EventArgs e) { } } aspx
<spry:listview SpryDataSetName="dsOrders" CallCreatePaging="true" runat="server" ID="orderListView"> <HeaderTemplate> <th> </th> <th>SİPARİŞ TARİHİ</th> <th style="text-align:right">GENEL TOPLAM</th> <th style="text-align:right">KDV</th> <th style="text-align:right">NET TOPLAM</th> </HeaderTemplate> </spry:listview> [edit]
I want to do exactly this in mvc 3 razor partial view.
-30345829 0You can use the HttpRequest.UrlReferer property. Create the single action in some controller:
public class SomeController : BaseController { public ActionResult Change(int value) { Session["Value"] = value; return Redirect(Request.UrlReferer.ToString()); } }
-5735706 0 Vim: Edit multi aleatory lines I'm aware of the possibility to edit multiple lines on the same column by doing:
CTRL+V down...down..down... SHIFT+I type_string_wanted But I'd like to edit multiple specific locals addin new strings (maybe using cursor (h j k l) or mouse (with :set mouse=a)).
Like on this example, where I want to add the string 'XX' to specific locations. I.e.,
from this:
Hi. My name is Mario! to this:
XXHi. My XXname is XXMario! Any ideas?
-30765223 0Your syntax is wrong, and doesn't produce anything except an error message as you've written it here.
If I understand your question correctly, this should produce the output you want:
SELECT old_column, CASE old_column WHEN 'A' THEN 1 WHEN 'B' THEN 2 WHEN 'C' THEN 3 ELSE 0 END AS new_column FROM table_name A SELECT does exactly what it says it does - it selects the data, but doesn't actually alter it's content.
To permanently add a new column and populate it, you'll need to first ALTER TABLE to add the new column, and then UPDATE that new column's content.
ALTER TABLE table_name ADD COLUMN newcolumn integer; UPDATE table_name SET newcolumn = CASE oldcolumn WHEN 'A' THEN 1 WHEN 'B' THEN 2 WHEN 'C' THEN 3 ELSE 0 END; For future reference: If you want help with your SQL syntax, include the actual code you've tried that isn't working, instead of inventing something as you go or re-typing. With SQL-related questions, it's almost always a good idea to post some sample data and the output you'd like to obtain from that data, along with your actual SQL code trying to produce that output. It makes it much easier to help you when we can understand what you're trying to do and have samples to use.
-10079340 0 jquery submit input and textareas at the same timeThe code below saves all the Input Fields. If I change the word "INPUT" to "TEXTAREA" it will save the textarea text boxes, is there a way to change the code to save all the input fields and the textarea fields at the same time, as opposed to running through the code twice?
// JQUERY: Run .autoSubmit() on all INPUT fields within form $(function(){ $('#ajax-form INPUT').autoSubmit();
-9985103 0 http://wiki.bash-hackers.org/scripting/posparams
It explains the use of shift (if you want to discard the first N parameters) and then implementing Mass Usage (look for the heading with that title).
just add a class at your main ul (i added 'main-menu' for example) and then add this css:
.main-menu > li > ul, .main-menu > li > ul > li > ul, .main-menu > li > ul > li > ul > li > ul { display: none; } .main-menu > li:hover > ul, .main-menu > li > ul > li:hover > ul, .main-menu > li > ul > li > ul > li:hover > ul { display:block; }
-19683858 0 You can use clearQueue() to stop the animation
clearQueue() : Stop the remaining functions in the queue
HTML
<div class="box"></div> <button id="restartTransition">Click Me</button> CSS
.box{ opacity: 0.8; position: absolute; left: 0; top: 5%; background: #505060; border-radius: 1px; box-shadow: inset 0 0 0 2px rgba(0, 0, 0, 0.2); margin: -16px 0 0 -16px; width: 32px; height: 32px; z-index: 2; } jQuery
$(document).ready(function(){ $("#restartTransition").on("click", function(){ $('.box').clearQueue().transition({ x: '0px' },10); $('.box').transition({ x: '350px' },5000); }); });
-13130522 0 JavaScript - Reposition a DIV incrementally onClick Very simple code, very simple problem. When a link is pressed, it moves a div either up or down. However, I cannot get it to move incrementally. I know this is a simple syntax error, but google isn't revealing the error of my ways. Anyone willing to enlighten me?
<a class="galsel" onclick="document.getElementById('innerscroll').style.bottom -='167px';">«</a>
<a class="galsel" onclick="document.getElementById('innerscroll').style.bottom +='167px';">»</a>
I already have it so that the div tiles itself vertically, so I'm not worried about it going "too high" or "too low"
Here's what it looks like right now: drainteractive.com/FBD/projects.php
-8281411 0View source shows you the source of the original html file, it does not update when javascript updates the DOM. Most browsers have some form of tool that allows you to inspect the current state of the DOM, such as the inspector in webkit browsers or firebug in firefox.
-25332174 0 Using conditions to specify groups for GROUP BYI'm not even sure if this is possible using SQL, but I'm completely stuck on this problem. I have a table like this:
Total Code 212 XXX_09_JUN 315 XXX_7_JUN 68 XXX_09_APR 140 XXX_AT_APR 729 XXX_AT_MAY I need to sum the "total" column grouped by the code. The issue is that "XXX_09_JUN" and "XXX_7_JUN" and "XXX_09_APR" need to be the same group.
I was able to accomplish this by creating a new column where I assigned values based on the row's code, but since this needs to be done on multiple tables with millions of entries, I can't use that method.
Is there some way that I could group the rows based on a condition such as:
WHERE Code LIKE '%_09_%' OR Code LIKE '%_7_%' This is not the only condition - I need about 10 conditions like this. Sorry if that doesn't make sense, I'm not sure how to explain this...
Also, if this can be accomplished using Visual Studio 2008 and SSRS more easily, that would work as well because that is the final goal of this query.
Edit: To clarify, this would be the ideal result:
Total Code 595 had_a_number 869 had_at
-21440485 0 I haven't used sublime, but here is what i found.
you could create snippets using Ruby on Rails Snippet package
You could use the solution given in 'How to automatically add "end" to code blocks?'.
This simple and well organized code is not working. Code uses AsyncTask and its a sample code from internet.Sample Code Im using android studio and tried starting it over and over.
package com.example.jakiro.jakki; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import java.io.IOException; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new Rush().execute(); } private class Rush extends AsyncTask { @Override protected Object doInBackground(Object[] objects) { makePostRequest(); return null; } } private void makePostRequest() { HttpClient httpClient = new DefaultHttpClient(); // replace with your url HttpGet httpPost = new HttpGet("https://www.google.com"); HttpResponse response; try { response = httpClient.execute(httpPost); Log.d("Response of GET request", response.toString()); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } error codes:
java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:300) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) at java.util.concurrent.FutureTask.setException(FutureTask.java:222) at java.util.concurrent.FutureTask.run(FutureTask.java:242) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:841) Caused by: java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=www.example.com at org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.java:591) at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:293) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) at com.example.nova.myapplication.MainActivity.makePostRequest(MainActivity.java:66) at com.example.nova.myapplication.MainActivity.access$100(MainActivity.java:22) at com.example.nova.myapplication.MainActivity$Rush.doInBackground(MainActivity.java:36) at android.os.AsyncTask$2.call(AsyncTask.java:288) at java.util.concurrent.FutureTask.run(FutureTask.java:237) Manifest:
<?xml version="1.0" encoding="utf-8"?> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.jakiro.jakki.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application>
-7100695 0 alias for expressions in hql queries my Hibernate version is 3.2.6.ga
Googling around reveals many people are having the same problems with Hibernate HQL not handling aliases very well. Apparently HQL only lets you alias a column that exists in a table. Also, HQL generates its own aliases for all columns in the query and these have the form col_x_y_ but how these are generated I don't know.
For my case I want to add two derived columns into a third derived column. Trivial in native SQL, surprisingly difficult in HQL.
My contrived, simplified example:
sqlcmd = " SELECT aa.course.code, " + " (CASE WHEN aa.gender = 'M' THEN 1 ELSE 0 END), " + " (CASE WHEN aa.gender = 'F' THEN 1 ELSE 0 END), " + " ( col_0_1_ + col_0_2_ ) " + " FROM Student AS aa "; How can I add the 2nd and 3rd columns together to form a 4th column in HQL?
TIA,
Still-learning Steve
-5377486 0 JavaScript unixtime problemI get the time from the database in Unix format.
It looks like this: console.log (time); Result: 1300709088000
Now I want to reformat it and pick out only the time, I found this: Convert a Unix timestamp to time in Javascript
That did not work as I want. The time I get is this:
1300709088000 9:0:0 1300709252000 6:33:20 1300709316000 0:20:0 1300709358000 12:0:0 1300709530000 11:46:40 It is very wrong times when I know that times are quite different. How can I fix it?
console.log(time); var date = new Date(time*1000); // hours part from the timestamp var hours = date.getHours(); // minutes part from the timestamp var minutes = date.getMinutes(); // seconds part from the timestamp var seconds = date.getSeconds(); // will display time in 10:30:23 format var formattedTime = hours + ':' + minutes + ':' + seconds; console.log(formattedTime);
-40968814 0 As most of people mentioned here - one of the solutions will be to use aliases. Don't like them to be honest because they are preventing me learning some really nice Linux commands :) It's just a joke. But the best way for you, as I think, will be to locate a ~/.bashrc file located in your home directory and put there:
alias mysql="mysql -h 127.0.0.1" Don't forget that you have to restart your session in order for this solution to work or you may type bash command at the same terminal session - it will reload all your bash settings. Good luck!
P.S. I suggest you to close all other terminal windows before editing .bashrc because you may just got a read-only file. I had such issue under Win7x64
that's my flash site , I want to extend the gray box to reach the edge of the HTML page . I mean that I don't want the background color to appear all I want in the page the flash site in the resolution of the page whatever the PC resolution . sorry for my bad English . 
Thank you. In my form there are some dynamic input text boxes created by using ng-repeat. How to get the values of these text boxes when submit the form using Angular js?
<form ng-submit="submit()"> <div ng-repeat="opt in option"> <input type="text" name=""> </div> </form>
-30461238 0 I'm not sure if you can do this in Ruby, but doing it like this in Jquery may work. However you should definitely fix the databases.
$(document).ready(function() { //On document ready $("form").find('input').each(function(){ //find all inputs in forms if ($(this).val() == "(NULL)") { //if the value of an input is "(NULL)" $(this).val(""); //Set it to "" } }) })
-4453806 0 The HTML search form will contain text fields, many select dropdowns and some checkboxes. Can anyone offer any advice, best practice, design patterns or resources to assist with this kind of problem.
I would suggest that Google exemplifies the best UI for search. Don't give me a lot of fiddly fields, just one text field so I can type "Shirley Jones UAF"
-27725949 0See this answer http://stackoverflow.com/a/27727236/286335. Really short, easy and general.
-32624714 1 Beautiful soup queriesI'm struggling to have queries in BS with multiple conditions of the type AND or OR. From what I read I have to use lambda. As an example, I'm looking for tags that match either "span", {"class":"green"} or tag.name == "h1" on the page http://www.pythonscraping.com/pages/warandpeace.html
I manage to get them separately using the lambda syntax:
bsObj.findAll(lambda tag: tag.name == "h1") will return h1
bsObj.findAll(lambda tag: tag.name == "span", {"class":"green"}) wil return span green
Or I can get all "span" tags and "h1" :
bsObj.findAll(lambda tag: tag.name == "span" or tag.name == "h1") return span green and red as well as h1
But I don't manage to get the span of class green or h1, as the following code does not provide the right result :
bsObj.findAll(lambda tag: tag.name == "span", {"class":"green"} or tag.name == "h1")
Can please someone explain me the right way to do it in one query ? Goal here is not only to get the result but rather understand the syntax. Thanks !
(using Python 3.4)
PS : I think this issue is different from the the one here: BeautifulSoup findAll() given multiple classes? as well as a variation of Python BeautifulSoup give multiple tags to findAll (as we want a specific attribute)
I'm new to bash and I am trying to do two string comparisons with an or statement. Can anyone give me any idea where I have gone wrong?
echo $DEVICETYPE FILEHEADER=ANDROID if [[ "$DEVICETYPE" == "iPad" ] || ["$DEVICETYPE" == "iPhone" ]]; then $FILEHEADER = IOS fi echo $FILEHEADER -18578783 0iPad
ANDROID
str.str[0].toUpperCase(); should just be
str[0].toUpperCase(); If that isn't the case, you should try console.log(str) and find out what exactly str is but I believe this is your problem.
I had a very similar problem myself: I was developing a C program (using the MinGW gcc compiler) which used the curl library to do http GET operations. I tested it on Windows XP (32-bit) and Windows 7 (64-bit). My program was working in Windows XP, but in Windows 7 it crashed with the same 0xc000007b error message as the OP got.
I used Dependency Walker on a down-stripped program (with only one call to the curl library:curl_easy_init()). I essentially got the same log as yours, with OPENLDAP.DLL as the last successfully loaded module before the crash.
However, it seems my program crashed upon loading LIBSASL.DLL (which was the next module loaded according to the log from Dependency Walker run on Windows XP).
When looking again in the log from Dependency Walker on Windows 7, LIBSASL.DLL indeed shows up a x64 module. I managed to get my program to run by copying a 32-bit version of the DLL file from another application on my harddisk to my program's directory.
Hopefully this will work for other people having similar problems (also for the OP if the problem still wasn't resolved after these years). If copying a 32-bit version of LIBSADL.DLL to your program's directory doesn't help, another module might cause the crash. Run Dependency Walker on both the 32- and 64-bit systems and look up the module name from the log of the successful run.
-5847615 0 Document.referrer issue on IE when the requests doesn't come from a linkPossible Duplicate:
IE has empty document.referrer after a location.replace
Hi there,
I have got an issue on using the document.referrer property in IE. When I get to a page not through a link but changing the window.location through JavaScript, the document.referrer of the destination page is empty in IE7/8. Any idea on how to get around it?
Thanks.
-14393716 0 launch command line from java without knowing OSIs there a way to launch the command line from java without knowing OS? For example, the method would open up the terminal shell for a Linux OS and open the command line for Windows.
I do know (from looking at previous questions) that i can just check the OS and then open the proper command line, but is there a way to open the command line from a java method that is OS agnostic?
-16375955 0It's not possible to do so.....
-14430016 0This, undocumented and unsupported, feature apparently never did work on Windows.
Instead you can use one of the pre-built runtime systems that loads a main.sav from the folder containing the executable. E.g. save your test.sav as main.sav instead and place it alongside sprti.exe in a folder that contains a proper folder structure for SICStus, as described in the manual, in the section Runtime Systems on Windows Target Machines.
The most common solution is to use the spld.exe tool an build a self contained executable but that requires the corresponding C compiler from Microsoft.
(I am one of the SICStus Prolog developers)
-17432434 0 How to add view on imageView?I have created a class that extends a view which will work as a drawing slate to draw a text. I want to add that drawing slate in image View. And I have main activity which contains a scrollable list on top and a image view below list. Now I want to add that View(Drawing slate) on image View. So how to implement this? I tried lot, but I am not getting how to do this.Do i need to use any other view instead of image View? Please help as soon as possible. Thanks in advance.
-21155503 0Found new way to put job back to same queue with some delay time. We can use direct release function of pheanstalk library. e.g.
$this->pheanstalk->release($job,$priority,$delay); This way, we don't need to find job's actual tube and can save concurrency issues, specially in my case.
Thanks for your help !!!
-23776481 0Thanks for all the help, and the answer I selected most closely answers the problem of 2 emulators running slowly.
What it turned out to be was that I was using 767MB on an Intel HAXM emulator, and creating 2 of those went over the allocated amount for HAXM. After running 1 Intel and 1 ARM emulator, it worked. The error message was somewhat inconspicuous so I didn't notice it at first.
-27407152 0It's been a while since I did this but I just had <cfpop> login to the email account in question, search for emails with a specific subject, gather up the data I wanted from there, like the email address it bounced from, and update the database using an IN clause based on a list of bounced email addresses.
Just make sure to delete the messages you've scanned afterwards.
However, in CF10+, you can use the secure attribute instead of invoking java for the secure connection.
<cfpop server="pop.gmail.com" action="getHeaderOnly" name="popMessages" port="995" maxrows="10" username="user@gmail.com" password="password" secure="yes|no"> A quick google for how to access gmail with cfpop returned this, useful for connecting with older CFs.
<!--- See: http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html Warning: Changing system properties is potentially dangerous and should be done with discretion. ---> <cfset javaSystem = createObject("java", "java.lang.System") /> <cfset javaSystemProps = javaSystem.getProperties() /> <cfset javaSystemProps.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory") /> <cfpop server="pop.gmail.com" action="getHeaderOnly" name="popMessages" port="995" maxrows="10" username="user@gmail.com" password="password">
-29371942 0 When you add a Script Task or Component to an SSIS package, there is a template in your installation folder that SSIS uses.
For 2012, it'd be in Program Files (x86)\Microsoft SQL Server\110\DTS\Binn
In there, you have a VSTA11_IS_ST_CS_Template.vstax file which is just an uncompressed zip.
IS%20Script%20Task%20Project.csproj I blogged a similar approach with Slimming down the SSIS Script Task
The specific attribute you're looking to modify in the project file is
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion> What you wanted to change it to, you never specified
-20725042 0 JS: Calling a function from within that function, when dealing with multiple instancesHow do I call a function from within the function, when I have multiple instances of that function?
I know I can simply call the function from within:
$(".mCSB_container").sortable({ revert: true, scroll: true, update: function( event, ui ){ new update(param1); }, }); function update(param1){ if (updating){ //If I'm already updating, I want to wait for that update to be finished setTimeout(function(){ update(param1); }, 100) } else { updating = true; //Proceed with the update //... postUpdate(); } } function postUpdate(){ $.ajax({ url: '/update', type: 'POST', dataType: 'json', async: true, data: postData, success: function (data) { //... updating = false; return data; }, error: function (data) { //refresh page return false; } }); } Now I'm trying to get my head around how instantiation works in JS. I know I can create a new instance simply by calling new update(param1);, but then what's going to happen in the timeout when I try to call the update function? I can always just create a new instance every time, but isn't that inefficient?
If I could just call the same instance from within the instance that seems like it would be ideal.
Thanks for any help, I greatly appreciate it.
-18939806 0 Accessing an Objective-C ivar from outside the class at runtimeI know this idea completely breaks encapsulation, but say I have the following class extension:
@interface MyClass () { int reallyImportantIvar; } // ... @end Normally, the class behaves like it should inside the Objective-C layer - sending and receiving messages, etc. However there is one ('public') subroutine where I need the best possible performance and very low latency, so I would prefer to use a C method. Of course, if I do, I can no longer access reallyImportantIvar, which is the key to my performance-critical task.
It seems I have two options:
My question is: is Option 2 even possible, and if so, what is its overhead? (E.g. Am I still looking at an O(n) algorithm to look up a class's instance variables anyway?)
-20859454 0Check if you have zero value for recursion property of the model.
$this->Post->recursive = 0; After hours of headbanging removing the above line fixed it for me
-28393248 0You cannot overload functions in C, but you can organize your code to make it optimal. I would create a function for rgb2hsv and that would get a void * type of parameter, would determine the type and use it, handling all possible cases. And you should use only this function. On lower levels you still duplicate your function, on higher level you will not have to call two separate functions. This would simplify usage.
return Class.forName(className); regarding your edit, you cannot "cast" a string value to a long value. in order to convert a string value to some other type, then you need something more complex, like this.
-26141164 0Skype was hogging port 80
I came to this conclusion from using this on the command line:
netstat -ano
Then finding the PID against port 80 in Task Manager
Then quitting skype and seeing the issue go away.
I resolved the conflict by changing Skype settings to leave port 80 alone. This also explains why the 404 was not an IIS styled 404 page and why there was nothing in the IIS logs - just a question mark against the default website icon.
-20210111 0 NSLog(@" %@",NSStringFromCGRect([(UIButton*)[array lastObject]frame]));NSLog(@" %@",NSStringFromCGRect([(UIButton*)[array lastObject]frame])); what is the error in this statement. My code is breaking error [__NSArrayI frame]: unrecognized selector sent to instance 0x1c5f2e00
-40980396 0That caused by module configuration cached. It was generated at first time to speed up reading configuration. So, after adding new service configuration always remove the cache in data/cache/module-config-cache.application.config.cache.php It will be created automatically if not found.
Read the documentation, log4net is very configurable and well documented.
Documentation: https://logging.apache.org/log4net/release/manual/configuration.html
using Com.Foo; // Import log4net classes. using log4net; using log4net.Config; public class MyApp { // Define a static logger variable so that it references the // Logger instance named "MyApp". private static readonly ILog log = LogManager.GetLogger(typeof(MyApp)); static void Main(string[] args) { // Set up a simple configuration that logs on the console. BasicConfigurator.Configure(); log.Info("Entering application."); Bar bar = new Bar(); bar.DoIt(); log.Info("Exiting application."); } } Take note the difference in the method for getting to log instance.
An example of the .config file is:
<log4net> <!-- A1 is set to be a ConsoleAppender --> <appender name="A1" type="log4net.Appender.ConsoleAppender"> <!-- A1 uses PatternLayout --> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%-4timestamp [%thread] %-5level %logger %ndc - %message%newline" /> </layout> </appender> <!-- Set root logger level to DEBUG and its only appender to A1 --> <root> <level value="DEBUG" /> <appender-ref ref="A1" /> </root> </log4net> There are lots of Appenders, above is a ConsoleAppender, but a DatabaseAppender exists and other types that might fit with you're need.
-25321810 0After exploration, I came across fnServerData Ajax Calling options. With the help of this API, i was able to complete this task. More details here
-24113368 0Java interfaces cannot be instantiated, the programmer has to specify what implementation of the interface he wants to instantiate.
For example, if you try to do this (replace INTERFACE with the name of the interface):
INTERFACE i = new INTERFACE(); you will get an error, because an interface cannot be instantiated.
What you must do is (replace IMPLEMENTATION with the name of the implementation of the interface):
INTERFACE i = new IMPLEMENTATION(); As you can see, you ALWAYS tell the program what implementation to use for an interface. There's no room for ambiguity.
In your example, the class TextSource is NOT instantating the interface TextReceiver (instantiation occurs with the "new" keyword). Instead, it has a constructor that receives the implementation of the interface as a parameter. Therefore, when you call TextSource you MUST tell it what implementation of TextReceiver to use.
-15442710 0function getMonth(monthNumber) { var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; return monthNames[monthNumber-1]; }
-11273633 0 If you consider what git-cmd.bat does, all you need to do is to set the right variable %PATH% before your git commands in your script:
If you don't, here is what you would see:
C:\Users\VonC>git --version 'git' is not recognized as an internal or external command, operable program or batch file. I have uncompressed the latest portable version of msysgit.
Put anywhere a test.bat script (so no powershell involved there) with the following content:
@setlocal @set git_install_root="C:\Users\VonC\prg\PortableGit-1.7.11-preview20120620" @set PATH=%git_install_root%\bin;%git_install_root%\mingw\bin;%git_install_root%\cmd;%PATH% @if not exist "%HOME%" @set HOME=%HOMEDRIVE%%HOMEPATH% @if not exist "%HOME%" @set HOME=%USERPROFILE% @set PLINK_PROTOCOL=ssh REM here is the specific git commands of your script git --version echo %HOME% git config --global --list Make sure HOME is correctly set, because Git will look for your global git config there.
The result will give you:
C:\Users\VonC>cd prog\git C:\Users\VonC\prog\git>s.bat C:\Users\VonC\prog\git>git --version git version 1.7.11.msysgit.0 C:\Users\VonC\prog\git>echo C:\Users\VonC C:\Users\VonC C:\Users\VonC\prog\git>git config --global --list user.name=VonC Note: that same script would work perfectly from a powershell session.
-6952371 0 CSS Fluid layout and imagesI am trying to create a completely fluid layout in CSS (everything in %), which would work seamlessly across platforms (desktop/mobile/tablets like iPad).
With Fluid Layouts, can an image be made completely fluid? For example:
img { max-width:100%; } There is no canonical mechanism in Ember to store and retrieve the current user. The simplest solution is probably to save your current user's account ID to Social.currentAccountId when the user is authenticated (ie. in the success callback of your ajax request). Then you can perform
Social.Account.find(Social.get('currentAccountId')) when you need to get the current user.
-11807076 0 streaming video from iphone to server programaticallyI need to implement iphone video streaming to server. I've googled a lot but I found only receiving video streams from server. It is made using UIWebView or MPMoviewPlayer. But how can I stream my captured media to server in realtime? Help me please. How can it be done?
-19345782 0Check your asset/www/ folder. Check the index.html file is there.
-7782179 0 RIA Services metadata for entities in different classIn my project, I have the following: - A class library that contains a Linq2SQL datacontext. - A web project containing the domainservice that uses the datacontext in the library.
I've not found a way to add metadata to the services where I don't have to manually build all of the metadata elements myself. Is there some something I am missing?
I am using RIA Services 1.0 - if a service pack addresses this, I'd be happy to know about it.
-37626429 0Which version of IIS you are using. Assuming 7.5 or above (> Windows 2008 r2), the default log location for IIS is C:\inetpub\logs\LogFiles . Inside this all the folders are named in format W3SVCsiteID, for example - W3SVC1. W3SVC2 etc.
In order to find the site ID
In the center pane (also know as workspace) you can see site name and it's ID.
Now usually when you browse a page in IIS something like below gets logged
2016-02-21 00:18:27 ::1 GET /index.html - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+WOW64;+rv:44.0)+Gecko/20100101+Firefox/44.0 200 0 0 75 However you wont see this immediately in log file as IIS buffers that in memory and flushes it later. If you want to forcefully flush the buffer to log file you can run below command from a elevated command prompt
netsh http flush logbuffer Hope this helps!
-17011472 0You need to set self.contentView height first Use this code:
- (void)configureScrollView { [self.contentView addSubview:self.contentArticle]; CGRect frame = self.contentArticle.frame; frame.size.height = self.contentArticle.contentSize.height; self.contentArticle.frame = frame; [self.scrollView addSubview:self.contentView]; frame = self.contentView.frame; frame.size.height += self.contentArticle.frame.height; self.contentView.frame = frame; self.scrollView.contentSize = self.contentView.frame.size; self.contentArticle.editable=NO; self.contentArticle.scrollEnabled=NO; //enable zoomIn self.scrollView.delegate=self; self.scrollView.minimumZoomScale=1; self.scrollView.maximumZoomScale=7; }
-34055244 0 Bootstrap Glyphicons hiding border For some reason, glyphicons hide a border of a container if it's being floated. Can someone explain this, and if there's a known workaround?
OS X 10.11.1, Chrome 47.0.2526.73 (64-bit)
-1940929 0 to open an excel file, what is the difference between these 2 assemblieswhen adding a reference I see:
.net tab
microsoft.office.tools.excel
is that the one I need to read a excel file?
other posts seem to be using a COM assembly with 'interop' in it?
-38173134 0test.c:5:5: error: conflicting types for 'getline' int getline (char line[], int maxline); ^ /usr/include/stdio.h:442:9: note: previous declaration is here ssize_t getline(char ** __restrict, size_t * __restrict, FILE * __restrict) ... I hope that answers your question. Your function getline() has the same name as a function defined in the standard library stdio.h, which is why you're getting the error. Just change your function name.
The first one is faster because vector rendering mathematics are required to fill your shape in the latter.
If you want noticeable (and I mean very noticeable) performance gains, you should have one Bitmap on the stage. What you do from there is store references to BitmapData to represent graphics, and sample those onto your one Bitmap via .copyPixels().
Example:
// This is the only actual DisplayObject that will hit the Stage. var canvas:Bitmap = new Bitmap(); canvas.bitmapData = new BitmapData(500, 400); addChild(canvas); // Create some BitmapData and draw it to the canvas. var rect:BitmapData = new BitmapData(40, 40, false, 0xFF0000); canvas.bitmapData.copyPixels(rect, rect.rect, new Point(20, 20));
-7193708 0 You can currently find Hype or Pixelmator on the Mac App Store.
This proves evidently that you can save to disk and read from disk, which seems a basic feature of any serious application. Moreover, Apple is pushing developers to start using incremental auto-backups of files, it would therefore be very surprising if they forbade that in the App Store, wouldn't it?
-34448607 0 How to add attachments to mailto in c#?string email ="sample@gmail.com"; attachment = path + "/" + filename; Application.OpenURL ("mailto:" + email+" ?subject=EmailSubject&body=EmailBody"+"&attachment="+attachment); In the above code, attachment isn't working. Is there any other alternative to add attachments using a mailto: link in C#?
increasing the heap size
is the way to go. But you also have to check how to do a distribute test; because 12000 is a big test that can't be run only in one machine alone; it is not a good practice.
http://jmeter.apache.org/usermanual/jmeter_distributed_testing_step_by_step.pdf
-9978987 0You can have .net give the User's Userpath. Like "C:\Users\User\MyDocuments". Actually, that's what George's link is about. +1 for him.
-13372952 0Don't single quote your table name, if anything use magic quotes (`)
You should not be building the query by concatenating strings.
To avoid potential issues with SQL injection, it would be wise to use prepared queries.
I've just confirmed this on a mysql server
mysql> delete from 'sessions' where `last_activity` = 0; ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''sessions' where `last_activity` = 0' at line 1 mysql> delete from sessions where `last_activity` = 0; Query OK, 0 rows affected (0.00 sec)
-10628885 0 You are using PDO to interface with the database. Use PDO::lastInsertId() to get the last inserted id.
$stmt->execute(); echo 'last id was ' . $db->lastInsertId(); mysql_insert_id() is part of the ext/mysql extension. You cannot mix-match functions from both extensions to interface with the same connection.
ok let's say I have these two links
<script src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script> I'm using these as my javascript sources
and I created another file called
<script src="testing.js"></script> but in my html I want to show the script src="testing.js" I am able to somehow put the first two links into the testing.js file?
so in my html it'll only show
<script src="testing.js"></script> but actually it's running three scripts...
-24882173 0 Google Analitics : Send PageViews or Event with PHPI have an website who already use Google Analytics, but it' didn't send page view for Ajax action (a Dynamical search engine for exemple) i don't find an API to send it with PHP by server.
-36072700 0If you attach this script to Water particle, and you have a Fire particle, then in your water collision script
if (other.gameObject.name=="Fire") { Destroy(other.gameObject); // bonus effect for smoke particles // Instantiate(smokeObject, other.gameObject.transform.position, other.gameObject.transform.rotation); }
-37544765 0 sims like this plugin help you. For landscape you have to use screen.lockOrientation('landscape'); in controller. And on other page if they are not in portrait view you have to put screen.lockOrientation('portrait');
-10733956 01 million entries containing words shouldn't be slow if you have an index on the word column. This is because the words would be pretty short but with enough entropy (statistical dispersion) to leverage the key.
If this were 1 million phrases, comparing the phrases might have taken a bit longer and in order to optimise you could've broken the phrases down into the first 3 words (in different columns) and a column for the rest of the phrase with 4 column index over them.
Test the speed like this:
set_time_limit(60*60); $pdo = new PDO('mysql:host=localhost;dbname=db', 'user', 'pass'); $x = microtime(TRUE); for($i = 0; $i < 1000000; $i++) { $word = ''; for($j = 0; $j < mt_rand(0,40); $j++) { $word .= chr(97+mt_rand(0,25)); } if($_GET['select']) $pdo->query("SELECT FROM words WHERE word = '$word';"); else if($_GET['insert']) $pdo->exec("INSERT IGNORE INTO words (word) VALUES ('$word');"); } $x = microtime(TRUE)-$x; var_dump($x); CREATE TABLE IF NOT EXISTS `words` ( `word` varchar(40) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL, UNIQUE KEY `word` (`word`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; The speed I clocked on my laptop was initially 80.765522003174 seconds, and I've done 10 tests and the average is around 93.478111839294 seconds for the 1million select statements, meaning 1 tenth of a millisecond for each select.
Take into consideration the fact that I clocked it from PHP that means that the actual SQL execution speed is much higher, the 93.5 seconds include PHP communicating with MySQL over TPC.
I have inserted an extra 9million values into the table and tested the same script running 1million select statements against 10million values. The overall duration is around 52 seconds.
-2750176 0To do this in gedit, try the Tab Converter plugin.
(Don't think there's a way to do it directly in Rails.)
-20723602 0 Bind event handler to "console.log" JavaScript eventMy script sends text to the console output from several places in Javascript (see examples), how do I bind an event handler function to the log function itself so that a function is executed each time the event is triggered?
try { //some code } catch(e) { console.log("error: "+e) } function x(n) { //some code console.log(str) }
-7902765 0 You will have to parse the Expression that is returned from the Expression property on the IQueryable<T> implementation.
You'll have to query for the Queryable.Where method being called as you crawl the Expression tree.
Also note that while Queryable.Where is going to be the most common way to detect a where filter, query syntax allows for other implementations to be used (depending on what namespaces are used in the using directives); if you have something that is not using the Queryable.Where extension method then you'll have to look for that explicitly (or use a more generic method of filtering for a Where method that takes an IQueryable<T> and returns an IQueryable<T>).
The ExpressionVisitor class (as pointed out by xanatos) provides a very easy way of crawling the Expression tree, I highly recommend using that approach as a base for processing your Expression tree.
Of note is that ExpressionVisitor class implementations are required to store and expose state on the class level. Because of that, it would be best (IMO) to create internal classes that perform the action one-time and then have a public method which creates a new instance of the ExpressionVisitor every time; this will help with dealing with mutating state, and if done properly, will allow the method to be thread-safe as well (if that is a concern of yours).
I have this code
#include<stdio.h> int main(int argc, char * argv[]){ printf("%i\n", (int) *argv[1]) } when I execute compiled code with command ./a.out 6 it prints number 54, but I need exactly 6.
-12117441 0 RowNumber() and Partition By performance help wantedI've got a table of stock market moving average values, and I'm trying to compare two values within a day, and then compare that value to the same calculation of the prior day. My sql as it stands is below... when I comment out the last select statement that defines the result set, and run the last cte shown as the result set, I get my data back in about 15 minutes. Long, but manageable since it'll run as an insert sproc overnight. When I run it as shown, I'm at 40 minutes before any results even start to come in. Any ideas? It goes from somewhat slow, to blowing up, probably with the addition of ROW_NUMBER() OVER (PARTITION BY) BTW I'm still working through the logic, which is currently impossible with this performance issue. Thanks in advance..
Edit: I fixed my partition as suggested below.
with initialSmas as ( select TradeDate, Symbol, Period, Value from tblDailySMA ), smaComparisonsByPer as ( select i.TradeDate, i.Symbol, i.Period FastPer, i.Value FastVal, i2.Period SlowPer, i2.Value SlowVal, (i.Value-i2.Value) FastMinusSlow from initialSmas i join initialSmas as i2 on i.Symbol = i2.Symbol and i.TradeDate = i2.TradeDate and i2.Period > i.Period ), smaComparisonsByPerPartitioned as ( select ROW_NUMBER() OVER (PARTITION BY sma.Symbol, sma.FastPer, sma.SlowPer ORDER BY sma.TradeDate) as RowNum, sma.TradeDate, sma.Symbol, sma.FastPer, sma.FastVal, sma.SlowPer, sma.SlowVal, sma.FastMinusSlow from smaComparisonsByPer sma ) select scp.TradeDate as LatestDate, scp.FastPer, scp.FastVal, scp.SlowPer, scp.SlowVal, scp.FastMinusSlow, scp2.TradeDate as LatestDate, scp2.FastPer, scp2.FastVal, scp2.SlowPer, scp2.SlowVal, scp2.FastMinusSlow, (scp.FastMinusSlow * scp2.FastMinusSlow) as Comparison from smaComparisonsByPerPartitioned scp join smaComparisonsByPerPartitioned scp2 on scp.Symbol = scp2.Symbol and scp.RowNum = (scp2.RowNum - 1)
-5243226 0 The following code
is missing.
Anyway when I was using WatiN + Nunit + MSVS, I had this configuration in my testing project:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <sectionGroup name="NUnit"> <section name="TestRunner" type="System.Configuration.NameValueSectionHandler"/> </sectionGroup> </configSections> <NUnit> <TestRunner> <!-- Valid values are STA,MTA. Others ignored. --> <add key="ApartmentState" value="STA" /> </TestRunner> </NUnit> </configuration>
-36179545 0 I believe you need the scale_numeric argument with reverse = TRUE to flip the order of the range.
Below is an example based on the mtcars dataset.
library(ggvis) mtcars %>% ggvis(~wt, ~mpg) %>% layer_points() %>% add_axis("x", orient = "top") %>% scale_numeric("y", reverse = TRUE)
-12813644 0 First of all, A lot depends on with which controller is your UIViewController embedded in.
Eg, If its inside UINavigationController, then you might need to subclass that UINavigationController to override orientation methods like this.
subclassed UINavigationController (the top viewcontroller of the hierarchy will take control of the orientation.) needs to be set it as self.window.rootViewController.
- (BOOL)shouldAutorotate { return self.topViewController.shouldAutorotate; } - (NSUInteger)supportedInterfaceOrientations { return self.topViewController.supportedInterfaceOrientations; } From iOS 6, it is given that UINavigationController won't ask its UIVIewControllers for orientation support. Hence we would need to subclass it.
MOREOVER
Then, For UIViewControllers, in which you need only PORTRAIT mode, write these functions
- (BOOL)shouldAutorotate { return YES; } - (NSUInteger)supportedInterfaceOrientations { return (UIInterfaceOrientationMaskPortrait); } For UIViewControllers, which require LANDSCAPE too, change masking to All.
- (NSUInteger)supportedInterfaceOrientations { return (UIInterfaceOrientationMaskAllButUpsideDown); //OR return (UIInterfaceOrientationMaskAll); } Now, if you want to do some changes when Orientation changes, then use this function.
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { } VERY IMPORTANT
in AppDelegate, write this. THIS IS VERY IMP.
- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { return (UIInterfaceOrientationMaskAll); } If you want to provide only Portrait mode for all your viewcontrollers, then apply the portait mask. i.e UIInterfaceOrientationMaskPortrait
Otherwise, if you want that some UIViewControllers stay in Portrait while others support all orientations, then apply an ALL Mask. i.e UIInterfaceOrientationMaskAll
-15711073 0 Will the optimizer prevent the creation of a string parameter if a constant will prevent it from being used?My question is best made with an example.
public static boolean DEBUG = false; public void debugLog(String tag, String message) { if (DEBUG) Log.d(tag, message); } public void randomMethod() { debugLog("tag string", "message string"); //Example A debugLog("tag string", Integer.toString(1));//Example B debugLog("tag string", generateString());//Example C } public String generateString() { return "this string"; } My question is, in any of the examples, A, B or C - since the string would not be used ultimately would the optimizer remove it?
Or asked another way, would it be better to do the following, thus ensuring that the string objects would not be created?
public void randomMethod() { if (DEBUG) debugLog("tag string", "message string"); //Example A if (DEBUG) debugLog("tag string", Integer.toString(1));//Example B if (DEBUG) debugLog("tag string", generateString());//Example C }
-2555747 0 Another approach is to use amfphp library and thus send/receive data in Flash native AMF format which Flash can fast way faster.
-7504465 0 K2 is a Windows Server platform that allows the creation and management of business workflows that consume data from a variety of data sources; on top of the .Net platform. -31686204 0 Displaying a legend in a line chart using Telerik UI for XamarinHow can I display a legend in a line chart using Telerik's UI for Xamarin?
Is it possible to accomplish this without creating a customer renderer?
Thanks for the help,
Anthony
-5229744 0You have to use iTune to run a .ipa file. But iTunes can be used to run .ipa files on devices only.
-36773463 0 reactjs radio group setting checked attribute based on stateClicking on the second radio button changes the state which triggers the render event. However, it renders the first radio button as the checked one again even though state.type got changed.
var MyComponent = React.createClass({ getInitialState: function() { return { type: 1 }; }, render: function() { console.log('->> type: ' + this.state.type);//prints the expected value return (<div className="my-component"> <label>type 1</label> <input ref="type1Selector" type="radio" name="type" id="type1" onChange={this.changeHandler} checked={this.state.type === 1}/><br/> <label>type 2</label> <input ref="type2Selector" type="radio" name="type" id="type2" onChange={this.changeHandler} checked={this.state.type === 2}/><br/> </div>); }, changeHandler: function(e) { e.preventDefault(); var t = e.currentTarget; if(t.id === 'type1') { this.setState({type: 1}); } else { this.setState({type: 2}); } } }); ReactDOM.render(<MyComponent />, document.getElementById('container')); <!DOCTYPE html> <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react-with-addons.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react-dom.min.js"></script> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <div id="container"></div> </body> </html> Can someone tell how to get this to work and why react is behaving like this?
-7916554 0 Error 404 with file_get_contents on one server, on another it works fineI'm have a problem with file_get_contents() - on my old server everything works fine, on my new one it throw 404 error on some URLs I'm trying to get.
All the URLs are from the same website and in the same structure - but some gives me this message:
Warning: file_get_contents(http://url.com/path_to_file.html) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 404 Not Found in /home/user/domains/domain.com/public_html/tst.php on line 3 I have DirectAdmin with his basic configurations installed on the new server, while on the other I have cPanel
Someone know what's the problem could be?
Thanks.
-3805086 0A few canned answers from well known experts: Paul Nielsen Why use Stored Procedures?
Adam Machanic: No, stored procedures are NOT bad
-40725863 0gen.flow_from_directory gives you a generator. The images are not really generated. In order to get the images, you can iterate through the generator. For example
i = 0 for batch in gen.flow_from_directory(path+'train', target_size=(224,224), class_mode='categorical', shuffle=False, batch_size=batch_size, save_to_dir=path+'augmented', save_prefix='hi'): i += 1 if i > 20: # save 20 images break # otherwise the generator would loop indefinitely
-4011339 0 String ordinal(int num) { String[] suffix = {"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"}; int m = num % 100; return String.valueOf(num) + suffix[(m > 10 && m < 20) ? 0 : (m % 10)]; }
-11078616 0 Under Linux (and maybe some other unix-based operating systems), you can mount a formatted image file using the -o loop option of the mount command:
mount -o loop /path/to/image_file mount_point
-38923431 0 You should use reflection to get into relative path:
public static string PredictAbsoluteFilePath(string fileName) { return Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), fileName); } You can use it like this:
string path = Utils.PredictAbsoluteFilePath("relativeFile.xml"); //assuming that currect executing file is in D:\Programs\MyApp directory //path is now 'D:\Programs\MyApp\relativeFile.xml'
-7696001 0 How to create a incomming call broad receiver programatically I have managed to put a broadcast receiver from the manifest file, it looks like this:
<receiver android:name=".BReceivers.CallBReciever"> <intent-filter> <action android:name="android.intent.action.PHONE_STATE" /> </intent-filter> </receiver> Now what i am trying to do is to take it out of the manifest and start it only when the user presses a certain button, which should look somethings like this:
Button start = (Button) findViewById(R.id.Button_Start); start.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { @Override public void onReceive(Context context, Intent arg1) { Log.d("aaa", "bbb"); switch (getResultCode()) { } } }, new IntentFilter(Intent.ACTION_CALL)); } } }); But i don't get into the receiver, any idea why? what IntentFilter String param should i use?
-1308566 0elem.nextSibling.nodeValue.replace('\n', '') The replace is to get rid of the newline (may be different on different OSes, I am running Windows) character which is there for some reason.
-12072825 0I think converting the switch expression to unsigned type will do the trick.
switch((unsigned char)ent->d_name[i]) { ... }
-36229974 0 When I follow the link given in terminal it also gives directs me to a blank page. But if I copy and paste the link into my browser it works fine. Dont know what is happening there...
[Stack: OSX, Google Chrome, Python 3, TensorFlow installed via pip]
Ps. I would/should have commented on, not answered, this question. But my reputation is too low.
-41057455 0First of all, create a base SLES image. Luckily for you, this process is [semi]automated by SUSE through the utility called sle2docker. A manual can be found here: https://www.suse.com/documentation/sles-12/book_sles_docker/data/cha_sle2docker_installation.html https://github.com/SUSE/sle2docker
Then you should run your container, install and setup your custom software and do docker commit to create you personal customized image. https://docs.docker.com/engine/tutorials/dockerimages/
[EDIT: Irrelevant suggestion about SQLite 3.7.11 removed]
You could use insert-select with the user id as a literal:
INSERT OR IGNORE INTO messages_seen (message_id, user_id) SELECT message_id, 4 FROM messages WHERE mb_topic_id = 7
-20865945 0 You may have to do this with the beforeRender() function.
These links may help.
http://www.yiiframework.com/wiki/249/understanding-the-view-rendering-flow/
http://www.yiiframework.com/wiki/54/
-12989085 0I've solved the problem setting a ScrollView as parent layout.
-22918592 0 ∞ not displaying inside span tagI am currently having an issue with getting any HTML entity to display while inside a span. I am currently trying to get ∞ to show up if my object has no destroy date. If I move the entity outside the span it will appear. Below is the code before it is rendered:
<tr> <th> Deactivate Date </th> <td> <span edit> <%= text_field_tag 'destroy_date', @account_type.destroy_date %> </span> <span show> <%= @account_type.destroy_date.present? ? @account_type.destroy_date : '∞'.html_safe %> </span> </td> </tr> Here is how the code is rendered if @account_types.destroy_date is not present.
<tr> <th> Deactivate Date </th> <td class="clickable"> <span edit="" style="display: none;"> <input id="destroy_date" name="destroy_date" type="text" last-value="" class="hasDatepicker"> </span> <span show="" style="display: inline-block;"> </span> </td> </tr>
-4675924 0 The first thing I notice is that you've got a lot of functions that do basically the same thing (with some numbers different). I would investigate adding a couple of parameters to that function, so that you can describe the direction you're going. So for example, instead of calling right() you might call traverse(1, 0) and traverse(0, -1) instead of up().
Your traverse() function declaration might look like:
int traverse(int dx, int dy) with the appropriate changes inside to adapt its behaviour for different values of dx and dy.
If I understood your requirements correctly, you can first let your lambda functor accept an argument of the appropriate type (passing by reference here, so take care of lifetime issues):
doSomething([](QNetworkReply* p) { // Here you have the sender referenced by p }); Then, your doSomething() template function could use std::bind() to make sure your lambda will be invoked with the appropriate object as its argument:
template<typename Functor> void MyClass::doSomething(Functor f) { connect(network_reply, &QNetworkReply::finished, bind(f, network_reply)); //... }
-39054962 0 I have solved the problem. It turned out I had to add one line in my NotificationHub class:
[HubName("notificationHub")] Now it looks following and this solved my problem.
[HubName("notificationHub")] public class NotificationHub : Hub { //public void Hello() //{ // Clients.All.hello(); //} }
-26907803 0 replace log4j with slf4j in hybris I am wandering if there is an elegant way to change logging in hybris from log4j to slf4j or something else?
Right now I am using slf4j when writing java code, but hybris itself is using log4j for any generated code. That is causing to use mixed logging frameworks in one hybris extension. Actually it is still log4j underneath the slf4j, but what if I want to change log4j to some other logging mechanism?
Maybe it can be done in some configuration file. Has anybody done that already?
-24274584 0 How do I match lines consisting *only* of four digits and remove lines in betweeen two regexp matches?I need to process a file consisting of records like the following:
5145 Xibraltar: vista xeral do Peñón 1934, xaneiro, 1 a 1934, decembro, 31 -----FOT-5011-- Nota a data: extraída do listado de compra. 5146 Xixón: a praia de San Lorenzo desde o balneario ca.1920-1930 -----FOT-3496-- 5147 Xixón: balneario e praia de San Lorenzo ca.1920-1930 Tipos de unidades de instalación: FOT:FOT -----FOT-3493-- I need to remove the 1 to 4 digits record number (i.e.: 5145) and any notes such as "Nota a data: extraída do listado de compra" which always come at the end of the record, after the signature (-----FOT-xxxx--) and before the next record's record number.
I've been trying to write an awk program to do this but I don't seem to be able to grasp awk's syntax or regular expressions at all.
Here's my attempt to match record numbers, those lines consisting of 1 to 4 digits only. (I think I'm missing the "only" part).
$ gawk '!/[[:digit:]]{1,4}/ { print $0 }' myUTF8file.txt Also, I can match these (record signatures):
$ gawk '/-----FOT-[[:digit:]]{4}--/ { print $0 }' myUTF8file.txt -----FOT-3411-- -----FOT-3406-- -----FOT-3397-- -----FOT-3412-- ... but I don't know how to remove the lines in between those and the record numbers.
Excuse my English and my repeated use of the word record, which I know might be confusing given the topic.
-9691123 0 HTTPBuilder is a wrapper for Apache's HttpClient, with some (actually, a lot of) Groovy syntactical sugar thrown on top. The request/response model is also inspired by Prototype.js' Ajax.Request. -15507314 0 Using Javascript on the Content of an iframeI have a page with some tabbed content on it. A couple of the tabs contain iframes and I use a handy little script to resize the iframes to suit their content. It's
function autoResize(id){ var newheight; if(document.getElementById){ newheight=document.getElementById(id).contentWindow.document.body.scrollHeight; } newheight=(newheight)+40; // Makes a bit of extra room document.getElementById(id).height= (newheight) + "px"; } Today I have added a little jQuery script to stop the tabbed area showing until it is fully loaded. This stops the tabs doing an unsightly little jump when the loading is complete. This is the script:
$(document).ready(function(){ $("#tabber").hide(); $("#loading").hide(); $("#loading").fadeIn(1000); }); $(window).load(function(){ $("#loading").hide(); $("#tabber").fadeIn(300); }); The loading div contains a loading icon and the tabber div is the entire content of the tabbed area.
This script is also stopping the iframe resizing working. In order to understand it better I added another script:
function checkResize(id){ var win=document.getElementById(id).contentWindow.document.body.scrollHeight; alert(win); Sure enough, "win" comes up as zero. If I delete the $("#tabber").hide() line, "win" shows a sensible number for the height of the iframe.
Is there another way of making the two things compatible?
Vlad produced the solution: I had to use the jQuery version of visibility=hidden instead of the jQuery version of display:none. That doesn't actually exist in jQuery so I found out from another StackOverflow question how to write my own functions to do it.
The final script is
(function($) { $.fn.invisible = function() { return this.each(function() { $(this).css("visibility", "hidden"); }); }; $.fn.visible = function() { return this.each(function() { $(this).css("visibility", "visible"); }); }; }(jQuery)); $(document).ready(function(){ $("#tabber").invisible(); $("#loading").hide(); $("#loading").fadeIn(1000); }); $(window).load(function(){ $("#loading").hide(); $("#tabber").visible(); }); My thanks to Vlad, and also RAS, for taking the trouble to look at my question and give their ideas.
-5672156 0You can use the Java library from here: http://www.johannes-raida.de/jnetcad. As far as I can see, it should support JT version 8 files. I used the DXF import library and was quite happy. The API is the same, so you have access to all triangles with their coordinates, normals, color and layer.
-26010679 0 Not able to load all the youtube iframe players on same page. Always loads the last oneMy base Html
<div class="ytplayer" id="player1" data-videoid="xxxxxxx" data-playerheight="390" data-playerwidth="640"></div> <div class="ytplayer" id="player2" data-videoid="xxxxxxx" data-playerheight="390" data-playerwidth="640"></div> <div class="ytplayer" id="player3" data-videoid="xxxxxxx" data-playerheight="390" data-playerwidth="640"></div> My script initialization is
$(document).ready(function(){ $(".ytplayer")._loadIFramePlayer(); }); my functions look like
_loadIFramePlayer: function(){ $("<script>") .attr("src", "//www.youtube.com/iframe_api") .insertBefore($("body").find("script").first()); var _youtubePlayer = null; if (typeof (YT) === 'undefined' || typeof (YT.Player) === 'undefined') { window.onYouTubeIframeAPIReady = function () { _youtubePlayer = new YT.Player("player", { height: "390", width: "640", videoId: "xxxxxx", events: { // i didn't mention the below functions since I am not doing any thing there, just calling stopVideo and playVideo native functions of youtube api. 'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange } }); }; $.getScript('//www.youtube.com/iframe_api'); } else { _youtubePlayer = new YT.Player("player", { height: "390", width: "640", videoId: "xxxxxx", events: { // i didn't mention the below functions since I am not doing any thing there, just calling stopVideo and playVideo native functions of youtube api. 'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange } }); } } Ideally we should get three instances of iframe player but in our case we are getting only one player that too the last one in all cases. Please let me know if any work around for this ..
-18118669 0Use this...
image { width: 100px; height: auto; } Of course you can do <img src="src" style="width:100px; height:auto;"> and changed width and height to 100px accordingly.
I believe you are looking for ]] which jumps to the next { char on the first column.
There are similar options, just try :help ]] for more information.
you can use the series configuration option to change the targetAxisIndex
the documentation says...
targetAxisIndex: Which axis to assign this series to, where 0 is the default axis, and 1 is the opposite axis. Default value is 0; set to 1 to define a chart where different series are rendered against different axes. At least one series much be allocated to the default axis. You can define a different scale for different axes.
but seems to work without assigning anything to the default axis...
see following example...
google.charts.load('current', { callback: function () { var data = new google.visualization.DataTable(); data.addColumn('string', 'Label'); data.addColumn('number', 'Amount'); data.addRows([ ['Label 1', 10], ['Label 2', 20], ['Label 3', 30], ['Label 4', 40] ]); new google.visualization.LineChart(document.getElementById('chart_div')).draw(data, { series: { 0: { targetAxisIndex: 1 } } }); }, packages:['corechart'] }); <script src="https://www.gstatic.com/charts/loader.js"></script> <div id="chart_div"></div> if you changed your package name you have also to change it in the AndroidManifest.xml
You can copy paste your project on your disk and on your project on eclipse right click on your package and go to refactor --> rename
-23717319 0You have a syntax error in your code: .navbar ul li a: hover Remove the space after the : and it will work.
I'm just getting into coding and put together a webpage using dreamweaver. I created a php page with my email coding which is executed from a form and submit button on an html page. I continously recieve blank emails on a daily basis which apparently means I need to add validation coding. I tried adding the coding but the problem persists. The page still submits even if the form is blank.
Below is my current coding.
<?php if(!filter_var($_POST['CustomerEmail'], FILTER_VALIDATE_EMAIL)) { $valerrors[] = "The email address you supplied is invalid." ;} $customeremail=$_POST['CustomerEmail']; $email='test@gmail.com'; $custfirst=$_POST['CustomerFirstName']; $custlast=$_POST['CustomerLastName']; $custphone=$_POST['CustomerNumber']; $custaddress=$_POST['CustomerAddress']; $custcity=$_POST['CustomerCity']; $custstate=$_POST['CustomerState']; $custrequest=$_POST['CustomerService']; $subject='Service Request'; $body = <<<EOD <br><hr><br> Email: $customeremail <br> First Name: $custfirst <br> Last Name: $custlast <br> Phone: $custphone <br> Address: $custaddress <br> City: $custcity <br> State: $custstate <br> Request: $custrequest <br> EOD; $headers = "From: $customeremail\r\n"; $headers .= "Content-type: text/html\r\n"; $Send = mail($email, $subject, $body, $headers); $confirmation = <<<EOD <html>"Thanks for Submitting."</html> EOD; echo"$confirmation"; ?> It's possible that I'm placing the if statement in the wrong place. Can someone correct my coding so the confirmation page will not load and the email will not be sent if the customer email is left blank?
-10441567 0 JSP download from intranetI need to read binary file from intranet http server and get it to download to public.
SCHEMA
intranet file server(Apache)=1 <-->Public http server(Apache Tomcat)=2<-->internet authorized user=3
howto release this without save to filesystem on server 2
Thanks for answers i am new on java.
Sorry for my English.
-36945788 0 Getting Google API Push Notifications for Resources/RoomsI'm trying to get Google Calendar Push Notifications working for Resources (aka Rooms). They work perfectly for user calendars, but when I call/watch on a Resource, it successfully creates. I get the initial "Sync" call on the server, but then I never hear back from Google again.
My approach to creating the watch is to authenticate an administrator, and use that Token to add the watch on the resource that the administrator had added as a calendar to his list, so it's showing up in the calendarList/list call. I've also turned on all notifications on the admin's account for that calendar.
Any idea on what I might be doing wrong?
-19130036 0 Text reaching over the specified width of its DIVEDIT: Another image to further showcase my issue:
http://imageshack.us/photo/my-images/405/cvtc.png/
I know this question has been asked but every solution I have tried has not worked, i.e.: word-wrap, text-wrap, overflow-wrap.
I have text that I have measure to be 344px in width, and would like the rest of my texts to meet that boundary and/or not flow over it. I keep setting this specified width of 344 or even less and this last set of text especially is just causing issues. Here is a screen shot of the issue as well as my HTML and CSS. Any help is appreciated!

HTML
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>Jessica ___: PORTFOLIO</title> <link rel="stylesheet" type="text/css" href="style1.css"> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript" src="jquery.lettering.js"></script> <link href='http://fonts.googleapis.com/css?family=Quicksand:300,400,700' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Playfair+Display:700italic' rel='stylesheet' type='text/css'> </head> <body> <div id="letter-container" class="letter-container"> <div id="heading">HELLO</div> <div id="aboutintro">My name is</div> <div id="name">jessica ___</div> <div id="aboutbody">and I'm a student at the College of Design, Architecture, Art, and Planning of the University of Cincinnati and I like to design websites and take pictures.</div> </div> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script type="text/javascript" src="jquery.lettering.js"></script> <script type="text/javascript"> $(function() { $("#heading").lettering(); }); </script> <script type="text/javascript"> $(function(){ $("#aboutintro").delay(4000).fadeIn(500); }); </script> <script type="text/javascript"> $(function() { $("#name").lettering(); }); </script> <script type="text/javascript"> $(function(){ $("#aboutbody").delay(6000).fadeIn(500); }); </script> </div> </body> </html> CSS
@charset "UTF-8"; /* CSS Document */ html { background: url(grungebg.png) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; margin:0; padding:0; } @font-face { font-family: 'league_gothicregular'; src: url('leaguegothic-regular-webfont.eot'); src: url('leaguegothic-regular-webfont.eot?#iefix') format('embedded-opentype'), url('leaguegothic-regular-webfont.woff') format('woff'), url('leaguegothic-regular-webfont.ttf') format('truetype'), url('leaguegothic-regular-webfont.svg#league_gothicregular') format('svg'); font-weight: normal; font-style: normal; } .letter-container { margin-left:auto; margin-right:auto; width:344px; text-align:center; } #heading { font-family: league_gothicregular, sans-serif; } #heading span { font-size: 200px; background-image: url(mask.png); -webkit-background-clip: text; background-clip: text; color: rgba(0,0,0,0); -webkit-text-fill-color: transparent; -webkit-transition: all 0.3s linear; -moz-transition: all 0.3s linear; -o-transition: all 0.3s linear; -ms-transition: all 0.3s linear; transition: all 0.3s linear; -webkit-animation: sharpen 0.6s linear backwards; -moz-animation: sharpen 0.6s linear backwards; -ms-animation: sharpen 0.6s linear backwards; animation: sharpen 0.6s linear backwards; } #heading span:nth-child(1) { -webkit-animation-delay: 2.2s; -moz-animation-delay: 2.2s; -ms-animation-delay: 2.2s; animation-delay: 2.2s; } #heading span:nth-child(2) { -webkit-animation-delay: 2.6s; -moz-animation-delay: 2.6s; -ms-animation-delay: 2.6s; animation-delay: 2.6s; } #heading span:nth-child(3) { -webkit-animation-delay: 2.9s; -moz-animation-delay: 2.9s; -ms-animation-delay: 2.9s; animation-delay: 2.9s; } #heading span:nth-child(4) { -webkit-animation-delay: 2.4s; -moz-animation-delay: 2.4s; -ms-animation-delay: 2.4s; animation-delay: 2.4s; } #heading span:nth-child(5) { -webkit-animation-delay: 3s; -moz-animation-delay: 3s; -ms-animation-delay: 3s; animation-delay: 3s; } #heading span:nth-child(6) { -webkit-animation-delay: 2.7s; -moz-animation-delay: 2.7s; -ms-animation-delay: 2.7s; animation-delay: 2.7s; } } @keyframes sharpen { 0% { opacity: 0; text-shadow: 0px 0px 100px #fff; color: transparent; } 90% { opacity: 0.9; text-shadow: 0px 0px 10px #fff; color: transparent; } 100% { color: #fff; opacity: 1; text-shadow: 0px 0px 2px #fff, 1px 1px 4px rgba(0,0,0,0.7); } } @-moz-keyframes sharpen { 0% { opacity: 0; text-shadow: 0px 0px 100px #fff; color: transparent; } 90% { opacity: 0.9; text-shadow: 0px 0px 10px #fff; color: transparent; } 100% { color: #fff; opacity: 1; text-shadow: 0px 0px 2px #fff, 1px 1px 4px rgba(0,0,0,0.7); } } @-webkit-keyframes sharpen { 0% { opacity: 0; text-shadow: 0px 0px 100px #fff; color: transparent; } 90% { opacity: 0.9; text-shadow: 0px 0px 10px #fff; color: transparent; } 100% { color: #fff; opacity: 1; text-shadow: 0px 0px 2px #fff, 1px 1px 4px rgba(0,0,0,0.7); } } @-ms-keyframes sharpen { 0% { opacity: 0; text-shadow: 0px 0px 100px #fff; color: transparent; } 90% { opacity: 0.9; text-shadow: 0px 0px 10px #fff; color: transparent; } 100% { color: #fff; opacity: 1; text-shadow: 0px 0px 2px #fff, 1px 1px 4px rgba(0,0,0,0.7); } } #aboutintro { font-family: 'Quicksand', sans-serif; font-size:65px; font-weight:300; color:white; display:none; } #name{ font-family: 'Playfair Display', serif; font-size:65px; font-weight:700; font-style:italic; background-image: url(mask.png); -webkit-background-clip: text; background-clip: text; color: rgba(0,0,0,0); -webkit-text-fill-color: transparent; -webkit-transition: all 0.3s linear; -moz-transition: all 0.3s linear; -o-transition: all 0.3s linear; -ms-transition: all 0.3s linear; transition: all 0.3s linear; -webkit-animation: sharpen 0.6s linear backwards; -moz-animation: sharpen 0.6s linear backwards; -ms-animation: sharpen 0.6s linear backwards; animation: sharpen 0.6s linear backwards; -webkit-animation-delay: 5s; -moz-animation-delay: 5s; -ms-animation-delay: 5s; animation-delay: 5s; text-align:center; } } @keyframes sharpen { 0% { opacity: 0; text-shadow: 0px 0px 100px #fff; color: transparent; } 90% { opacity: 0.9; text-shadow: 0px 0px 10px #fff; color: transparent; } 100% { color: #fff; opacity: 1; text-shadow: 0px 0px 2px #fff, 1px 1px 4px rgba(0,0,0,0.7); } } @-moz-keyframes sharpen { 0% { opacity: 0; text-shadow: 0px 0px 100px #fff; color: transparent; } 90% { opacity: 0.9; text-shadow: 0px 0px 10px #fff; color: transparent; } 100% { color: #fff; opacity: 1; text-shadow: 0px 0px 2px #fff, 1px 1px 4px rgba(0,0,0,0.7); } } @-webkit-keyframes sharpen { 0% { opacity: 0; text-shadow: 0px 0px 100px #fff; color: transparent; } 90% { opacity: 0.9; text-shadow: 0px 0px 10px #fff; color: transparent; } 100% { color: #fff; opacity: 1; text-shadow: 0px 0px 2px #fff, 1px 1px 4px rgba(0,0,0,0.7); } } @-ms-keyframes sharpen { 0% { opacity: 0; text-shadow: 0px 0px 100px #fff; color: transparent; } 90% { opacity: 0.9; text-shadow: 0px 0px 10px #fff; color: transparent; } 100% { color: #fff; opacity: 1; text-shadow: 0px 0px 2px #fff, 1px 1px 4px rgba(0,0,0,0.7); } } #aboutbody { font-family: 'Quicksand', sans-serif; font-size:12px; font-weight:400px; color:#e5e5e5; display:none; margin-left:auto; margin-right:auto; padding:0; margin:0; }
-7126722 0 For purpose of EF linq query, is First(c=>cond) equiv to Where(c=>cond).First()? Is there any hidden subtlety, is one perferred, or is one just a shorter way to write the other?
Client = db.Clients.First(c=>c.Name == "Client 1") and
Client = db.Clients.Where(c=>c.Name == "Client 1").First()
-33727457 0 What time format is this: 38793.20139 This data is from scientific tracking data. What is this date format:
38793.20139
I have looked through all of the stackoverflow datetime format entries I could find.
-34701508 0You have the fade backwards
$(".btn--alt").hover( function () { $("#please").fadeOut(); }, function () { $("#please").fadeIn(); } ); See this example:
-26070327 0Here's an easy way to do it, using the fact that on the lines in question, if your file follows the same format then the numbers will always appear in the same character of the line. This is a little bit fragile, and it'd be better to make your program more robust, to cope with arbitrary amounts of whitespace, for instance, but I'll leave that as an exercise to you:
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_LEN 100 #define BUY_LEN 9 #define AWARD_LEN 11 int main(void) { FILE * infile = fopen("file.dat", "r"); if ( !infile ) { perror("couldn't open file"); return EXIT_FAILURE; } char buffer[MAX_LEN]; char * endptr; while ( fgets(buffer, MAX_LEN, infile) ) { if ( !strncmp(buffer, "BUY ITEM ", BUY_LEN ) ) { char * num_start = buffer + BUY_LEN; long item = strtol(num_start, &endptr, 0); if ( endptr == num_start ) { fprintf(stderr, "Badly formed input line: %s\n", buffer); return EXIT_FAILURE; } printf("Bought item %ld\n", item); } else if ( !strncmp(buffer, "AWARD ITEM ", AWARD_LEN) ) { char * num_start = buffer + AWARD_LEN; long item = strtol(num_start, &endptr, 0); if ( endptr == num_start ) { fprintf(stderr, "Badly formed input line: %s\n", buffer); return EXIT_FAILURE; } printf("Awarded item %ld\n", item); } } fclose(infile); return 0; } Running this with the sample data file in your question, you get:
paul@local:~/src/sandbox$ ./extr Bought item 8 Bought item 10 Awarded item 7 Bought item 1 Bought item 3 Awarded item 9 Bought item 7 paul@local:~/src/sandbox$ Incidentally, based on one of the suggestions in your question, you might want to check out the answers to the question "while( !feof( file ) )" is always wrong.
I have this Food class with 20 properties. I need to use this Food class and output 3 different files, using variations of these 20 fields. For example, File 1 contains output only 8 fields. File 2 contains 15 fields. File 3 contains 18 fields.
So right now, I have these 3 separate methods.
FoodService() { void WriteRecommendedFood(IList<Food> foodList); void WriteRecommendedFoodCalculation(IList<Food> foodList); void WriteRecommendedFoodAllEligibleFoods(IList<Food> foodList); } So I'd write:
public void WriteRecommendedFood(IList<Food> foodList) { using (StreamWriter sw = new StreamWriter("file.csv", false) { StringBuilder sb = new StringBuilder(); foreach (Food f in foodList) { sb.Append(f.Field1); //Repeat for the # of fields I want to spit out sb.Clear(); sw.WriteLIne(sb.ToString()); } sw.Close(); } } I feel like I'm writing the same code three times (with slight variations). I started to read up on different design patterns like Visitor and Strategy pattern, but I'm not sure which design pattern to improve my code. (Note: I only need to output it to a comma delimited file at this time. Also, from the UI side, the user gets to select which one they want to output (either one to all 3 files.) Any suggestions?
-15608831 0You can set the NSWorkspaceDesktopImageScalingKey in the option parameter. Here's the possible values:
NSImageScaleProportionallyDown
If it is too large for the destination, scale the image down while preserving the aspect ratio.
NSImageScaleAxesIndependently
Scale each dimension to exactly fit destination. This setting does not preserve the aspect ratio of the image.
NSImageScaleNone
Do not scale the image.
NSImageScaleProportionallyUpOrDown
Scale the image to its maximum possible dimensions while both staying within the destination area and preserving its aspect ratio.
Declared in NSCell.h.
-36602276 0I have found more flexible solution. I have created xlsx file which will be updated once per week with exactly measured cities. My script will read that xlsx file and pull cities from that. On that way I am avoiding empty printed pdf pages. Thanks all!
-33236419 0$( "input" ).keyup(function() { //It's changed }); Easy way to track any change in anywhere... Many framework with 2 ways data binding, use keyup in Javascript to $watch the changes...
Also jQuery UI date-picker has onSelect...So easy way to do ur job... look at https://jqueryui.com/datepicker for more information...
-25144180 0Your issue is with attempting to change your month by adding 1. 1 in date serials in Excel is equal to 1 day. Try changing your month by using the following:
NewDate = Format(DateAdd("m",1,StartDate),"dd/mm/yyyy")
-28952453 0 If you are using Laravel 5, you can do it like this (I am not sure if it is the best way)
return view("layout/here", [ "content" => view("dynamic/content/here") ]); then in your view you can do this
<?php echo $content; ?> of course, if you are not using blade.
-15754009 0Edit: I updated the code to work better.
I'm unsure exactly what the issue is but looking at your code I wouldn't be surprised that the negative look behind regex isn't matching multiple word strings where the "keyword" is not the first word after the src or alt. It might possible to beef up the regex, but IMHO a complicated regex might be a little too brittle for your html parsing needs. I'd recommend doing some basic html parsing yourself and doing a simple string replace in the right places.
Here's some basic code. There is certainly a much better solution than this, but I'm not going to spend too much time on this. Probably, rather than inserting html in a text node, you should create a new html a element with the right attributes. Then you wouldn't have to decode it. But this would be my basic approach.
$text = "Lorem ipsum <img src=\"lorem ipsum\" alt=\"dolor sit amet\" /> dolor sit amet"; $result = array( array('keyword' => 'lorem', 'link' => 'http://www.google.com'), array('keyword' => 'ipsum', 'link' => 'http://www.bing.com'), array('keyword' => 'dolor sit', 'link' => 'http://www.yahoo.com'), ); $doc = new DOMDocument(); $doc->loadHTML($text); $xpath = new DOMXPath($doc); foreach($result as $row) { if (!empty($row['keyword'])) { $search = $row['keyword']; $replace = '<a href="'.$row['link'].'.html" class="ared">'.$row['keyword'].'</a>'; $text_nodes = $xpath->evaluate('//text()'); foreach($text_nodes as $text_node) { $text_node->nodeValue = str_ireplace($search, $replace, $text_node->nodeValue); } } } echo html_entity_decode($doc->saveHTML()); The $result data structure is meant to be similar to result of your mysql_fetch_array(). I'm only getting the children of the root for the created html DOMDocument. If the $text is more complicated, it should be pretty easy to traverse more thoroughly through the document. I hope this helps you.
The problem you face is that you wish to go to the bottom of your page which has not loaded yet. I would consider loading the page in a hidden format then show it when it has all loaded and after scrolling the user at the location you want. Use the focus or scroll to methods.
Take a look at the filament group website.
they hide the page with a loading screen until it is ready.
This way there is no jerk.
Hope this helps.
-23808539 0Re : 'how' is this used - one place we are finding this useful is when dealing with java api mappings where null is commonplace, e.g. on jdbc prepared statements to nullable sql columns. The Optional internal model fields can be mapped:
stmt.setDate("field", myModel.myDateField.orNull) Instead of the more verbose:
stmt.setDate("field", myModel.myDateField.getOrElse(null))
-27035659 0 view state MAC validation failed I made one web application in asp.net. It works fine but some time it shows the error Validation of view state MAC failed. After refreshing the page all works fine. This error comes at least once in a day. Can any one please help.
-38015203 0Starting from iOS 10, it's mandatory to add "NSCameraUsageDescription" in info.plist which is just an informatory message to the user stating the reason for accessing camera. It will be displayed to the user while trying to access the camera.
Though this key is existing since iOS 7, it has been made mandatory in iOS 10 beta. Please refer to below Apple reference link.
-27023669 0That's not the strict solution to the issue.
What's happening is that you have only one server block and it becomes the default server block for all requests, even the ones not matching the server name. You simply need to add a default server block in your configuration :
server { listen 80 default_server; } By the way, you have a typo (semicolon before permanent) and you don't need a rewrite as you have specific regular expression. Use this instead :
return 301 http://www.example.net$request_uri;
I have a model which consists of two ForeignKeys. I am only interested in parsing the content of the ForeignKeys, so i'm using the depth variable, which basically gives me all columns of the tables referenced with the FK. Is there a way to select which columns there should be included?
class SomeSerializer(serializers.ModelSerializer): class Meta: model = MyAwesomeModel fields = ('id', 'fk_one','fk_two') depth = 1
-25997467 0 Ajax is not updating data I've got a forum in which user is allowed to edit and delete only his comments, I've defined an "edit" button, that by a click of mouse brings down a modal, and in that modal user is allowed to get access to the data's he/she has been sent before, I've written an ajax to target these field and update them whenever the users clicks on "edit" button, code totally makes sense, but so far the functionality doesn't, to make it more clear, user clicks, modal comes down, whatever he/she has been posted will appear in fields, and there is an "edit" button at the bottom of modal, which is responsible for changing and updating data. here is the modal code :
<button id="btn-btnedit" class="btn btn-primary " data-toggle="modal" data-target="#myModal<?php echo $list['id']; ?>"> Edit <i class="fa fa-pencil-square-o"></i> </button> <!-- Modal --> <div class="modal fade" id="myModal<?php echo $list['id']; ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button> <h4 class="modal-title" id="myModalLabel">Modal title</h4> </div> <div class="modal-body"> <div class="container"> <form style="width: 550px;" action="" method="post" id="signin-form<?php echo $list['id']; ?>" role="form"> <input type="hidden" name="commentID" value="<?php echo $list['id']; ?>"> <div class="from-group"> <label for="title">Title: </label> <input class="form-control" type="text" name="title" id="txttitle" value="<?php echo $list['title']; ?>" placeholder="Page Title"> </div> <div class="from-group"> <label for="label">Label: </label> <input class="form-control" type="text" name="label" id="txtlabel" value="<?php echo $list['label']; ?>" placeholder="Page Label"> </div> <br> <div class="from-group"> <label for="body">Body: </label> <textarea class="form-control editor" name="body" id="txtbody" row="8" placeholder="Page Body"><?php echo $list['body']; ?></textarea> </div> <br> <input type="hidden" name="editted" value="1"> <br> <br> <input type="submit" id="btnupdate" value="Edit"> </form> </div> </div> as you can see I've assigned "editted" to my "name" attribute, which is later on used to call the query in the database, sql code is as below :
case 'postupdate'; if(isset($_GET['editted'])){ $title = $_GET['title']; $label = $_GET['label']; $body = $_GET['body']; $action = 'Updated'; $q = "UPDATE posts SET title ='".$title."', label = '".$label."', body = '".$body."' WHERE id = ".$_GET['commentID']; $r = mysqli_query($dbc, $q); $message = '<p class="alert alert-success"> Your Post Is Succesfully '.$action.'</p>' ; } and here is the ajax code snippet;
$('#btnupdate').click(function() { var tempTitle = $('#txttitle').val(); var tempLabel = $('#txtlabel').val(); var tempBody = $('#txtbody').val(); var tempUrl = "index.php?page=postupdate"+"&title="+tempTitle+"&label="+tempLabel+"&body="+tempBody+"&commentID=30&editted=1"; $.get(tempUrl); }); I assume there is nothing advance about this segment of code, and i'm missing something very simple, any consideration is highly appreciated :)
-29704404 0Maybe you need:
$.ajax({ url: "test.html", error: function(){ // will fire when timeout is reached }, success: function(){ //do something }, timeout: 3000 // sets timeout to 3 seconds }); [READ] http://api.jquery.com/jQuery.ajax/
You can specify the timeout as a property.
-4998548 0Yes. The current working directory is a property of the process.
To expand on that a little - here are a couple of the relevant POSIX definitions:
The current working directory is defined as "a directory, associated with a process, that is used in pathname resolution for pathnames that do not begin with a slash character" (there is more detail in the section on pathname resolution).
chdir() is defined to set the current working directory to a pathname.
It seems somewhat circular, but there is nothing special about a "pathname" in the context of the argument chdir(); it is subject to pathname resolution as normal.
There's several ways, but this is the simplest given what you are doing:
$(document).on("click", "ul.form-nav a", function(event) { event.preventDefault(); var id = event.target.href.replace(/^[^#]+/, ""); console.log("Going to: " + id); // Hide forms that do not have the selected id $('form.hidden').not(id).hide(); // Show the appropriate form $(id).show().focus(); }); View the Fiddle
-3433282 0 How is Java's for loop code generated by the compilerHow is Java's for loop code generated by the compiler?
For example, if I have:
for(String s : getStringArray() ) { //do something with s } where getStringArray() is a function that returns the Array I want to loop on, would function be called always or only once? How optimal is the code for looping using this construct in general?
A couple ideas:
Sometimes this can happen if there are oddities with your system clock or modified dates on the files. Try resetting the modified date. Maybe the easiest way is by zipping up the project, then extracting over top. Also of course delete your .suo and .ncb files.
Make sure the .h file is IN the project tree. If it's #included, but not specifically in the project tree, I don't believe VS will recognize changes always.
Change the following line:
return view('welcome')->withRestaurants($restaurants); // there is nothing like withRestaurants in laravel to
return view('welcome', array('restaurants' => $restaurants)); and try again.
-21213935 0 How to select object in muti level arrayI am attempting to get just the smiling array under tags then attributes. I have tried both to search and simply select. Every attempt results in an undefined variable. If you could explain how to select the smiling array that would be excellent!
{ "status": "success", "photos": [{ "url": "http://tinyurl.com/673cksr", "pid": "F@019cbdb135cff0880096136c4a0b9bad_3547b9aba738e", "width": 375, "height": 406, "tags": [{ "uids": [], "label": null, "confirmed": false, "manual": false, "width": 30.67, "height": 28.33, "yaw": -16, "roll": -1, "pitch": 0, "attributes": { "face": { "value": "true", "confidence": 84 }, "smiling": { "value": "false", "confidence": 46 } }, "points": null, "similarities": null, "tid": "TEMP_F@019cbdb135cff0880096136c00d500a7_3547b9aba738e_56.80_41.13_0_1", "recognizable": true, "center": { "x": 56.8, "y": 41.13 }, "eye_left": { "x": 66.67, "y": 35.71, "confidence": 51, "id": 449 }, "eye_right": { "x": 50.67, "y": 35.47, "confidence": 57, "id": 450 }, "mouth_center": { "x": 60.8, "y": 51.23, "confidence": 53, "id": 615 }, "nose": { "x": 62.4, "y": 42.61, "confidence": 54, "id": 403 } }] }], "usage": { "used": 21, "remaining": 79, "limit": 100, "reset_time": 1390111833, "reset_time_text": "Sun, 19 January 2014 06:10:33 +0000" }, "operation_id": "edc2f994cd8c4f45b3bc5632fdb27824" }
-12483668 0 It's really whichever you like better. I've tried out both and don't see any real advantages which would make one superior
-21629330 0 How do I embed a JFrame into a JavaFX 2.0 application?I have searched stackoverflow extensively for help on this topic, but the Q&As I found are old and the answers have changed for the current version of the JDK (I'm currently using 7u51).
Note that I was never SUPER proficient in Swing to begin with, but I believe I understand the fundamentals. (I've always been more focused on the meat inside an app, not the GUI).
I'm trying to work with a third party library. The third party library requires that it's components use JFrame.
Therefore, I'm trying to see how I would embed a JFrame into my JavaFX application. There was an old answer about doing something with javafx.ext.swing, but that's no longer included in JavaFX.
Help?
==========
I should also add: I think Java 8, which is currently beta, will support what I need based on this: http://docs.oracle.com/javafx/8/embed_swing/jfxpub-embed_swing.htm , but I need to see if there is a way to do this without relying on a beta product.
-34697179 0Reducer should be aware only of a small part of state.
Good place for described logic is the action creator. With redux-thunk you will be able to make a decision based on a global state.
function selectFilter(enjoys) { return (dispatch, getState) => { dispatch({type: SELECT_FILTER, enjoys}); // if getState().ui.userList.selected exists in getState().data dispatch({type: SELECT_USER, name: null}); } };
-12400413 0 It seems like you misunderstanding some concepts in software development process. This:
Since I want to manage both projects at the same time, I created a new solution for second application, which subclasses the necessary forms and classes
is a very bad idea.
In fact, new functionality brings you to new version of your software.
Do not inherit anything. Just make a development branch (in terms of source control) for your previous project version, and continue to develop new version, extending functionality.
This will allow you to get two, completely independent versions of your software, which you will support simultaneously.
-38238429 0You can define a class like this:
class Stack { private: int stack[MAX_STACK]; int MIN_STACK = 0; public: . . . } The push function can be implemented as follows:
When you increment the value of MIN_STACK before inserting, you always leave stack[0] empty and waste the space. Also use MIN_STACK as your index and not MAX_STACK as the value of MAX_STACK is always 10.
void PUSH(int val) { if(MIN_STACK < MAX_STACK) { stack[MIN_STACK++] = val; /* Here MIN_STACK is incremented after insertion. It is the same as stack[MIN_STACK] = val; MIN_STACK +=1; */ } else cout << "Full stack!" << endl; } In POP function, you have nothing to delete if MIN_STACK is 0 because each time you push a value MIN_STACK is incremented.MIN_STACK always points to the next free location. SO the data to be popped out is in (MIN_STACK-1)th position. So decrement the MIN_PATH and use it.
void POP() { int aux; if(MIN_STACK > 0) { aux = stack[--MIN_STACK]; /* Here MIN_STACK is decremented before popping out. It is the same as MIN_STACK -= 1; aux = stack[MIN_STACK]; */ cout << " POP : " << aux << endl; } else cout << "Empty stack!" << endl; } In your cpp file create an object of the class as:
Stack S1; S1.PUSH(elm); S1.POP();
-21245488 0 One way is with a custom binding handler.
ko.bindingHandlers.lineBreaks = { init: function (element, valueAccessor, allBindings, data, context) { $(element).html(value.replace(/-/g, '<br />')); } }; See updated fiddle
And if the value of the observable might change, then you can add an update section to the binding handler with the same code that is in the init.
ko.bindingHandlers.lineBreaks = { init: function (element, valueAccessor, allBindings, data, context) { $(element).html(value.replace(/-/g, '<br />')); }, update: function (element, valueAccessor, allBindings, data, context) { $(element).html(value.replace(/-/g, '<br />')); } }; Now the displayed value will be formatted via the binding handler when the value of the observable updates.
You can probably achieve the same effect with an extender as well.
-9739414 0 How to performance test JavaScript in a web page on iPhone?Ive made a web page with quite extensive JavaScript. Its runs fine in my browser and in my iPhone simulator. However on my iPhone 3G its very sluggish. My iPhone is pretty buggy though and often freezes for no reason so I dont know if its just my device or too much / bad code.
Other than using lots of devices (might be difficult to get my hands on), is there a good way to test this? Thanks
-212308 0It turns out that FindControl does work:
CType(MyListView.FindControl("litTotal"), Literal).Text = GetTheSum() I'd still like to know if there might be a better way though.
-39750079 0Process exited with singal 11 (segmentation fault). Typically, it means process unexpectedly crashed because of some error in memory usage, and php just can't handle that error in any way. You will get same error using apache+mod_php, apache+mod_fcgid or any other configuration.
In my practice, segfault gives you no useful error message in all cofigurations. The only real way to debug it is strace. One-liner to attach strace to all php processes running:
strace -f -F -s1000 -t -T `ps aux | grep -E 'apache|php|httpd' | awk '{print "-p" $2}' | xargs` If the error is hard to reproduce, you can use xdebug php-module. You need to install it like that:
apt-get install php5-xdebug or
yum install php-pecl-xdebug for CentOS. For automatic tracing of all processes add to config:
xdebug.auto_trace=On And you'll get traces, default path is:
xdebug.trace_output_dir => /tmp => /tmp xdebug.trace_output_name => trace.%c => trace.%c So your trace will have name /tmp/trace.$PID.xt
There you should be able to see last called fuction before process crash.
-13230640 0 How to obtain just particular lines of summary on lm objectThis problem comes from easier problem which I managed to solve myself. So here is my original question.
In my data I have lots of categories, but i'm not interested in estimating coefficients for all of them, I just want to test the hypothesis, that there is no difference in categories. And calling summary on my object produces most information that I don't need for my report.
set.seed(42) dat <- data.frame(cat=factor(sample(1:10, 100, replace=T)), y=rnorm(100)) l1 <- lm(y~cat-1, data=dat) summary(l1) How do I extract only the last line from call to summary(l1)?
In this particular case I can just used anova function
anova(l1) and got only the info that I needed, just in different formatting than summary(l1) produces.
What if I have some kind of a summary on an object and I want to extract just particular part of summary(object) how do I do that? For example, how do I get R to print only the line of call summary(l1)?
p.s. I am aware of summary(l1)$fstatistic.
You could use the row_number function to partition by Name and Parent, like:
select * from ( select row_number() over (partition by Name, Parent order by Name, Parent) as rn , * from YourTable ) sub where rn = 1 -- Only first row for a name/parent combination If you're looking to select only rows that are unique, in the sense that no other rows with the same name and parent exist, try:
select * from YourTable a where ( select count(*) from YourTable b where a.Name = b.Name and a.Parent = b.Parent ) = 1
-30551958 0 This may be further off topic than you want to go but NSubstitute is a great mocking library that handles this very well. In NSubstitute it's just:
var mock = Substitute.For<IInterface>(); var obj = new MyClass(); await obj.Run(); Received.InOrder(() => { mock.MethodOne("foo"); mock.MethodTwo("foo"); });
-39796869 0 Looks like you want the vector product i.e. outer join. But to have a join you need a column with rows matching. A trick here would be to create a new column with just a single value like "1" for all of the rows (use "Insert Calculated Column" - be sure to freeze the column so you can join to it later). Then do a full outer join of that table with a copy of itself (use the "Insert Columns" feature for the join) using the column with that dummy column as the key field. You will then get the combinations you showed above, but it will also have rows where the keys matched.
To remove the matches, you can easily create a new column with an expression testing if the primary keys match like:
if([Location]=[Location(2)],"Match","NoMatch") Then filter to the matching rows and delete if you don't want them in the data set.
You can certainly ask Spotfire questions here, but you can also try the Spotfire section of the TIBCO Community here:
https://community.tibco.com/products/spotfire
-38252374 0When used as part of a URL, ? and & represent key value pairs that make up the Query String, which is a set of information sent to the server.
The query string starts after the end of the page being requested with a ? and then a key value pair like:
?variable1=value1 Any additional key/value pairs need to be prefaced with & like:
?variable1=value1&variable2=value2&variable3=value3
-4022463 0 How can I extract non-standard HTTP headers using Perl's LWP? I'm working with a web application that sends some non-standard HTTP headers in its response to a login request. The header in question is:
SSO_STATUS: LoginFailed I tried to extract it with LWP::Response as $response->header('SSO_STATUS') but it does not work. It does work for standard headers such as Set-Cookie, Expires etc.
Is there a way to work with the raw headers?
-19131961 0YourActivity.this.runOnUiThread(new Runnable() { public void run() { //What you want to do, updating a UI in main thread ect. } }); you could also refer to another post HERE
-39483974 0I'm not sure if I understand your problem correctly, but please check if solution mentioned in this question suits your needs.
-11251593 0Here is might suggestion, if not suitable please ignore it: use a self hosted service as @driis mentioned. That is your best option for your scenario. The about hosting an HTML page inside your WCF service...yes it is possible but this is not a simple solution. To summarize in one sentence, you have to create your custom message formater and bypass the default one provided by WCF. You would create an HtmlBehavior which must inherit from WebHttpBehavior, HtmlBehaviorExtension which must inherit from BehaviorExtensionElement and finally a HtmlFormater which would implement IDispatchMessageFormatter. On the following link you will find a great article about custom formatters: http://blogs.msdn.com/b/carlosfigueira/archive/2011/05/03/wcf-extensibility-message-formatters.aspx
-16472086 0 How to repaint GUI after a certain element was removed?I'm making an app where a user would be able to add a button to the screen or remove it (I don't have those options implemented yet). So, for now I'm manually populating it with a for() loop and manually removing one of the buttons. My problem is that after the button has been removed (the removal action in the main()), there's just a blank spot. I want to be able to repaint the screen after I remove one of those buttons. In this example, index 2 (block #3) has been removed, leaving an empty space, where it was before... and I have no idea how to repaint it. I've tried validating or repainting from different places in the program with no success.
Here's the code (P.S. I'm sure my code is not the most efficient way to accomplish what I'm trying to and I'm using setLayout(null), which is not a preferred method, but for now I'm just trying to learn certain things and then expand on that to better myself and my code):
import java.awt.Color; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.LineBorder; class TestApp extends JFrame{ JFrame frame = new JFrame("Test Program"); ArrayList<JButton> grid = new ArrayList<JButton>(); private int w = 14; private static int amount = 102; private static int counter = 0; //Default Constructor (sets up JFrame) TestApp(){ frame.setLayout(null); frame.setPreferredSize(new Dimension(1186, 880)); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); frame.setResizable(false); paintGrid(); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } public void newWindow() { JFrame select_win = new JFrame("Selected Frame"); JPanel select_panel = new JPanel(); select_panel.setPreferredSize(new Dimension(600, 800)); select_panel.setBackground(Color.ORANGE); select_win.add(select_panel); select_win.pack(); select_win.setResizable(false); select_win.setVisible(true); select_win.setLocationRelativeTo(null); } private void paintGrid() { for(int i = 0, y = 4; i < ((amount / w) + (amount % w)); i++, y += 104) { for(int j = 0, x = 4; j < w && (counter < amount); j++, x += 84) { addBlock(counter, x, y); counter++; } } } //Adds a block private void addBlock(int index, int x, int y){ int height = 100; int width = 80; grid.add(new JButton("counter: " + (counter + 1))); (grid.get(index)).addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { javax.swing.SwingUtilities.invokeLater(new Runnable() { @Override public void run() { newWindow(); } }); } }); (grid.get(index)).setBorder(new LineBorder(Color.BLACK)); (grid.get(index)).setBackground(Color.YELLOW); (grid.get(index)).setVisible(true); (grid.get(index)).setBounds(x, y, width, height); frame.add(grid.get(index)); } //Removes a block private void removeBlock(int index){ frame.remove(grid.get(index)); grid.remove(index); amount--; counter--; } public static void main(String [] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { @Override public void run() { TestApp app = new TestApp(); //testing block removal app.removeBlock(2); } }); } }
-17886893 0 If the query builder is done in house, and if your query builder returns a the SQL statement in a string, you can parse it either looking for Update statements keyworks or with Regex, if you want to spare the users the trouble of creating an update query then realizing that they can't run it, then you should consider doing this check continiously as they create the query. Alternatively, you can use a third party query builder, like this one: http://www.activequerybuilder.com/, unfortunately i belive it doesn't support anything else but Select statements but it may be worth the shot.
-22937003 0 HTTP Illegal state exceptionI have the following code, which in general works without problems:
HttpPost post = new HttpPost(sendURL); StringEntity se = new StringEntity( postJSON.toString(), "UTF-8"); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); post.setEntity(se); response = httpClient.execute(post); When postJSON has the following, I get an IllegalStateException, with the message "Manager is shut down":
{"action":"add","items":["61515"],"screen":"display","customer_number":"200001013"} I got a similar message when the items array had malformed content, but I don't see the problem here. Also, the response is immediate, so I am pretty sure that the HTTP library is throwing the exception, not the server. What is wrong with this JSON object?
Furthermore, testing the JSON at JSONLint shows me that the JSON parses correctly, including the array with "61515", which is the new element in the code.
-40702416 0Got it working....had to return promise from child parent which is t.none() without catch()
-7686048 0You can use:
xhr.timeout = 10000; xhr.ontimeout = timeoutFired; for this purpose
-20958023 0 A simple C# Statement works unexpectedI've got this line of code:
int WStoneCost = PriceMethod.StoneCost / 100 * AP; While PriceMethod.StoneCost is equal to 25 and AP is equal to 70. I've checked it using breakpoints and I can't understand why do I get zero after I run this line. (WStoneCost is equal to zero) Is it just a wrong symbol or am I doing something wrong? Thanks in advance. And how to get a correct double at the end? Like 17.5
-13946115 0You must add MessageUI.framework to your Xcode project and include a
#import <MessageUI/MessageUI.h> in your header file.
try this code may be its helpful to you..
[self presentModalViewController:picker animated:YES]; //[self becomeFirstResponder];//try picker also instead of self Also Refer this bellow tutorial and also check demo..
i hope this help you...
-4680447 0You friendship relationship here seems to be symmetrical.
In this case, you should insert the friends' ids in strict order: say, least id first, greatest id second.
This will make one record per friendship, not depending on who befriended whom.
Use this query:
SELECT 1 FROM users_friends WHERE (user_id, friend_id) = (LEAST($user_id, $SESSION['user_id']), GREATEST($SESSION['user_id'], $user_id)) to check the friendship status, and this one:
INSERT INTO users_friends (user_id, friend_id) VALUES (LEAST($user_id, $SESSION['user_id']), GREATEST($SESSION['user_id'], $user_id)) to insert a new record.
-36910275 0Do you need to use reflection? If you have control of the classes that you are iterating over, it would be better to create an interface. Reflection is slow and should be avoided where possible.
public interface IDocumentCreator { void GenerateDocument(); } Add this interface to your classes:
public class YourClass : IDocumentCreator { // ... public void GenerateDocument() { // ... } } And then make a List<IDocumentCreator> instead of List<object>. You can then call the method in the normal way:
List<IDocumentCreator> allClassesINeedList = ... foreach(IDocumentCreator item in allClassesINeedList) { item.GenerateDocument(); }
-2053294 0 If I understand what you're trying to do... you can do something like this:
// For my benefit, hide all lists except the root items $('ul, li', $('#lesson-sidebar ul li')).hide(); // Show active parents and their siblings $('li a.active').parents('ul, li').each(function() { $(this).siblings().andSelf().show(); }); // Show the active item and its siblings $('li a.active').siblings().andSelf().show(); The parents() and siblings() methods are both great for this kind of thing.
Edit: There was a bug before where it wasn't showing parent siblings. Try this new version.
Edit 2: Now it works with class="active" on the anchor instead of the list item.
-5306229 0You've set the variable i in the line var i = document.getElementById('i').innerHTML = (document.getElementById("nine").value);. i refers to the variable i, not to the control with id i.
You'll have to do
var a = document.getElementById('number').value etc.
Edit: Ah I see you've declared a..h inside your methods. Remember that var a only applies within the curly brackets that it's declared inside, so declare them at the start of your script by doing var a=0 etc. This is called the 'scope' of your variables.
If the table data is added by JS then you might want to add an on() handler like:
$('#area-work-time').on('change','input[type="checkbox"]',function(){ alert("inside change event"); }); This makes the event trigger for dynamically created elements.
-33539108 0... and you could use the OpenNTF Domino API that has functions for exactly this. As far as I remember there is an example of this in the demo database. Not sure if it is also in the new version of the demo database - but then you may just need to find an older version (e.g. for milestone 4.5 where I saw this).
/John
-28822638 0While Hackaholic's solution is excellent (and very functional-programming), here's an alternative using list comprehensions.
The key ingredient is zip(a,b,c), which returns a sequence of tuples containing the ith elements of a, b, c. As Joran Beasley mentions, your code will work just by adding zip:
d = [] for i,j,k in zip(a,b,c): d.append(i+j+k) From here it's pretty easy to get to the list comprehension version:
d = [i+j+k for i,j,k in zip(a,b,c)] And in fact you don't even need to unpack the tuple as i, j, k, instead you can sum the tuple directly:
d = [sum(tup) for tup in zip(a,b,c)]
-29785839 0 var url = 'http://website.com/testing/test2/', //URL to convert lastSlash = url.lastIndexOf('/'), //Find the last '/' middleUrl = url.substring(0,lastSlash); //Make a new string without the last '/' lastSlash = middleUrl.lastIndexOf('/'); //Find the last '/' in the new string (the second last '/' in the old string) var newUrl = middleUrl.substring(0,lastSlash); //Make a new string that removes the '/' and everything after it alert(newUrl); //Alert the new URL, ready for use This works.
-12932793 0Why is this the case that an empty class without any values already needs 220 bytes for saving itself?
Why ask what you can find out? This code already yields 33 bytes:
FileStream fs = new FileStream("Serialized.dat", FileMode.Create); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(fs, "FooString"); Because there's more being serialized than just the string itself. If you serialize an object, its class definition (and the assembly it's in) is also being serialized. Serializing an instance of this class:
[Serializable] class Foo { public String FooString { get; set; } } Costs 166 bytes, while the FooString property contains the same data as the raw string serialized earlier.
So: write your own serialization (or: load/save) logic. You are the one that reads and writes that data, so you can for example assign specific bytes in the space you have to certain properties of your class.
-7456443 0No. You'd have to expose the static instance to the caller. Reference equality means that it is exactly the same object. Unless there is a way to access that particular object, you can't have another that references the same memory. If you were to use the equality operator, that would be different as string overloads that to do value equality rather than reference equality.
Had you, on the other hand, set the static instance value to a constant, you could (by using the constant) have a reference that is equal to the static instance. That is because string literals are interned and shared through out the code, meaning that all string literals that are the same have the same reference.
For example,
class GuessTheSecret { private static readonly string Secret = "Secret"; public static bool IsCorrect(string token) { return object.ReferenceEquals(token, Secret); } } Console.WriteLine( GuessTheSecret.IsCorrect( "Secret" ) ); would output True
If you declare the variable outside of a method, the state is remembered.
A solution could be:
public class Test { int count = 0; public static void main(String[] args) { Test test1 = new Test(); test1.doMethod(); test1.doMethod(); test1.doMethod(); } public void doMethod () { count++; System.out.println(count); } } This way count is created the moment you call new Test() and will be remembered until the Object is destroyed. Variables have something called a 'scope'. They can only be accessed in their scope and will only exist in that scope. Because you created count inside your void doMethod() method, it did not exist anywhere else. An easy way to look at the scope is by watching the brackets { } your variables are only stored inside those brackets. In my solution the brackets for count are the brackets for the entire Test class. Thus the variable is stored until the Object is destroyed.
More on scope: http://en.wikipedia.org/wiki/Scope_(computer_science)
I just noticed you mentioned you want the count value to remain after you run the program. You can do this by saving it in a database or file. However, you might have meant that you want the count value to remain after you run the void doMethod() method. I have edited my solution to execute the void doMethod() method three times so you see the value actually remains after running the method.
I've been playing around with my code, trying to better it and im stuck a this part.
I have the following header
Funcionario.h
class Funcionario { private: std::string Userid; std::string Nome; std::string Sobrenome; std::string Email; std::string Pass; public: Funcionario(std::string Userid, std::string Nome, std::string Sobrenome, std::string Email, std::string Pass); ~Funcionario(void); string GetUserID() { return Userid; } string GetName() { return Nome; } string GetSName() { return Sobrenome; } string GetEmail() {return Email; } string GetPass() { return Pass; } }; And this is my form, note that it's not the entire form, just the part that matters;
#include <list> #include <algorithm> #include "Funcionario.h" Form1(void) { InitializeComponent(); // //TODO: Add the constructor code here // LF = new list<Funcionario>(); } //Button click list<Funcionario>::iterator it1 = find(LF->begin(), LF->end(), ID); //*Searches for ID When i try to run this it says that there is no suitable converter to tipe Funcionario. Any help would be apreciated and thank you very much in advance.
-30495711 0 IOS - Have UITableViewCells scroll over UIView (like the shazam app)I have a UIView above my UITableView. When the user scrolls down I want the UIView to stay in place at the top of the screen and have the cells scroll over it. The first page of the Shazam app does what I want.
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{ if (self.tableView.contentOffset.y > 0) { CGRect newframe = self.publicTopView.frame; newframe.origin.y = -self.tableView.contentOffset.y; self.publicTopView.frame = newframe; } }
This is what I've tried so far, but it doesn't do anything. Thanks
-35450932 0As you want to avoid recursion, you need to reverse the list first. I see some attempt in the original code but it doesn't look correct. Try the following:
node *current = head; if (current != NULL) { node *prev = NULL; for (node *next = current->next; ; next = (current = next)->next) { current->next = prev; prev = current; if (next == NULL) break; } } Then current will point to the head of the list and you can traverse using the next link over the list. Note that it will modify your original list but this is expected as I understood the original requirement.
"aPosition" is not used in the shader code so the GLSL-compiler has optimized away the variable. Try using it in the gl_Position assignment and you will notice that it works.
gl_Position = uMVPMatrix * uTMatrix * aPosition;
-2401438 0 MVC Model Implementation? I am creating a simple application using the MVC design pattern where my model accesses data off the web and makes it available to my controllers for subsequent display.
After a little research I have decided that one method would be to implement my model as a singleton so that I can access it as a shared instance from any of my controllers.
Having said that the more I read about singletons the more I notice people saying there are few situations where a better solution is not possible.
If I don't use a singleton I am confused as to where I might create my model class. I am not over happy about doing it via the appDelegate and it does not seem viable to put it in any of the viewControllers.
any comments or pointers would be much appreciated.
EDIT_001:
TechZen, very much appreciated (fantastic answer as always) can I add one further bit to the question before making it accepted. What are your thoughts on deallocating the singleton when the app exits? I am not sure how important this is as I know quite often that object deallocs are not called on app teardown as they will be cleared when the app exits anyway. Apparently I could register the shared instance with NSApplicationWillTerminateNotification, is that worth doing, just curious?
gary
-1777744 0Named Pipes can be used for this. It might be the more acceptable method with .net.You can define a service in the main application that accepts a message from the calling application. Here's a sample of the service, in vb. It calls the main app and passes a string to it, in this case, a filename. It also returns a string, but any parameters can be used here.
Public Class PicLoadService : Implements IMainAppPicLoad Public Function LoadPic(ByVal fName As String) As String Implements IMainAppPicLoad.LoadPic ' do some stuff here. LoadPic = "return string" End Function End Class The setup in the calling application is a little more involved. The calling and main application can be the same application.
Imports System.Diagnostics Imports System.ServiceModel Imports System.IO Imports vb = Microsoft.VisualBasic Module MainAppLoader Sub Main() Dim epAddress As EndpointAddress Dim Client As picClient Dim s As String Dim loadFile As String Dim procs() As Process Dim processName As String = "MainApp" loadFile = "" ' filename to load procs = Process.GetProcessesByName(processName) If UBound(procs) >= 0 Then epAddress = New EndpointAddress("net.pipe://localhost/MainAppPicLoad") Client = New picClient(New NetNamedPipeBinding, epAddress) s = Client.LoadPic(loadFile) End If End Sub <System.Diagnostics.DebuggerStepThroughAttribute(), _ System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")> _ Partial Public Class picClient Inherits System.ServiceModel.ClientBase(Of IMainAppPicLoad) Implements IMainAppPicLoad Public Sub New(ByVal binding As System.ServiceModel.Channels.Binding, ByVal remoteAddress As System.ServiceModel.EndpointAddress) MyBase.New(binding, remoteAddress) End Sub Public Function LoadPic(ByVal fName As String) As String Implements IMainAppPicLoad.LoadPic Return MyBase.Channel.LoadPic(fName) End Function End Class ' from here down was auto generated by svcutil. ' svcutil.exe /language:vb /out:generatedProxy.vb /config:app.config http://localhost:8000/MainAppPicLoad ' Some has been simplified after auto code generation. <System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0"), _ System.ServiceModel.ServiceContractAttribute(ConfigurationName:="IMainAppPicLoad")> _ Public Interface IMainAppPicLoad <System.ServiceModel.OperationContractAttribute(Action:="http://tempuri.org/IMainAppPicLoad/LoadPic", ReplyAction:="http://tempuri.org/IMainAppPicLoad/LoadPicResponse")> _ Function LoadPic(ByVal fName As String) As String End Interface <System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")> _ Public Interface IMainAppPicLoadChannel Inherits IMainAppPicLoad, System.ServiceModel.IClientChannel End Interface <System.Diagnostics.DebuggerStepThroughAttribute(), _ System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")> _ Partial Public Class IMainAppPicLoadClient Inherits System.ServiceModel.ClientBase(Of IMainAppPicLoad) Implements IMainAppPicLoad Public Sub New(ByVal binding As System.ServiceModel.Channels.Binding, ByVal remoteAddress As System.ServiceModel.EndpointAddress) MyBase.New(binding, remoteAddress) End Sub Public Function LoadPic(ByVal fName As String) As String Implements IMainAppPicLoad.LoadPic Return MyBase.Channel.LoadPic(fName) End Function End Class End Module <ServiceContract()> Public Interface IMainAppPicLoad <OperationContract()> Function LoadPic(ByVal fName As String) As String End Interface
-1931770 0 If I'm not going to be saving data into an SQL database, where should I be saving it? I'm making an encyclopedia program of sorts similar to RAWR for World of Warcraft. I'm not going to be saving data de an SQL database, but I've been conditioned so hard to always do this when I'm sure there are alternatives for these lighter case uses.
For example, my program will have no creation of new data via user input, nor deletion of data via user input. Just a program that will display information that I code into it. Nothing more, nothing less.
Where should I save these things? By save I mean, store them for deployment when I release the program.
I'm mostly going to be saving just string variables and some videos/animation (see my other question)
Thanks for the help SO. As always, you guys rock!
-21331631 0Well the algorithm is as follows:
Let, P(N) denote the number of trees possible with N nodes. Let the indexes of the nodes be 1,2,3,...
Now, lets pick the root of the tree. Any of the given N nodes can be the root. Say node i has been picked as root. Then, all the elements to the left of i in the inorder sequence must be in the left sub-tree. Similarly, to the right.
So, total possibilities are: P(i-1)*P(N-i)
In the above expression i varies from 1 to N.
Hence we have,
P(N) = P(0)*P(N-1) + P(1)*P(N-2) + P(2)*P(N-3).... The base cases will be:
P(0) = 1 P(1) = 1 Thus this can be solved by using Dynamic Programming.
So modify the two lines to:
movlps QWORD PTR[rdx], xmm7
movss dword ptr [rdx+8], xmm6
like here: http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/4f473acb-7b14-4bf4-bed3-e5e87e1f81e7
-15084430 0 android 4.0.3 ScrollingTabContainerView NullPointerExceptionOur Android Application randomly crashes (very hard to repro the issue) with the following stack trace . This is seen when the orientation of the device is changed from portrait to landscape from the logcat logs. Also this issue has been seen on devices with Android 4.0.3 version. So wanted to check if it is a known issue with 4.0.3? Not sure from the code how to debug this issue as the stack trace is entirely of Android platform with no involvement of App code.
02-21 17:44:01.761 E/UncaughtException( 3344): java.lang.NullPointerException 02-21 17:44:01.761 E/UncaughtException( 3344): at com.android.internal.widget.ScrollingTabContainerView.onItemSelected(ScrollingTabContainerView.java:352) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.widget.AdapterView.fireOnSelected(AdapterView.java:882) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.widget.AdapterView.selectionChanged(AdapterView.java:865) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.widget.AdapterView.checkSelectionChanged(AdapterView.java:1017) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.widget.AdapterView.handleDataChanged(AdapterView.java:999) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.widget.AbsSpinner.onMeasure(AbsSpinner.java:179) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.widget.Spinner.onMeasure(Spinner.java:285) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.view.View.measure(View.java:12723) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.widget.HorizontalScrollView.measureChildWithMargins(HorizontalScrollView.java:1159) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.widget.FrameLayout.onMeasure(FrameLayout.java:293) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.widget.HorizontalScrollView.onMeasure(HorizontalScrollView.java:303) 02-21 17:44:01.761 E/UncaughtException( 3344): at com.android.internal.widget.ScrollingTabContainerView.onMeasure(ScrollingTabContainerView.java:117) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.view.View.measure(View.java:12723) 02-21 17:44:01.761 E/UncaughtException( 3344): at com.android.internal.widget.ActionBarView.onMeasure(ActionBarView.java:878) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.view.View.measure(View.java:12723) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4698) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.widget.FrameLayout.onMeasure(FrameLayout.java:293) 02-21 17:44:01.761 E/UncaughtException( 3344): at com.android.internal.widget.ActionBarContainer.onMeasure(ActionBarContainer.java:173) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.view.View.measure(View.java:12723) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4698) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1369) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.widget.LinearLayout.measureVertical(LinearLayout.java:660) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.widget.LinearLayout.onMeasure(LinearLayout.java:553) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.view.View.measure(View.java:12723) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4698) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.widget.FrameLayout.onMeasure(FrameLayout.java:293) 02-21 17:44:01.761 E/UncaughtException( 3344): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2092) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.view.View.measure(View.java:12723) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1064) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2442) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.os.Handler.dispatchMessage(Handler.java:99) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.os.Looper.loop(Looper.java:137) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.app.ActivityThread.main(ActivityThread.java:4424) 02-21 17:44:01.761 E/UncaughtException( 3344): at java.lang.reflect.Method.invokeNative(Native Method) 02-21 17:44:01.761 E/UncaughtException( 3344): at java.lang.reflect.Method.invoke(Method.java:511) 02-21 17:44:01.761 E/UncaughtException( 3344): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 02-21 17:44:01.761 E/UncaughtException( 3344): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 02-21 17:44:01.761 E/UncaughtException( 3344): at dalvik.system.NativeStart.main(Native Method)
-30863431 0 In oracle, you can use start with connect by to achieve the same result, no need to use nested query
Preparation
CREATE TABLE EMP ( EMPNO numeric(4,0), ENAME VARCHAR(10 ), JOB VARCHAR(9 ), MGR numeric(4,0), HIREDATE DATE, SAL numeric(7,2), COMM numeric(7,2), DEPTNO numeric(2,0) ); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7369,'SMITH','CLERK',7902,sysdate,800,null,20); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7499,'ALLEN','SALESMAN',7698,sysdate,1600,300,30); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7521,'WARD','SALESMAN',7698,sysdate,1250,500,30); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7566,'JONES','MANAGER',7839,sysdate,2975,null,20); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7654,'MARTIN','SALESMAN',7698,sysdate,1250,1400,30); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7698,'BLAKE','MANAGER',7839,sysdate,2850,null,30); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7782,'CLARK','MANAGER',7839,sysdate,2450,null,10); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7788,'SCOTT','ANALYST',7566,sysdate,3000,null,20); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7839,'KING','PRESIDENT',null,sysdate,5000,null,10); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7844,'TURNER','SALESMAN',7698,sysdate,1500,0,30); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7876,'ADAMS','CLERK',7788,sysdate,1100,null,20); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7900,'JAMES','CLERK',7698,sysdate,950,null,30); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7902,'FORD','ANALYST',7566,sysdate,3000,null,20); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7934,'MILLER','CLERK',7782,sysdate,1300,null,10); Query:
select empno, mgr, ename, level - 1 as T from emp start with mgr is null connect by prior empno = mgr; Output:
| EMPNO | MGR | ENAME | T | |-------|--------|--------|---| | 7839 | (null) | KING | 0 | | 7566 | 7839 | JONES | 1 | | 7788 | 7566 | SCOTT | 2 | | 7876 | 7788 | ADAMS | 3 | | 7902 | 7566 | FORD | 2 | | 7369 | 7902 | SMITH | 3 | | 7698 | 7839 | BLAKE | 1 | | 7499 | 7698 | ALLEN | 2 | | 7521 | 7698 | WARD | 2 | | 7654 | 7698 | MARTIN | 2 | | 7844 | 7698 | TURNER | 2 | | 7900 | 7698 | JAMES | 2 | | 7782 | 7839 | CLARK | 1 | | 7934 | 7782 | MILLER | 2 |
-2732209 0 you need to check if you are posting all the "posting fields".. some sites use security tokens or sessions ids to prevent bots from logging on their sites. anyway, you need to install Live HTTP headers firefox extension. open it and try to login manually, then see whats being posted actually when you press login button. after you get the values. add then to the first function and test again.
-13457679 0 Mailto link with display name in non-Latin characters doesn't work correctly in Chrome browserI have the following problem in Chrome browser: When I have a mailto link with display name in non-Latin characters and email address the right button->copy email address->paste anywhere doesn’t work correctly. The display name is broken /with escape characters/.
For example:
<a href="mailto:нова категория <7580397996@gmail.com>?Subject=[Enter your subject title here]&body=[Enter your content email here]">нова категория</a>
If you try this in Chrome Copy Email Address doesn’t work correctly. Does anyone know how can I fix this problem or this problem is bug in Chrome?
Please help and thanks in advance.
-35367363 0Ok, so I solved it (pretty much). The password and username in my odbc files were being ignored. Because I was calling the DB queries from Asterisk, I was using a file called res_odbc.ini too. This contained my username and password also, and when I run the query from Asterisk, it conencts and returns the correct result.
In case it helps, here is my final working configuration.
odbc.ini
[asterisk-connector] Description = MS SQL connection to asterisk database driver = /usr/lib64/libtdsodbc.so servername = SQL2 Port = 1433 User = MyUsername Password = MyPassword odbcinst.ini
[FreeTDS] Description = TDS connection Driver = /usr/lib64/libtdsodbc.so UsageCount = 1 [ODBC] trace = Yes TraceFile = /tmp/sql.log ForceTrace = Yes freetds.conf
# $Id: freetds.conf,v 1.12 2007/12/25 06:02:36 jklowden Exp $ # # This file is installed by FreeTDS if no file by the same # name is found in the installation directory. # # For information about the layout of this file and its settings, # see the freetds.conf manpage "man freetds.conf". # Global settings are overridden by those in a database # server specific section [global] # TDS protocol version ; tds version = 4.2 # Whether to write a TDSDUMP file for diagnostic purposes # (setting this to /tmp is insecure on a multi-user system) dump file = /tmp/freetds.log ; debug flags = 0xffff # Command and connection timeouts ; timeout = 10 ; connect timeout = 10 # If you get out-of-memory errors, it may mean that your client # is trying to allocate a huge buffer for a TEXT field. # Try setting 'text size' to a more reasonable limit text size = 64512 # A typical Sybase server [egServer50] host = symachine.domain.com port = 5000 tds version = 5.0 # A typical Microsoft server [SQL2] host = 192.168.1.59 port = 1433 tds version = 8.0 res_odbc.conf
[asterisk-connector] enabled = yes dsn = asterisk-connector username = MyUsername password = MyPassword pooling = no limit = 1 pre-connect = yes Remember if you are using Centos 64 bit to modify the driver path to lib64. Most of the guides online have the wrong (for 64 bit) paths.
Good luck - it's a headache :)
-6153297 0 Opening another window in an Appcelerator Titanium-app doesn't workI've got basically 5 windows in my iPad-application (created with Appcelerator Titanium) and want to be able to navigate forth and back (a back and and a next-button for that purpose). The following approach doesn't work. Nothing happens upon clicking the button.
The first window is opened in my app.js like this:
var window = Titanium.UI.createWindow({ url:'mainwindows.js', modal: true }); window.open(); then in mainwindows.js I've got a button called 'next' which does this:
buttonNext.addEventListener('click', function(e){ var newWindow = Titanium.UI.createWindow({ url: "step_1.js", title: "Step 1" }); win.open(newWindow, { animated:true}) });
-7009813 0 Try by using the Silverlight toolkit for Windows Phone 7. If you need to capture the Tap event on the page, you've to use the services of the GestureListner class.
<phone:PhoneApplicationPage xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" x:Name="phoneApplicationPage" x:Class="XXXXX" > <toolkit:GestureService.GestureListener> <toolkit:GestureListener Tap="Page_Tap" /> </toolkit:GestureService.GestureListener> . . .
-15908210 0 This is probably because your background image doesn't get repeated (as do the corner images) therefore, it will get covered up by one of the corner pictures. Try to set the first background-image to repeat:
background-repeat: repeat, no-repeat, no-repeat, no-repeat, no-repeat;
-27761566 0 As an alternative, you can use flatten with len:
from compiler.ast import flatten my_list = [[1,2,3],[3,5,[2,3]], [[3,2],[5,[4]]]] len(flatten(my_list)) 11 PS. thanks for @thefourtheye pointing out, please note:
Deprecated since version 2.6: The compiler package has been removed in Python 3.
-14334909 0 Sprite not showing renderToTexture Map / rendertarget mapI am working with three.js and I set up a second scene and camera and added a cylinder to it. Now I setup a rendertarget and I wanted to show this renderedScene on a sprite (HUD-Sprite so to say), but the sprite is not showing up. I added a plane into the original scene and it shows the rendertarget perfectly fine.
What I already checked:
1) When using the rtTexture as a map for a MeshLambertMaterial, it works perfectly fine
2) When loading an image for the sprite with ImageUtils and using this as a map for the SpriteMaterial, it works great and the spline is showing up where it should be!
I have the feeling that I overlooked something. Would be cool if someone can help me.
OK, guys, i created a jsFiddle, maybe this helps!
My Fiddle for RenderTarget Sprite Problem
as you can see there, the rendertarget is correctly display on the plane and there is a sprite with screenspace coordinates in there but it does not show the renderTarget.
rttMaterial = new THREE.SpriteMaterial( { color: 0xFF0000, map: rtTexture, alignment: THREE.SpriteAlignment.topLeft, useScreenCoordinates: true} ); Thank you in Advance
-38689468 0change the trigger element to button.
triggerEl: 'button'
-5544452 0 It's been deprecated for a while now. You're better off writing your own function, or taking some hints from the docs and comments on php.net
-16439440 0int r = arc4random() % 8;.switch statement set the CGRect of the button depending on r.like this:
<select id="mySelectTV"><option>tv</option></select> //parent <select><option>model</option></select> //sub select var x = document.getElementById("mySelectTV"); var option = document.createElement("option"); option.text = "music chanel"; x.add(option); OR using loop
var chanels = ['chanel 1', 'chanel 2', 'chanel 3']; var x = document.getElementById("mySelectTV"); var option = document.createElement("option"); for(var i=0; i< chanels.length; i++){ option.text = chanels[i] ; x.add(option); }
-24714797 0 Textwatcher in custom listview with SQLite database I want to add a filter in custom listview which is getting values from sqlite database. Is it possible to filter according to two value of textview? Please help me to add a filter query . If you have any text watcher example then please tell me.
I have added a listview adapter in MainActivity.java
lv = (ListView) findViewById(R.id.listView1); mydb = new DBHelper(this); Log.d("tag", mydb.listfromdb().toString()); lv.setAdapter(new ViewAdapter(mydb.listfromdb())); and
public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub if (convertView == null) { LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = mInflater.inflate(R.layout.list_item, null); } Listcollection o = collectionlist.get(position); if (o != null) { TextView idText = (TextView) convertView .findViewById(R.id.lvid); TextView nameText = (TextView) convertView .findViewById(R.id.lvname); TextView dateText = (TextView) convertView .findViewById(R.id.lvdate); TextView phoneText = (TextView) convertView .findViewById(R.id.lvjno); if (idText != null) { idText.setText(Integer.toString(o.getId())); } if (nameText != null) { nameText.setText("Name : " + collectionlist.get(position).getName()); } if (dateText != null) { dateText.setText("Date of Complain : " + collectionlist.get(position).getCdate()); } if (phoneText != null) { phoneText.setText("Job No.: " + collectionlist.get(position).getType()); } } return convertView; } Here I am getting values from DBHelper.java
public ArrayList<Listcollection> listfromdb() { SQLiteDatabase db = this.getReadableDatabase(); ArrayList<Listcollection> results = new ArrayList<Listcollection>(); Cursor crs = db.rawQuery("select * from contacts", null); while (crs.moveToNext()) { Listcollection item = new Listcollection(); item.setId(crs.getInt(crs.getColumnIndex(CONTACTS_COLUMN_ID))); item.setName(crs.getString(crs.getColumnIndex(C_NAME))); item.setCdate(crs.getString(crs.getColumnIndex(C_CDATE))); item.setType(crs.getString(crs.getColumnIndex(C_TYPE))); results.add(item); } db.close(); return results; } I have also included DBHelper.java after removing some methods.
public class DBHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "MyDBName.db"; public static final String CONTACTS_TABLE_NAME = "contacts"; public static final String CONTACTS_COLUMN_ID = "id"; public static final String C_NAME = "name"; public static final String C_TYPE = "type"; public static final String C_ADDRESS = "address"; public static final String C_DATE = "sdate"; public static final String C_PHONE = "phone"; public static final String C_PNAME = "pname"; public static final String C_MNO = "mno"; public static final String C_CDATE = "cdate"; public static final String C_DNAME = "dname"; public static final String C_DPHONE = "dphone"; public static final String C_TSCHARGE = "tscharge"; public static final String C_DAMOUNT = "damount"; public static final String C_FANDSOL = "fandsol"; public static final String C_TRNO = "trno"; public static final String C_TCRAMOUNT = "tcramount"; private HashMap hp; public DBHelper(Context context) { super(context, DATABASE_NAME, null, 1); } public ArrayList<Listcollection> listfromdb() { SQLiteDatabase db = this.getReadableDatabase(); ArrayList<Listcollection> results = new ArrayList<Listcollection>(); Cursor crs = db.rawQuery("select * from contacts", null); while (crs.moveToNext()) { Listcollection item = new Listcollection(); item.setId(crs.getInt(crs.getColumnIndex(CONTACTS_COLUMN_ID))); item.setName(crs.getString(crs.getColumnIndex(C_NAME))); item.setCdate(crs.getString(crs.getColumnIndex(C_CDATE))); item.setType(crs.getString(crs.getColumnIndex(C_TYPE))); results.add(item); } db.close(); return results; } }
-40160996 0 Some dead containers were still running in the background. I removed all of them restarted and everything works now.
I removed them using,
docker ps --all | grep restml | cut -c138- | xargs docker rm
-13240785 0 I suspect that:
require 'cowboy', that tells rubygems to set up the load paths automatically to point to the currently installed gem dir.test/test_cowboy.rb it doesn't require 'cowboy'. This makes sense because during development, you don't want to load the installed version of the gem, which could be different from the code in your working dir.I think you should create a test/test_helper.rb file that sets up the load path:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) You may need to add other dirs if the compiled shared object file (.so or .bundle) isn't placed in lib.
Then in each test file (e.g. test/test_cowboy.rb), require test/test_helper.rb:
require File.expand_path('../test_helper.rb', __FILE__) You'll need to adjust that relative path if you have subdirs. E.g. if you have a file test/shoes/spur.rb, you'd use:
require File.expand_path('../../test_helper.rb', __FILE__)
-1229096 0 You should download leopard, not snow leopard. Snow won't be out until around september, so you have leopard.
-10430694 0function changeImage(me){ alert(me.id) }
-21615296 0 When you inflate the layout for your fragment, you should ensure that the visibility is set to GONE. The default for a view (and thus your fragment) is VISIBLE.
Also, you should use the constants View.VISIBLE and View.GONE instead of 0, 8.
-32056796 0First add this certificate via script in this folder: {rubyfolder}\lib\ruby\2.1.0\rubygems\ssl_certs
-22182388 0 Difference between P2 and P2 Update site in Nexus P2 proxy supportSo I've installed nexus p2 plugin.
It gives me two options when creating a proxy on a P2 Repository. P2 and P2 Update Site.
What is the difference between the two and when should I use one over the other?
-307889 0Of course you can write a makefile by hand. A quick googling shows LOTS of tutorials. This one looks promising.
For the cliffs notes version, the example boils down this:
CC=g++ CFLAGS=-c -Wall LDFLAGS= SOURCES=main.cpp hello.cpp OBJECTS=$(SOURCES:.cpp=.o) EXECUTABLE=hello all: $(SOURCES) $(EXECUTABLE) $(EXECUTABLE): $(OBJECTS) $(CC) $(LDFLAGS) $(OBJECTS) -o $@ .cpp.o: $(CC) $(CFLAGS) $< -o $@
-13030685 0 XML is one choice among many for serialization. You can do Java Serializable, XML, JSON, protobuf, or anything else that you'd like. I see no pitfalls.
One advantage of XML is you can use JAXB to marshal and unmarshal objects.
-26956900 0You could simply use grep instead of sed . The reason why i choose grep means, grep is a tool which prints each match in a separate line.
grep -oP 'tel:\K.*?(?=;)' file.txt Regular Expression:
tel: 'tel:' \K '\K' (resets the starting point of the reported match) .*? matches any character except \n (0 or more times) non-greedily (?= look ahead to see if there is: ; ';' ) end of look-ahead Update:
$ cat file tel:02134343, 3646848393; tel:02134343; tel:02134344; $ grep -oP '(?:tel:|(?<!^)\G)\K\d*(?=[^;\n]*;)' file 02134343 3646848393 02134343 02134344
-825455 0 BEA used to have a product named JAM that was used to communicate with mainframe COBOL programs. It included a tool that would read copybooks and generate both corresponding Java POD classes and data conversion code.
I don't know if this is still available, I lost track of it when I left BEA.
-13692871 0Do it like that:
$(".imgt").click(function() { $("#imgb").prop("src", this.src); });
-21105509 0 How to call struct from separate function? #include <iostream> #include <cmath> using namespace std; struct workers{ int ID; string name; string lastname; int date; }; bool check_ID(workers *people, workers &guy); void check_something(workers *people, workers &guy, int& i); int main() { workers people[5]; for(int i = 0; i < 5; i++){ cin >> people[i].ID; cin >> people[i].name; cin >> people[i].lastname; cin >> people[i].date; if(check_ID(people, people[i]) == true) cout << "True" << endl; else cout << "False" << endl; check_something(people, people[i], i); } return 0; } bool check_ID(workers *people, workers &guy){ for(int i = 0; i < 5; i++){ if(people[i].ID == guy.ID) return true; break; } return false; } void check_something(workers *people, workers &guy, int& i){ check_ID(people, guy[i]); } This is the code I have, it's not very good example, but I quickly wrote it to represent my problem I have because my project is kinda too big. So basically, I want to call struct from a different function and I'm getting this error: error: no match for 'operator[]' in guy[i] on this line : check_ID(people, guy[i]); in the function check_something.
I am working in two java projects. The first supports OSGi components, second does not. The first depend to the second for logging.
My need is to add a callback in the second project from the first to recover a variable to add in the log.
-424593 0moo, cow, sheep, baa (in that order).
-19171346 0 Create a wordpress page with archives of a categoryI'm a bit stumped on this one. I'd like to create a page that is an archive of all posts of a certain category - and show excerpts. However, Reading through the Wordpress docs, they say a page cannot be a post or associated with categories.
So, I'm now wondering if this is possible or if there is a work around. I'd really like to put this on a page as I'd like to have a custom sidebar as well. Is this possible with a custom page template? Any other ways this can be done that I am not thinking of?
Thanks!
-20387958 0This works with arbitrary number of dicts:
def combine(**kwargs): return { k: { d: kwargs[d][k] for d in kwargs } for k in set.intersection(*map(set, kwargs.values())) } For example:
print combine( one={'1': 3, '2': 4, '3':8, '9': 20}, two={'3': 40, '9': 28, '100': 3}, three={'3':14, '9':42}) # {'9': {'one': 20, 'three': 42, 'two': 28}, '3': {'one': 8, 'three': 14, 'two': 40}}
-1821665 0 There are certainly many options for this, but one that is very easy to implement and meets your criteria is an Asynchronous Web Service call.
This does not require you to start a worker thread (the Framework will do that behind the scenes). Rather than use one of the options outlined in that link to fetch the result, simply ignore the result since it is meaningless to the calling app.
-20928108 0 making text bold via codeI have the code:
label5.Font = new Font(label5.Font.Name, 12, FontStyle.Underline); ..But I can't figure how to change it to bold as well. How can I do that?
-3622066 0e to the power of something imaginary can be computed with sin and cos waves

wikipedia entry for e
and vector exponentiation has it's own page as well

matrix exponential
I'd say follow the Single Responsibility Principle.
What you have is a SportsCard that does nothing on itself. It's just a data container.
class SportsCard { protected $_price; protected $_sport; public function __construct($price, $sport) { $this->_price = $price; $this->_sport = $sport; } public function getPrice() { return $this->_price; } public function getSport() { return $this->_sport; } } The SportsCards have to be stored in a CardBook. If you think about a CardBook, then it doesn't do much, except for storing SportsCards (not Pokemon or Magic The Gathering cards), so let's just make it do that:
class CardBook extends SplObjectStorage { public function attach($card) { if ($card instanceof SportsCard) { parent::attach($card); } return $this; } public function detach($card) { parent::detach($card); } } While there is nothing wrong with adding Finder Methods to the SportsCard set, you do not want the finder method's logic inside it as well. It is fine as long as you only have
public function findByPrice($min, $max); public function findBySport($sport); But the second you also add
public function findByPriceAndSport($sport, $min, $max); you will either duplicate code or iterate over the collection twice. Fortunately, PHP offers an elegant solution for filtering collections with Iterators, so let's put the responsibility for filtering into separate classes as well:
abstract class CardBookFilterIterator extends FilterIterator { public function __construct($cardBook) { if ($cardBook instanceof CardBook || $cardBook instanceof self) { parent::__construct($cardBook); } else { throw new InvalidArgumentException( 'Expected CardBook or CardBookFilterIterator'); } } } This class merely makes sure the child classes accept only children of itself or CardBooks. This is important because we are accessing methods from SportsCard in actual filters later and because CardBooks can contain only SportsCards, we make sure the iterated elements provide these methods. But let's look at a concrete Filter:
class SportCardsBySportFilter extends CardBookFilterIterator { protected $sport = NULL; public function filterBySport($sport) { $this->_sport = $sport; return $this; } public function accept() { return $this->current()->getSport() === $this->_sport; } } FilterIterators work by extending the class and modifying it's accept() method with custom logic. If the method does not return FALSE, the currently iterated item is allowed to pass the filter. Iterators can be stacked, so you add Filter on Filter on top, each caring only for a single piece of filtering, which makes this very maintainable and extensible. Here is the second filter:
class SportCardsByPriceFilter extends CardBookFilterIterator { protected $min; protected $max; public function filterByPrice($min = 0, $max = PHP_INT_MAX) { $this->_min = $min; $this->_max = $max; return $this; } public function accept() { return $this->current()->getPrice() > $this->_min && $this->current()->getPrice() < $this->_max; } } No magic here. Just the accept method and the setter for the criteria. Now, to assemble it:
$cardBook = new CardBook; $cardBook->attach(new SportsCard('10', 'Baseball')) ->attach(new SportsCard('40', 'Basketball')) ->attach(new SportsCard('50', 'Soccer')) ->attach(new SportsCard('20', 'Rugby')) ->attach(new SportsCard('30', 'Baseball')); $filteredCardBook = new SportCardsBySportFilter($cardBook); $filteredCardBook->setFilterBySport('Baseball'); $filteredCardBook = new SportCardsByPriceFilter($filteredCardBook); $filteredCardBook->filterByPrice(20); print_r( iterator_to_array($filteredCardBook) ); And this will give:
Array ( [4] => SportsCard Object ( [_price:protected] => 30 [_sport:protected] => Baseball ) ) Combining filters from inside the CardBook is a breeze now. No Code duplication or double iteration anymore. Whether you keep the Finder Methods inside the CardBook or in a CardBookFinder that you can pass CardBooks into is up to you.
class CardBookFinder { protected $_filterSet; protected $_cardBook; public function __construct(CardBook $cardBook) { $this->_cardBook = $this->_filterSet = $cardBook; } public function getFilterSet() { return $this->_filterSet; } public function resetFilterSet() { return $this->_filterSet = $this->_cardBook; } These methods just make sure you can start new FilterSets and that you have a CardBook inside the Finder before using one of the finder methods:
public function findBySport($sport) { $this->_filterSet = new SportCardsBySportFilter($this->getFilterSet()); $this->_filterSet->filterBySport($sport); return $this->_filterSet; } public function findByPrice($min, $max) { $this->_filterSet = new SportCardsByPriceFilter($this->getFilterSet()); $this->_filterSet->filterByPrice(20); return $this->_filterSet; } public function findBySportAndPrice($sport, $min, $max) { $this->findBySport($sport); $this->_filterSet = $this->findByPrice($min, $max); return $this->_filterSet; } public function countBySportAndPrice($sport, $min, $max) { return iterator_count( $this->findBySportAndPrice($sport, $min, $max)); } } And there you go
$cardBookFinder = new CardBookFinder($cardBook); echo $cardBookFinder->countBySportAndPrice('Baseball', 20, 100); $cardBookFinder->resetFilterSet(); foreach($cardBookFinder->findBySport('Baseball') as $card) { echo "{$card->getSport()} - {$card->getPrice()}"; } Feel free to adapt and improve for your own CardBook.
-31844597 0The answer provided by @patricus above is absolutely correct, however, if like me you're looking to also benefit from casting out from JSON-encoded strings inside a pivot table then read on.
I believe that there's a bug in Laravel at this stage. The problem is that when you instantiate a pivot model, it uses the native Illuminate-Model setAttributes method to "copy" the values of the pivot record table over to the pivot model.
This is fine for most attributes, but gets sticky when it sees the $casts array contains a JSON-style cast - it actually double-encodes the data.
The way I overcame this is as follows:
1. Set up your own Pivot base class from which to extend your pivot subclasses (more on this in a bit)
2. In your new Pivot base class, redefine the setAttribute method, commenting out the lines that handle JSON-castable attributes
class MyPivot extends Pivot { public function setAttribute($key, $value) { if ($this->hasSetMutator($key)) { $method = 'set'.studly_case($key).'Attribute'; return $this->{$method}($value); } elseif (in_array($key, $this->getDates()) && $value) { $value = $this->fromDateTime($value); } /* if ($this->isJsonCastable($key)) { $value = json_encode($value); } */ $this->attributes[$key] = $value; } } This highlights the removal of the isJsonCastable method call, which will return true for any attributes you have casted as json, array, object or collection in your whizzy pivot subclasses.
3. Create your pivot subclasses using some sort of useful naming convention (I do {PivotTable}Pivot e.g. FeatureProductPivot)
4. In your base model class, change/create your newPivot method override to something a little more useful
Mine looks like this:
public function newPivot(Model $parent, array $attributes, $table, $exists) { $class = 'App\Models\\' . studly_case($table) . 'Pivot'; if ( class_exists( $class ) ) { return new $class($parent, $attributes, $table, $exists); } else { return parent::newPivot($parent, $attributes, $table, $exists); } } Then just make sure you Models extend from your base model and you create your pivot-table "models" to suit your naming convention and voilà you will have working JSON casts on pivot table columns on the way out of the DB!
NB: This hasn't been thoroughly tested and may have problems saving back to the DB.
-5942149 0You can build using your existing makefiles and create a wrapper project with a custom target with a 'Run Script' build phase that just calls down to your makefile. This means that you'll also be able to use the debugger, but you probably won't get the full benefit of the editor with autocompletion etc.
-10831435 0you could use jQuery to remove the title attribute like so...
$(document).ready(function() { $('[title]').removeAttr('title'); });
-15844099 0 Can we have a mixed-type matrix in Matlab...and how? I'm trying to write a function with a matrix (specifically a matrix) as the output, the rows of which show a double-type variable and a binary 'status'. For no real reason and just out of curiosity, I wonder if there is a way to have the rows to have different types.
Many Thanks
-7444823 0 Jquery fading slideshow if statementHI I need to create a if statement for my slide show, if there is only one image I don't want the slideshow to be active;
Javascript:
<script type="text/javascript"> function slideSwitch() { var $active = $('#slideshow IMG.active'); if ( $active.length == 0 ) $active = $('#slideshow IMG:last'); // use this to pull the images in the order they appear in the markup var $next = $active.next().length ? $active.next() : $('#slideshow IMG:first'); // uncomment the 3 lines below to pull the images in random order // var $sibs = $active.siblings(); // var rndNum = Math.floor(Math.random() * $sibs.length ); // var $next = $( $sibs[ rndNum ] ); $active.addClass('last-active'); $next.css({opacity: 0.0}) .addClass('active') .animate({opacity: 1.0}, 1000, function() { $active.removeClass('active last-active'); }); } $(function() { setInterval( "slideSwitch()", 5000 ); }); </script> html:
<div id="slideshow"> <img src="image1.jpg" class="active" /> JS is not really my strong suit, any help would be great!
-18053942 0You are passing the values through intent correctly. I think you are getting problems while getting the passed values. Try this and this works for me.
You have to use a bundle for getting the values.
Intent intent = new Intent(); Bundle b = intent.getExtras(); int addTaskID = b.getInt("AddTask_Id, 0);
-19435060 0 It looks like Tattletale was not able to read my war. It may be because it was created for Tomcat 7.
I exploded the war to a directory with the "jar xvf" command and reran the same command on that folder:
java -Xmx512m -jar tattletale.jar myapp report This created all of the reports. I was most interested in the "unused jar" report, and I can see that it is incorrectly reporting some jars as unused, but I have gotten past my initial hurdle.
-17969272 0 Dynamic rule validation persistence between validator callsI've came across this problem a few times, but could never find a solution, only work arounds.
Lets say I have multiple 10 jobs, but depending on the answers given the validation rules are different.
foreach($jobs as $job){ if(!$this->Job->validates()){ echo 'Oh no, it didn't validate'; } } The main problem I'm finding is if I set a rule that was triggered only by the first job.
if($this->data['Job']['type'] == 'special'){ $this->validator()->add('special_field', 'notEmpty', array( 'rule' => array('notEmpty'), 'message' => 'Please provide data' )); } It would also apply to the other 9. So the rules are persistent between calls. So can could remove the rule if it exists.
if($this->data['Job']['type'] == 'special'){ $this->validator()->add('special_field', 'notEmpty', array( 'rule' => array('notEmpty'), 'message' => 'Please provide data' )); }else{ $this->validator()->remove('special_field', 'notEmpty'); } But if the rule doesn't exist when it tries to remove it a Fatal Error is thrown.
Is there any way to check a rule exists before I remove it or a way to clear dynamic rules at the start of beforeValidate?
-16251756 0Database is meant for data not files! I have come across many situation where many prefer to store it to database, be it mangodb or others. Logically that's not worth.
Your question "is it worth of programming effort?"; seriously no if you are doing once in a while. It takes a lot of effort to put things in database. However if you are a developer working on it frequently once you are get used to you, you will do it even if its not worth to do so :)
I vote for you to go for file system storage for files and not database. And for difficulties of no. of files, you will find a way to resolve it for sure.
-26067295 0You can simple add
<key>MinimumOSVersion</key> <string>6.0</string> into your AppName-app.xml manifest into "InfoAdditions" section.
This was the first thing I've tried. But this didn't help me to get rid of this error...
UPD: Just found here:
Hi,everyone.
I have the same warning too. But I was just resolved.
As a result of the update to the latest version of Mac OSX(10.9.5) that is installed in the Application loader, it came to success.
I don't know this reason. Please try.
Can anybody check if this really helps? Also it would be good to check both cases - with default MinimumOSVersion and with set to 6.0 (for example).
-32124098 0 rails-api nested attributes for a polymorphic associationI have a polymorphic association like so:
class Client < ActiveRecord::Base belongs_to :contractable, :polymorphic => true end class Individual < ActiveRecord::Base has_many :clients, :as => :contractable end class Business < ActiveRecord::Base has_many :clients, :as => :contractable end If I want to send a POST to my controller for clients (POST /clients), when I send the JSON in the request body, how do I specify to create either an individual OR a business and set the association properly?
Ex JSON (not working):
{ "client": { "name": "Person", "contractable": { "age": 50 } } } Also, how do I tell strong_params to allow this to happen?
-21104231 0Your "standard Ubuntu terminal" probably supports xterm escape codes: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
See specifically:
CSI P s ; P s ; P s t P s = 1 9 → Report the size of the screen in characters. Result is CSI 9 ; height ; width t
...and...
ESC Y P s P s Move the cursor to given row and column.
"CSI" is explained at http://en.wikipedia.org/wiki/ANSI_escape_code
-26883650 0 Clean HTML table with Reshape2New user of R. Can't think how to even ask the question. I scraped a webpage for HTML tables. Generally, everything went well, except for one table. Instead of there being 7 separate tables, everything got collapsed into 1 table, with the column name and the value for the first table being two separate columns, and all the other tables being rows. The results is a table with something like this:
df <- data.frame(is_employed = c("Hobbies", "Has Previous Experience"), false = c("squash", "false")) Obviously, I need to have the rows (and the column name) in the first column as their own columns, with the item in the second column as their values, preferably with underscores in the columns names. I tried:
df <- dcast(df, ~is_employed, value.var = "false") But got an error message. Then I thought to add another column, as such:
df2 <- data.frame(number = c(1, 2), is_employed = c("Hobbies", "Has Previous Experience"), false = c("squash", "false")) then I tried
df3 <- dcast(df2, number ~is_employed, value.var="false") That placed the values in the first columns as their own columns, but produced two rows (instead of 1), with NAs. I'm sure this is really basic, but I can't figure it out.
On edit: I think this gives me what I want, but I'm away from my computer so I can't confirm:
library("dplyr") library("tidyr") mat <- as.matrix(df) mat <- rbind(colnames(mat), mat) colnames(mat) <- c("variable", "value") df2 <- as.data.frame(mat) df3 <- df2 %>% mutate(n = 1) %>% spread(variable, value) %>% select(-n) I need to add n or I get NAs, but I don't like it.
They are quite different in purpose.
OpenAL is a low level, cross-platform API for playing and controlling sounds.
AudioSession, as the documentation puts it, is a C interface for managing an application’s audio behavior in the context of other applications. You may want to take a look at AVAudioSession which is a convenient Objective-C alternative to AudioSession.
You would typically use Audio Sessions for getting sound hardware information, determining if other applications are playing sounds, specifying what happens to those sounds when your application also tries to play sounds, etc.
Audio Sessions are all about managing the environment in which your application plays sounds. Even sounds played using OpenAL are subject to the rules imposed by your application's audio session.
You should really check out the docs. There is a lot to cover.
-30001768 0 Angular set ng-checked for specific child onclickIf someone clicks on the link the child input element should get the attribute ng-checked = "true" and if he clicks again it should be set false.
I already managed to implement this behaviour but the problem is that i have multiple checkbox probably around 20 and i do not want to set a unique variable for all of those
<a href="" ng-click="setSelect()"> <div class="checkbox"> <label> <input type="checkbox" ng-model="someModel" ng-checked= "selectStatus"> text </label> </div> </a> and the according setSelect method
$scope.toggleSelect = true; $scope.setSelect = function () { if ($scope.toggleSelect){ $scope.selectStatus = true; $scope.toggleSelect = false; } else { $scope.selectStatus = false; $scope.toggleSelect = true; } }; is it possible to do this without jquery and in an easy way?
-4360210 0Look in the project build settings for the Deployment Target setting. This is the lowest version of the SDK that you're interested in supporting. If it's lower than 4.0 then all of the pre-4.0 methods will be stripped out by the compiler (since they won't be available on the devices you're planning to deploy to). Try setting it to 4.0 or later; that should help.
-15654776 0The problem is in the predicate. It fetches all products without an image. If I download images, the result set for the predicate changes on a subsequent fetch and gets smaller every time. The solution is to process the result set in reverse order. So change:
for (NSUInteger offset = 0; offset < numberOfProducts; offset += batchSize) Into:
for (NSInteger offset = MAX(numberOfProducts - batchSize, 0); offset > 0; offset -= batchSize)
-8475202 0 const int kPadding = 4; // Padding for the diference between the font's height and the line height - it's 2 for front and 2 for bottom float maxHeight = (FONT_SIZE+kPadding)*kNumberOfLinesYouNeed; CGSize labelSize = [yourString sizeWithFont:yourFont constrainedToSize:CGSizeMake(kYourNeededWidth, maxHeight) lineBreakMode:UILineBreakModeWordWrap]; youLabel.frame=CGRectMake(yourX, yourY, kYourNeededWidth, maxHeight); I'm sorry for any mistakes. I have written this form my head.
-34973591 0 mysql multi group sumBelow is my payments mysql 5.7.9 table need hlpe to write a query
payments
|s.no |transaction |order-id |order-item-code|amount-type |amount ------------------------------------------------------------------------------------- |1 |Order |1 |11 |ItemPrice |200 |2 |Order |1 |11 |ItemPrice |100 |3 |Order |1 |11 |ItemFees |-12 |4 |Order |1 |11 |ItemFees |-1.74 |5 |Order |1 |11 |ItemFees |-10 |6 |Order |1 |11 |ItemFees |-1.45 |7 |Order |1 |11 |ItemFees |-4 |8 |Order |1 |11 |ItemFees |-0.58 |9 |Order |1 |22 |ItemPrice |150 |10 |Order |1 |22 |ItemPrice |50 |11 |Order |1 |22 |ItemFees |-12 |12 |Order |1 |22 |ItemFees |-1.74 |13 |Order |1 |22 |ItemFees |-10 |14 |Order |1 |22 |ItemFees |-1.45 |15 |Order |1 |22 |ItemFees |-4 |16 |Order |1 |22 |ItemFees |-0.58 |17 |Ship |1 | |other-transaction|-55 |18 |Ship Tax |1 | |other-transaction|-7.98 |19 |Order |2 |33 |ItemPrice |450 |20 |Order |2 |33 |ItemPrice |150 |21 |Order |2 |33 |ItemFees |-36 |22 |Order |2 |33 |ItemFees |-5.22 |23 |Order |2 |33 |ItemFees |-30 |24 |Order |2 |33 |ItemFees |-4.35 |25 |Order |2 |33 |ItemFees |-12 |26 |Order |2 |33 |ItemFees |-1.74 |27 |Ship |2 | |other-transaction|-55 |28 |Ship Tax |2 | |other-transaction|-7.98 Expected result
|order-id |order-item-code |Received --------------------------------------------- |1 |11 |238.74 |1 |22 |138.74 |2 |33 |447.71 Calculation Logic:
sum (itemprice per order-item-code) + sum(itemfees per order-item-code) + sum (other-transcation per order-id) / distinct of order-item-id in order-id
other transcation is the shipping fee charged on a order, I need to divide the sum of other transcations with no of unique items present in the order. in case of order-id- 1, we have 2 items as only two item id code, in case of order-id -2 we have one item. it is the no of distinct order-item -code present
-39030378 0Basically, the date/datetime properties in Eloquent are converted to Carbon object, so you can do it like this,
{{ $note->updated_at->format("l, h:i A") }}
-11054126 1 How to change contour colors in a range of values Colormap class in matplotlib has nice methods set_over and set_under, which allow to set color to be used for out-of-range values on contour plot.
But what if I need to set color to be used in a range of values, e.g. white out values from -0.1 to 0.1? Is there a method set_between(colormap, interval, color)? If not, what would be the easiest solution?
You can't do it with jQuery's .slideUp() and .slideDown() function because it animates height of the element. However you can add class on click and use css transform for styling them.
$("#slide").click(function() { $("#top, #bottom").toggleClass('hidden'); }); .slide { position: relative; height: 100px; background-color: yellow; overflow: hidden; } .slide .innerTop, .slide .innerBottom { transition: transform 0.25s linear; transform: translateY(0); } .slide .innerTop { position: absolute; top: 0px; } .slide .innerTop.hidden { transform: translateY(-100%); } .slide .innerBottom { position: absolute; bottom: 0px; } .slide .innerBottom.hidden { transform: translateY(100%); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button id="slide">slide it</button> <div id="slidebottom" class="slide"> <div class="innerTop" id="top">Slide from top</div> <div class="innerBottom" id="bottom">Slide from bottom</div> </div> This is encapsulation.
If you have getters like these, then private access modifiers on your fields would make them more meaningful.
private double purchase; private int numItems;
-24690196 0 I have been able to solve the problem.
Seemingly, the index for the foreign key must have the same column order that the constraint, which is something that I didn't find specified.
Changing the constraint to `fk_id_checklist` , `fk_id_user` , `fk_id_user_company` , `fk_sent_date` solves this error.
The images of your charts helped a lot in understanding what you trying to do. Using ddply with summarize from the plyr package does the same calculation as tapply but returns the result in a data frame that ggplot can use directly. Given that different data is used in the two examples, the code below seems to reproduce your chart in R:
library(plyr) df3 <- ddply(df2,.(sex, smoker), summarize, BMI_mean=mean(BMI)) ggplot(df3,aes(as.numeric(smoker), BMI_mean, color=sex)) + geom_line() + scale_x_discrete("Current Sig Smoker Y/N", labels=levels(df3$smoker)) + labs(y="Mean Body Mass Index (kg/(M*M)", color="SEX") 
I have a page with two forms and each form uses a different PHP page for its post. I can only find examples / documentation on using multiple forms with the same PHP post script. I am struggling to get this to work, can any help ?
This is the JQUERY, that works if i use one form, I've tried to add an ID tag but it didn't seem to work:
$(function () { $('form').on('submit', function (e) { var form = $(this); e.preventDefault(); $.ajax({ type: 'post', url: form.attr('action'), data: form.serialize(), success: function () { alert('Suppiler Amended!'); } }); }); }); </script> </head> <body> <?php echo "<div class='table1'>"; echo "<div class='datagrid'>"; echo "<table id='tblData2'><thead><tr><th>Notes</th><th>Updated By</th><th></th></thead></tr>"; while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) { ?> <tbody><tr> <td><FONT COLOR='#000'><b><?php echo "".$row["notes"].""?></td> <td><FONT COLOR='#000'><b><?php echo "".$row["enteredby"].""?></td> <td><FONT COLOR='#000'><b><a href="edit.php"> <form name="edit" action="script1.php" method="post"> <input type="hidden" name="notes" value="<?php echo"".$row["notes"]."";?>"> <input type="hidden" name="noteid" value="<?php echo"".$row["noteid"]."";?>"> <input type="submit" value="EDIT"> </form> </a></td> </tr></tbody> <?php $companyid = "".$row['id'].""; } ?> </table> </div> <br> <form name="notes" action="add-note.php" method="post"> ADD NEW NOTE:<br> <input type="text" name="newnote" style="height:120px;width:200px;"><br> <input type="hidden" name="companyid" value="<?php echo"".$companyid."";?>"> <input type="hidden" name="user" value="<?php echo"".$user."";?>"> <br> <input type="submit" value="ADD NOTE"> </form>
-13947664 0 C++ friendship works the other way: if GameComponent declares Position as a friend it means that Position has access to all the private methods of the GameCompenent. What you need is exactly the opposite: call Position private methods from GameComponent
So if Position::displayPositions() is the private method of the Position class that you want to access from GameComponent then you can declare GameComponent as a friend of Position:
class Position { friend class GameComponent; ... };
-9234066 0 jQuery Mobile: Which event should listview('refresh') go in? I'm developing an application which uses WebSQL DB to store data and then retrieve it. The UI is powered by jQuery Mobile, and when I successfully get back the data from the DB, I put it in a listview.
When I do that, I get the data, but with no styling at all. Just plain web browser rendering.
To refresh the layout, I looked on jQuery Mobile Docs that I need to use $('#list').listview('refresh');
Now I tried several implementations of this and always failed. I'm asking, which event should the refresh statement go in. On my page load I load the Data and put it in the DOM.
Please Help!... Thanks...
-40386029 0 How to tar bitbucket's home directory?When i try to tar /var/atlassian/application-data/bitbucket, i get 2 errors:
tar: /var/atlassian/application-data/bitbucket/shared/config/ssh-server-keys.pem: Cannot open: Permission denied tar: /var/atlassian/application-data/bitbucket/shared/bitbucket.properties: Cannot open: Permission denied How can i backup these 2 files without sudo? I plan to use it on cron.
-38385240 0 Retrieve Hive Data as JSON document using Java REST APII am trying to build a front end visualization screen and the backend data is in Hive. I am trying to develop a REST API that fetches data from Hive into JSON format from where I can use any D3.js or other libraries to display data.
I am new to this so need an advice as to which is the best approach to do this and in case you already have any examples about how to do this. Appreciate your response. Thanks.
-24233088 0The problem in your code is that, on the first button click, you are adding the value to the ArrayList, of which the state is not saved during the post back. Which means, on the Button2_Click event the array list will always be empty.
Change your value property something like this. Or Save the Arraylist value to the session in the DataList1_ItemCommand event itself
ArrayList value { get { ArrayList values = null; if(ViewState["selectedValues"] != null) values = (ArrayList)ViewState["selectedValues"]; else { values = new ArrayList(); ViewState["selectedValues"] = values; } return values; } }
-38755365 0 Running gradle with the --info flag to determine the command being run:
gradlew :app:compileHello-jniArm64- v8aDebugAllSharedLibraryHello-jniMainC --info In the output you should see a command containing aarch64-linux-android-gcc -dM -E - with a full path. Check that you do actually have this binary at the path shown (it should have been included in the android ndk).
Assuming you do, try running the command yourself. It will read from stdin and print a bunch of constants to stdout (gradle is trying to parse the version from this), but you want to see stderr:
echo '' | ./aarch64-linux-android-gcc -dM -E - 1>/dev/null If the command fails, an error should be shown which can hint at the problem. In my case it was trying to include a folder 4.9.x but I had a folder named 4.9. Most likely there will be a different problem with your setup.
Is it possible to set an elements width like this:
<img id="backgroundImg" src="images/background.png" alt="" width="javascript:getScreenSize()['width']+px" height="1100px"/> Where getScreenSize() is a javascript function.
function getScreenSize() { var res = {"width": 630, "height": 460}; if (document.body) { if (document.body.offsetWidth) res["width"] = document.body.offsetWidth; if (document.body.offsetHeight) res["height"] = document.body.offsetHeight; } if (window.innerWidth) res["width"] = window.innerWidth; if (window.innerHeight) res["height"] = window.innerHeight; alert( res['width'] ); return res; } Or do I have to change the img's width inside a javascript function?
function changeImgWidth( img ) { img.offsetRight = getScreenWidth()['width'] + "px"; }
-32257363 0 You can do it on change event. You can use on() function for binding events.
$('yourInputSelector').on('input',function(){ if( $(this).val() == 0 ) $('yourDiv').show(); else $('yourDiv').show(); });
-35514929 0 Rounding in R Returning Wrong Value Consider the following code using a modified rounding function:
round2 = function(x, n) { posneg = sign(x) z = abs(x)*10^n z = z + 0.5 z = trunc(z) z = z/10^n z*posneg } n<-387.9 d<-400 round2(n/d,4) The function should return 0.9698, but it returns 0.9697. This seems to occur during the trunc function when 9698 gets truncated to 9697. Is there another rounding function I can use (besides the default round function) to make this value correct?
-12848334 0$("input").click(function() { var dataAttr = $(this).attr("data-logic"); if (dataAttr == "yes") { var value = $(this).attr("value"); alert('Has logic ' + value); } });
-39493460 0 Hopefully you can find your answer in this:
https://jsfiddle.net/ekekp8rh/1/
Not sure what you were hoping to get but at least this displays a chart.
var data = { projects: [{ name: 'Project X', jobs_running: [ [1459814400000, 121], [1459900800000, 205], [1459987200000, 155], [1460073600000, 458] ], jobs_pending: [ [1459814400000, 146], [1459900800000, 149], [1459987200000, 158], [1460073600000, 184] ] }, { name: 'Project Y', jobs_running: [ [1459814400000, 221], [1459900800000, 295], [1459987200000, 255], [1460073600000, 258] ], jobs_pending: [ [1459814400000, 246], [1459900800000, 249], [1459987200000, 258], [1460073600000, 284] ] }] }; nueva(data); function nueva(current_data) { var seriesOptions = [], type = ['jobs_running', 'jobs_pending']; for (var j = 0; j < current_data['projects'].length; j++) { var project = current_data['projects'][j]; for (var i = 0; i < type.length; i++) { seriesOptions.push({ name: project.name + ' ' + type[i], data: project[type[i]] }); } } $('#containerChart').highcharts('StockChart', { series: seriesOptions }); }
-22060105 0 You are using System.out.println("X"); This automatically appends a newline character to the end of the string.
Instead use System.out.print("X"); to print the X's next to each other.
We are using Document List API version 3. We use two-legged OAuth and get access using permission obtained through Google Apps Marketplace. We retrieve a list of folders contained in a folder as follows: https://docs.google.com/feeds/default/private/full/folder:[folder doc id]/contents/-/folder?xoauth_requestor_id=[user name]
We get 9 results. We retain the document ids of these folders. Later on we retrieve each folder using their document id as follows where [user name] is the same as what we used previously: https://docs.google.com/feeds/default/private/full/[folder doc id]?xoauth_requestor_id=[user name]
We are able to get the document (folder) for 8 of the 9 but for one of them we get ResourceNotFoundException no matter when we try and no matter if we retry. We know that the folder still exists and the specified user has access to it.
This is similar in nature to the issue that someone else reported recently in: Document not found
Is this likely to be a google bug? Any suggestions of how to resolve it other than moving to Google Drive API?
Regards, LT
-2889797 0 Trouble getting started with Spring Roo and GWTI am trying to get started with SpringRoo and GWT after seeing the keynote... unfortunately I am stuck at this issue. I successfully created the project using Roo and added the persistence, the entities and when I perform the command "perform package" I get this error:
23/5/10 12:10:13 AM AST: [ERROR] ApplicationEntityTypesProcessor cannot be resolved 23/5/10 12:10:13 AM AST: [ERROR] ApplicationEntityTypesProcessor cannot be resolved to a type 23/5/10 12:10:13 AM AST: [WARN] advice defined in org.springframework.mock.staticmock.AnnotationDrivenStaticEntityMockingControl has not been applied [Xlint:adviceDidNotMatch] 23/5/10 12:10:13 AM AST: [WARN] advice defined in org.springframework.mock.staticmock.AbstractMethodMockingControl has not been applied [Xlint:adviceDidNotMatch] 23/5/10 12:10:13 AM AST: Build errors for helloroo; org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.codehaus.mojo:aspectj-maven-plugin:1.0:compile (default) on project helloroo: Compiler errors : error at import tp.gwt.request.ApplicationEntityTypesProcessor;
I see this in the Maven console and can't complete the build... I know there is some jar missing but how and why? Because I downloaded all the latest version including GWT milestone release. Any idea why this error is occurring? How do I resolve this issue?
-19647288 0Assuming that tbl_b.col_ba is a primary key (or just unique field) simple JOIN should help. Try this SQL:
SELECT col_aa, col_ab FROM tbl_a JOIN ( SELECT col_ba FROM tbl_b WHERE col_bb IN ( SELECT col_ca FROM tbl_c WHERE col_cb = 1 ) ) T2 ON (col_ac = T2.col_ba AND col_ad = T2.col_ba) Hope it will help
-33960649 0Looks like you need conversion from JSON to hash. (See DOCS). But, when you do to_s the output is not in pure JSON format. So, you may see I'm using gsub to replace => with :
require 'json' hash = {"description" => "test"} => {"description"=>"test"} str = hash.to_s.gsub("=>", ":") => "{\"description\":\"test\"}" JSON.parse(str) => {"description"=>"test"}
-16209274 0 You have 17GB of RAM available for about 20GB of data plus 4GB of indexes (and that's just on this DB - I don't know if there is more in your system, but mongostat says you have total datafile size of about 28GB).
If you are querying over your entire dataset, wouldn't you expect that eventually new data records being read can no longer fit into RAM without displaying some of the previously read (and loaded into RAM) records? That's what you're seeing with page faulting.
It's not data storage that you are concerned about, it's data being used or queries or accessed. If it all can't stay in RAM then it will get swapped out and then will need to be swapped back in when accessed again.
-18952554 0Download SMTP server, run the server before you click submit.
-12078361 0have you made sure that during MDM enrollment, the MDM payload (PayloadType = com.apple.mdm) you deliver has the correct Topic?
i.e. in your APN push cert that you've downloaded from apple.you'll see something like CN = com.apple.mgmt.external.[GUID]. This needs to be the same value delivered to your IOS device during MDM enrollment.
If APN does not give any error during the message upload, or the feedback service does not return the deviceID which indicates that the device is not available, it should mean that it will be delivered correctly to the device. The next phase is to determine if the IOS device is setup to listen to the APN message via this topic.
You can try connecting your device to XCode or IPCU, in the console logs, it will contain logs indicating if APN was able to successfully deliver this message using the agreed upon topic.
Here's also an article on troubleshootin APN http://developer.apple.com/library/ios/#technotes/tn2265/_index.html
there's a downloadable profile in the above article that you can load to your device for additional verbose logging.
-31909576 0You will have to ksort() your params before you pass them here:
foreach(array_keys($params) as $key) { $url_parts[] = $key . "=" . str_replace('%7E', '~', rawurlencode($params[$key])); } e.g.
$params = array( 'AWSAccessKeyId' => "MY_AWS_KEY", 'Action' => "SubmitFeed", 'SellerId' => "MY_SELLER_ID", 'FeedType' => "_POST_PRODUCT_DATA_", 'SignatureMethod' => "HmacSHA256", 'SignatureVersion' => "2", 'Timestamp'=> $timestamp, 'Version'=> "2009-01-01", 'MarketplaceIdList.Id.1' => "MY_MARKETPLACE_ID", 'PurgeAndReplace'=>'false' ); $secret = 'MY_SECRET_KEY'; $url_parts = array(); ksort($params); foreach(array_keys($params) as $key) { $url_parts[] = $key . "=" . str_replace('%7E', '~', rawurlencode($params[$key])); } I'm not entirely sure about the string you are signing, you should try it with this (adding /Feeds/2009-01-01 to it):
"POST\nmws-eu.amazonservices.com\n/Feeds/2009-01-01\n" . $url_string Also, Amazon expects a SellerId for the _POST_PRODUCT_DATA_ operation, not Merchant.
I suggest you to use mws-eu-amazonservices.com instead of the co.uk one, you can use this for all the european marketplaces and don't need to change it for each. As a sidenote:
Amazon doesn't really report the correct error. The error you are getting can also occur if only SellerId is Merchant like above, or anything different that has nothing to do with what you are trying to do.
-30035009 0I was searching for that same problem and i find this on github
https://github.com/DWorkS/AStickyHeader/issues/12
And this solved my problem.
All this says is to rename the package name on the AndroidManifast.xml file. And its done.
There is a fairly easy solution to the System.exit problem. Where you had:
System.out.println("the size of Hashmap is: " + jobCountMap.size()); System.exit(job.waitForCompletion(true) ? 0 : 1); Instead place the following:
System.out.println("the size of Hashmap is: " + jobCountMap.size()); boolean completionStatus = job.waitForCompletion(true); //your code here if(completionStatus==true){ System.exit(0) }else{ System.exit(1) } This should allow you to run any processing you want within your main function, including starting a second job if you want.
-1899843 0 Is there a nosql store that also allows for relationships between stored entities?I am looking for nosql key value stores that also provide for storing/maintaining relationships between stored entities. I know Google App Engine's datastore allows for owned and unowned relationships between entities. Does any of the popular nosql store's provide something similar?
Even though most of them are schema less, are there methods to appropriate relationships onto a key value store?
-3626662 0 Android, Google Analitics: how to implement page view tracking on "/quit" application exit?I need to track my Android application exit as a page view. My application has several activities, but there is no hierarchy, so there is not an unique exit point.
My understanding is that "application exit" means another application is on top of mine, hiding it completely. So if my application is no more visible, there is an "application exit". Is my understanding correct?
So, how could I track this "application exit" with Google Analytics?
Looking forward for advice. Thank you.
-5868669 0You should just change the "upload_path" value in your configuration Array.
Here is some kind of code you could use :
$config['upload_path'] = './uploads/'; $this->load->library('upload', $config); Referring to the User Guide : http://codeigniter.com/user_guide/libraries/file_uploading.html
-30097122 0I have a more compact method.
I think it's more readable and easy to understand. You can refer as below:
This is your var I delcare response:
response = [ {'country': 'KR', 'values': ['Server1']}, {'country': 'IE', 'values': ['Server1', 'Server3', 'Server2']}, {'country': 'IE', 'values': ['Server1', 'Server3']}, {'country': 'DE', 'values': ['Server1']}, {'country': 'DE', 'values': ['Server2']}, ] Let's merge the values.
new_res = {} for e in response: if e['country'] not in new_res: new_res[e['country']] = e['values'] else: new_res[e['country']].extend(e['values']) You can print new_res if you want to know its content. It's like as below:
{ 'KR': ['Server1'], 'DE': ['Server1', 'Server2'], 'IE': ['Server1', 'Server3', 'Server2', 'Server1', 'Server3'] } Invoking collections module collects elements:
from collections import Counter new_list = [] for country, values in new_res.items(): # elements are stored as dictionary keys and their counts are stored as dictionary values merge_values = Counter(values) # calculate percentage new_values = [] total = sum(merge_values.values()) for server_name, num in merge_values.items(): #ex: Server1-40.0 new_values.append("{0}-{1:.1f}".format(server_name, num*100/total)) percent = merge_values["Server1"]*1.0*100/total new_list.append({"country": country, "percent": percent, "values": new_values}) You can print new_list when finishing calculating result:
[{'country': 'KR', 'percent': 100.0, 'values': ['Server1-100.0']}, {'country': 'DE', 'percent': 50.0, 'values': ['Server1-50.0', 'Server2-50.0']}, {'country': 'IE', 'percent': 40.0, 'values': ['Server1-40.0', 'Server2-20.0', 'Server3-40.0']}] So you can get answer you want.
-31860435 0 What is the easiest way to truncate an IP address to /24 in C?Is there a method that can truncate the IP address to /24? Or, should I parse the IP address manually and do the conversion?
Edit:
Ip address is IPv4 and is stored in the Dotted decimal format surrounded by quotes as char *. I am expecting the /24 to be char * too.
Example format: "64.233.174.94" .
/24 expected format: "64.233.174.0"
Hope this helps. Thanks.
-20215732 0 How could uptime command show a cpu time greater than 100%?Running an application with an infinite loop (no sleep, no system calls inside the loop) on a linux system with kernel 2.6.11 and single core processor results in a 98-99% cputime consuming. That's normal. I have another single thread server application normally with an average sleep of 98% and a maximum of 20% of cputime. Once connected with a net client, the sleep average drops to 88% (nothing strange) but the cputime (1 minute average) rises constantly but not immediately over the 100%... I saw also a 160% !!?? The net traffic is quite slow (one small packet every 0.5 seconds). Usually the 15 min average of uptime command shows about 115%.
I ran also gprof but I did not find it useful... I have a similar scenario:
IDLE SCENARIO %time name 59.09 Run() 25.00 updateInfos() 5.68 updateMcuInfo() 2.27 getLastEvent() .... CONNECTED SCENARIO %time name 38.42 updateInfo() 34.49 Run() 10.57 updateCUinfo() 4.36 updateMcuInfo() 3.90 ... 1.77 ... .... None of the listed functions is directly involved with client communication
How can you explain this behaviour? Is it a known bug? Could be the extra time consumed in kernel space after a system call and lead to a calculus like
%=100*(apptime+kerneltime)/(total apps time)?
-9248418 0 ID item of item to be edited is passed to edit form in the query string like this: editform.aspx?ID=ItemId. So, first, check if ID is in the url and correct.
-34394168 0You need to change this line
$("myTable tr td") to
$("#myTable tbody tr td") //missing pound sign & your tds are inside tbody
-2687532 0 This is possible.
class Object class << self Kernel.send :define_method, :foo do #Object.send to be more restrictive @foo = 'bar' end end end .
irb(main):023:0> class Object irb(main):024:1> class << self irb(main):025:2> Kernel.send :define_method, :foo do irb(main):026:3* @foo = 'bar' irb(main):027:3> end irb(main):028:2> end irb(main):029:1> end => #<Proc:0x00007f5ac89db168@(irb):25> irb(main):030:0> x = Object.new => #<Object:0x7f5ac89d6348> irb(main):031:0> x.foo => "bar" irb(main):032:0> [].foo => "bar" irb(main):033:0> //.foo => "bar" It's important to understand eigenclasses. Every class is implemented mysteriously by the Ruby interpreter as a hidden class type:
irb(main):001:0> class Object irb(main):002:1> def eigenclass irb(main):003:2> class << self; self; end irb(main):004:2> end irb(main):005:1> end => nil irb(main):006:0> x = Object.new => #<Object:0x7fb6f285cd10> irb(main):007:0> x.eigenclass => #<Class:#<Object:0x7fb6f285cd10>> irb(main):008:0> Object.eigenclass => #<Class:Object> irb(main):009:0> Object.class => Class So, in your example, when you're trying to call foo on your objects, it's operating on the class #<Object:0x7fb6f285cd10>. However, what you want it to operate on is the secret class #<Class:#<Object:0x7fb6f285cd10>>
I hope this helps!
-8814194 0 TableViewCell's textLabel value returns to 1 when cell is scrolled out of the viewi have a table view in which i can add 1 or subtract 1 to the value of my cell.textLabel.text but when i switch views and return or scroll a cell out of the view, and when it comes back into view, the textLabel's value returns to 1 which is the original starting point! Please help! Here is the code to add and subtract 1:
- (IBAction)addLabelText:(id)sender{ cell = (UITableViewCell*)[sender superview]; // <-- ADD THIS LINE cell.textLabel.text = [NSString stringWithFormat:@"%d",[cell.textLabel.text intValue] +1]; } - (IBAction)subtractLabelText:(id)sender { cell = (UITableViewCell *)[sender superview]; if ( [[cell.textLabel text] intValue] == 0){ cell.textLabel.text = [NSString stringWithFormat:@"%d",[cell.textLabel.text intValue] +0]; } else{ cell.textLabel.text = [NSString stringWithFormat:@"%d",[cell.textLabel.text intValue] -1]; } }
-32571066 0 You are forgetting the if(i%2==0) which is crucial. This line basically skips every second character. Then, the line you have identified can be split in 2 parts:
string[j]=string[i]; // Overwrite the character at position j j++; // Now increase j The variable i keeps track of the position of the string you have reached while reading it; j is used for writing. In the end, you write 0 at position j to terminate the string.
Consider the following:
> console.log({ foo : { bar : [ { xxx : 1 } ] } }) { foo: { bar: [ [Object] ] } } This is showing similar output to what you are seeing. The reason for the unexpected output is that a regular console.log() will only show nested objects up to a specific depth, after which it will abbreviate the output (in this case, it will show [Object] instead of the actual object). This doesn't mean the object is invalid, though, it's just shown in this shorter format when you print it.
One solution to get to see the whole object is to convert it to JSON first:
> console.log('%j', { foo : { bar : [ { xxx : 1 } ] } }) {"foo":{"bar":[{"xxx":1}]}} Or, in your case:
console.log('%j', data);
-20837850 0 Tailor ansible roles to environment I have a number of environments, that require a bunch of text files to be tailored in order for things like mule to speak to the right endpoints.
For this environment, this works:
ansible-playbook test03.yml The only difference between an environment (from ansible's perspective) is the information held in ./roles/esb/vars/main.yml.
I've considered using svn to keep a vars/main.yml for each environment, so each time I need to configure an environment I check out roles and then vars/main.yml for that environment, before I run the command above.
To me, not an elegant solution. How can I do this better?
Directory structure
./test03.yml ./roles/esb/vars/main.yml ./roles/esb/tasks/main.yml ./roles/esb/templates/trp.properties.j2 ./test03.yml
--- - hosts: test03-esb gather_facts: no roles: - esb ./roles/esb/vars/main.yml
--- jndiProviderUrl: 'jnp://mqendpoint.company.com:1099' trp_endpoint_estask: 'http://tmfendpoint.company.com:8080/tmf/estask' trp_endpoint_builderQ: 'jnp://mqendpoint.company.com:1099' ./roles/esb/tasks/main.yml
--- - name: replace variables in templates template: src=trp.properties.j2 dest=/path/to/mule/deploy/conf/trp.properties ./roles/esb/templates/trp.properties.j2
trp.endpoint.estask={{ trp_endpoint_estask }} trp.endpoint.builderQ={{ trp_endpoint_builderQ }}
-7738588 0 BufferedImage turns all black after scaling via canvas I have a method which purpose is to receive an image and return it scaled down. The reason I'm using canvas is that I believe that it will scale the image automatically for me.
After the conversion the outputimage is completely black. Anyone have any clue on how to fix this?
try { InputStream in = new ByteArrayInputStream(f.getBytes()); BufferedImage image = ImageIO.read(in); File beforescale = new File("beforescale.jpg"); ImageIO.write(image, "jpg", beforescale); //works Canvas canvas = new Canvas(); canvas.setSize(100, 100); canvas.paint(image.getGraphics()); image = canvasToImage(canvas); File outputfile = new File("testing.jpg"); ImageIO.write(image, "jpg", outputfile); //all black response.getWriter().print(canvas); } catch (Exception ex) { ex.printStackTrace(); } } private BufferedImage canvasToImage(Canvas cnvs) { int w = cnvs.getWidth(); int h = cnvs.getHeight(); int type = BufferedImage.TYPE_INT_RGB; BufferedImage image = new BufferedImage(w,h,type); Graphics2D g2 = image.createGraphics(); cnvs.paint(g2); g2.dispose(); return image; }
-33283325 0 A Self-closing tag is a special form of start tag with a slash immediately before the closing right angle bracket. These indicate that the element is to be closed immediately, and has no content. Where this syntax is permitted and used, the end tag must be omitted. In HTML, the use of this syntax is restricted to void elements and foreign elements. If it is used for other elements, it is treated as a start tag. In XHTML, it is possible for any element to use this syntax. But note that it is only conforming for elements with content models that permit them to be empty.
The examples you listed would generally contain content, JavaScript, or other elements, so having a proper start and end tag would delimit the scope of those elements/tags.
-29892707 1 set value to 99 percentile for each column in a dataframeI am working with the data which looks like a dataframe described by
df = pd.DataFrame({'AAA' : [1,1,1,2,2,2,3,3], 'BBB' : [2,1,3,4,6,1,2,3]}) what i would like to do is to set value to roundup(90%) if value exceeds 90 percentile. So its like capping max to 90 percentile. This is getting trickier for me as every column is going to have different percentile value.
I am able to get 90 percentile value using
df.describe(percentiles=[.9]) so for column BBB 6 is greater than 4.60 (90 percentile), hence it needs to be changed to 5 (roundup 4.60).
In actual problem I am doing this for large matrix, so I would like to know if there is any simple solution to this, rather than creating an array of 90 percentile of columns first and then checking elements in for a column and setting those to roundup of 90 percentile
-17817348 0 Total pages in PDF using html2pdfI have some HTML using which I am printing a PDF, I would like to get the count of total pages the PDF will produce in a PHP Variable.
$html2pdf = new HTML2PDF('P', 'A4'); $html2pdf->writeHTML($html, false); $html2pdf->Output('myfile.pdf'); I would like to do something like..
$totalpages = $html2pdf->getTotalPageCount(); //should return total pages the myfile.pdf would produce.
-14552521 0 You can see this post, it seems that you have a similar JSONArray.. you can simply use:
JSONArray yourArray = new JSONArray(jsonString); // do the rest of the parsing by looping through the JSONArray
-3166759 0 // Here UL will be the id attribute, not the <ul> element. var UL = document.createElement('ul').id = 'meta-ul'; // this doesn't makes sense... (id.appendChild) UL.appendChild(li1) ; // solution: var UL = document.createElement('ul'); UL.id = 'meta-ul'; And the same goes for Dialog and Tabs. (your li1 and li2 are fine)
Oh, and as long as you're not using anything starting with $, you cannot conflict with jQuery.
-10103473 0What about:
select std.name ,(select count(1) from STUD_Name) nrofstds from STUD_Name std where std.id='2'
-7064737 0 How to select Dev Express's WPF GridControl row? I want to select GridControl's row, after data binding:
- Get selected row
- Bind GridControl with new Data
- Select GridControl's row
I'm trying so, but with no success:
int selectedRowhandle = gridControl1.View.GetSelectedRowHandles()[0]; gridControl1.DataSource = "DataSource..."; gridControl1.View.SelectRow(selectedRowhandle); How can I do this in DevExpress.Xpf.Grid.GridControl?
Thanks.
-8738380 0Just use preventDefault and it will work
$("#txt1").bind('keydown', function (e) { if (e.which == 9) { $("#txt2").focus(); e.preventDefault() } } ); BTW, its much better to use direct selectors with ids (#txt2 instead of input[id$=txt2]).
-17415160 0Solved partially (please read bottom of this) separating up\down movement from left\right: changed the above mousemove function to
if (event->buttons() & Qt::RightButton) { setMatrixes(); gluUnProject(event->x(), -event->y(), 0, model_matrix, proj_matrix, view_matrix, &newx, &newy, &newz); float acc=sqrt((int)dx^2+(int)dy^2); acc*=acc; qDebug()<< acc; if (dy<dx){ if (event->x()>lastPos.x()){ emit SignalPreviewMouseChanged((float)(newx/2500)*acc,0,(float)(-newz/2500)*acc); } else { emit SignalPreviewMouseChanged((float)(-newx/2500)*acc,0,(float)(newz/2500)*acc); } } else{ if (event->y()<lastPos.y()) emit SignalPreviewMouseChanged(0,(float)(newy/1750)*acc,0); else { emit SignalPreviewMouseChanged(0,(float)(-newy/1750)*acc,0); } } isPressed=true; } lastPos = event->pos(); updateGL(); while in the controller:
void Controller::SlotMouseTranslationValueChanged(float val1, float val2, float val3){ if (val1!=0) sceneRef->translate(val1,0,0); if (val2!=0) sceneRef->translate(0,val2,0); if (val3!=0) sceneRef->translate(0,0,val3); facade->window->getPreview()->RebuildScene(); } Now it has no lag and everything works fine.
Consideration:
Now I am not dragging the object but using the gluUnproject to retrieve the plan on which my object can move (then calling translate function that add\sub values to object position).So where my mouse points to is different from the position of the object on my screen.
How to achieve this result?could someone explain me the logical steps?
-14206730 0$("[ref=B]").append($(data).find("[ref=A]")); The way you do it in your question, the last part find( '[ref=A]' ) is useless.
[Edit] Also, the other question is more than 2 years old. For recent versions of jQuery you might need additional quotes:
$("[ref='B']").append($(data).find("[ref='A']"));
-16410844 0 Multiple matches for syntax highlighting in VIM I'm writing a syntax file to match a log format (basically column based; think syslog for a similar example), and I'm trying to set up a type of inheritance for columns.
I have two main goals with this.
First, I want to say that column 3 is the "component" field (let's say it's marked by a header; it could also be at a fixed position) and set the background to, say, Grey. I then want to say that component "foo" gets a foreground color of Red, and component "bar" gets a foreground color of Green, but they should inherit the background color of the "component" column. In this case, the field should really have two syntax matches; this also makes it easy to conceal the entire column (a la Toggling the concealed attribute for a syntax highlight in VIM)
Second, there's a field for levels; I want to set the background of the entire line for a critical level message to Red, but the foreground should be continue to be set via the normal highlighting (component, source, etc; I left off most of the other requirements).
From what I can see in the vim documentation, this doesn't seem possible. Am I missing something? Alternatively, can anyone suggest a good workaround?
Thanks
-32486438 0Try git clone origin-url . (with dot)
Example:
hg clone https://Name@bitbucket.org/mitsuhiko/flask .
-6804386 0 RMagick: Setting opacity on a png that already has transparent elements I need to compose images in rmagick. If I put a png that has transparent regions on another image and set the opacity of that png to 50% the parts that where transparent become white (with 50% opacity). But I want these regions to stay transparent.
Here's my code:
canvas = Magick::Image.new(1024,768) canvas.opacity = Magick::MaxRGB image = Magick::ImageList.new('/tmp/trans.png').first image.background_color = "none" image.opacity = Magick::MaxRGB/2 canvas.composite!(image, 50, 50, Magick::OverCompositeOp) canvas.write('/tmp/composite.png') Any suggestions?
-30083314 0I do not know how many records you have in each table. If they it is a relatively small number you may be better finding a way of holding them in memory rather than querying each time.
-14284922 0Possible dupplicate of ASP.NET MVC bind array in model
Here is blogpost explaining what you have to do.
-13858364 0If you do not want to change your pom.xml you may set the skip to true from command line using the –D option. This was mentioned above as "overridden the skip parameter within an execution". This is quite similar to -Dmaven.test.skip=true usage.
mvn site -Dcheckstyle.skip=true
-7259030 0 I know this isn't an ideal solution but you could use a HTML5 worker instead of setInterval (though I don't know if they are paused in the background as well - I'm assuming they are not, that would be very odd if they were)?
And it does add lots of backwards compatibility issues for PC browsers that are not HTML5 compliant :(
http://www.sitepoint.com/javascript-threading-html5-web-workers/
-29071106 0F# uses single = for equality operator:
let t = seq { 1..10 } |> Seq.takeWhile (fun e -> e % 2 = 0)
-10430603 0 Windows-1251 or code page CP1251 is a popular 8-bit character encoding, designed to cover languages that use the Cyrillic script such as Russian, Bulgarian, Serbian Cyrillic and other languages. It is the most widely used for encoding the Bulgarian, Serbian and Macedonian languages. In modern applications, Unicode is a preferred character set.
Source and more information: Windows-1251 on the English Wikipedia
-7718532 0 Adaptively render views in Ruby on RailsIn a RoR app, I have all partial views and a single layout page. If the request is ajax, I want to return only the partially rendered html, otherwise I want to return the fully rendered html page.
What is the most efficient way to do this in RoR? I would prefer to do this at the application level rather than in every single controller action.
-18385021 0 Django ModelForm with prefixI have a template with 2 forms. I would like to use "prefix" parameter to have different id in my rendered template like that :
My first form :
<input id="id_folder-name" maxlength="75" name="folder-name" type="text" /> My second form :
<input id="id_file-name" maxlength="75" name="file-name" type="text" /> I my view, I instantiate forms :
self.form_class(prefix="folder") self.form_class_upload(prefix="file") but it doesn't work, see console log :
[23/Aug/2013 11:15:57] "GET /sample/ HTTP/1.1" 200 1037 invalid <tr><th><label for="id_name">Name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input id="id_name" maxlength="75" name="name" type="text" /></td></tr> [23/Aug/2013 11:16:50] "POST /sample/new-folder/ HTTP/1.1" 200 634 So it doesn't call my form_valid method...
I don't understand why Django doesn't consider 'prefix' parameter for validation form.
models.py:
from django.db import models class Inode(models.Model): name = models.CharField(max_length=75) file = models.FileField(upload_to="files", null=True) def __unicode__(self): return self.name forms.py :
from django import forms from .models import Inode class FileUploadForm(forms.ModelForm): class Meta: model = Inode fields = ['name', 'file'] class NewFolderForm(forms.ModelForm): class Meta: model = Inode fields = ['name'] views.py :
from django.views.generic import TemplateView from django.views.generic.edit import FormView from .forms import FileUploadForm, NewFolderForm from .models import Inode class MainView(TemplateView): template_name = "sample/browser.html" form_class = NewFolderForm form_class_upload = FileUploadForm def get_context_data(self, **kwargs): context = super(MainView, self).get_context_data(**kwargs) context['form_new_folder'] = self.form_class(prefix="folder") context['form_upload'] = self.form_class_upload(prefix="file") context["inodes"] = [i for i in Inode.objects.all()] return context class NewFolderView(FormView): template_name = "sample/browser.html" form_class = NewFolderForm success_url = "/sample" def form_invalid(self, form): invalid = super(NewFolderView, self).form_invalid(form) print "invalid" print form return invalid def form_valid(self, form): isvalid = super(NewFolderView, self).form_valid(form) print "valid" return isvalid template :
<!DOCTYPE html> <html lang='fr' xml:lang='fr'> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>sample</title> </head> <body> <form method="post" action="{% url 'sample-new-folder' %}"> {% csrf_token %} {{form_new_folder}} <input type="submit" value="Valider"/> </form> <form method="post" action="{% url 'sample-upload' %}"> {% csrf_token %} {{form_upload}} <input type="submit" value="Valider"/> </form> </body> </html> rendered template :
<html lang='fr' xml:lang='fr'> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>sample</title> </head> <body> <form method="post" action="/sample/new-folder/"> <input type='hidden' name='csrfmiddlewaretoken' value='btopdI8WyHgqG2ZSTG81yhmaDa9Rk7Is' /> <tr><th><label for="id_folder-name">Name:</label></th><td><input id="id_folder-name" maxlength="75" name="folder-name" type="text" /></td></tr> <input type="submit" value="Valider"/> </form> <form method="post" action="/sample/upload/"> <input type='hidden' name='csrfmiddlewaretoken' value='btopdI8WyHgqG2ZSTG81yhmaDa9Rk7Is' /> <tr><th><label for="id_file-name">Name:</label></th><td><input id="id_file-name" maxlength="75" name="file-name" type="text" /></td></tr> <tr><th><label for="id_file-file">File:</label></th><td><input id="id_file-file" name="file-file" type="file" /></td></tr> <input type="submit" value="Valider"/> </form> </body> </html>
-39181653 0 AutoCompleteDecorator.decorate(combobox); is not working perfectly in JTable I'm using A JCombobox with editable = true in a JPanel and using a JTable in the same panel with a column that is set to show combobox as its field type. I applied
AutoCompleteDecorator.decorate(cb); to JCombobox that is outside the JTable and its working perfectly But when I applied the same line of code to combobox within jtable which selects the first occurrence of the data that match the key typed.
How can I resolve this issue. Any Suggestion ?
Look at the image below in which the exact item is selected that I typed.
And this is the image of combobox within JTable.
When I press w key it select the first occurrence windy and set it in the cell.
The format of the value you are passing into the constructor of the MediaTypeHeaderValue is invalid. You are also trying to add multiple content types to the header value.
Content type header takes a single type/subtype, followed by optional parameters separated with semi-colons ;
eg:
Content-Type: text/html; charset=ISO-8859-4 For your result you need to decide on which one you want to use. application/zip or application/octet-stream
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip"); Also, to avoid exception you can use the MediaTypeHeaderValue.TryParse method
var contentTypeString = "application/zip"; MediaTypeHeaderValue contentType = null; if(MediaTypeHeaderValue.TryParse(contentTypeString, out contentType)) { result.Content.Headers.ContentType = contentType; }
-16246386 0 You can do this with "while read" and avoid awk if you prefer:
while read a b c d e f g h i; do if [ ${a:0:2} == "Ge" ]; then echo $h $i >> allgood.txt; elif [ ${a:0:2} == "ea" ]; then echo $c $d >> allgood.txt; fi; done < abc.txt The letters represent each column, so you'll need as many as you have columns. After that you just output the letters you need.
-36267287 0Implicit sharing in Qt follows the CoW (copy on write) paradigm - objects will implicitly share the same internal resource as long as it is not modified, if some of the copies attempts to modify the resource, it will be "detached" from the shared resource, copy it and apply the modifications to it.
When object lifetime ends, it decrements the reference counter for the shared resource, and if it is zero that means no other object uses it, so it is deleted. If the reference count is more than zero, the resource remains alive until there are objects, referencing it.
In case 1 the shared resource will be deleted, as there are no more objects referencing it.
In case 2 it will be deleted as well, because aImg will be out of scope by the time tImg is deleted.
For my school project I have to realize a mini website where I use primefaces framework. In a form I want after pressing the Save button two things: 1 - Validate the data entered. that's why I put
<p:message for="date" /> and <p:message for="zone" /> As the values are not correct, the dialog box should not be displayed. 2 - When all data is correct, and I click Save, I want to display my dialog box.
Now I can not. Can you help me? I use version 4 primefaces.
<h:form> <p:panel id="panel" header="Create" style="margin-bottom:10px;border-color:blueviolet" > <p:messages id="messages" /> <h:panelGrid columns="3"> <h:outputLabel for="date" value="Date : *" /> <p:calendar locale="fr" id="date" value="#{newBusinessCtrl.exercice.debut}" required="true" label="date" showButtonPanel="true"/> <p:message for="date" /> <h:outputLabel for="zone" value="Zone Monétaire: *" /> <p:selectOneMenu id="zone" value="#{newBusinessCtrl.exercice.zoneChoice}" > <f:selectItem itemLabel="Choice " itemValue="" /> <f:selectItems value="#{newBusinessCtrl.exercice.zones}" var="azone" itemLabel="#{azone}" itemValue="#{azone}" > </f:selectItems> <p:message for="zone" /> </p:selectOneMenu> <p:message for="zone" /> </h:panelGrid> </p:panel> <p:commandButton update="panel" value="Save" icon="ui-icon-check" style="color:blueviolet" onclick="choice.show()"/> <p:confirmDialog message="Would you like to create accounts automatically ?" header="Account creation" severity="alert" widgetVar="choice" appendTo="@(body)"> <p:button outcome="personalizeAccount" value="Personalize" icon="ui-icon-star" /> <p:button outcome="autoAccount" value="Continue" icon="ui-icon-star" /> </p:confirmDialog>
-1518073 0 Embed pdb into assembly I want my application to be distributable as a single .exe file but I want to be able to get nice error reports with source code line numbers (the application simply sends email with exception.ToString() and some additional information when unhandled exception occurs).
Is there any way to embed .pdb into assembly?
-27615170 0 Transfering data from textbox to 2D ArrayI am a new in C sharp and a little stupid, I have a problem with my project, hope you can help me!
Suppose I have a textbox1 as follow (n rows x n columns):
0 1 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 Now I want to transfer data from this text box into an existed 2d Matrix that will store data in Integer Type.
I tried this but it seem to not works:
private void GETNUMERICDATA() { string txt = textbox1.text; txt = txt.Replace(" ", string.Empty); for (int k = 0; k < 32; k++) { for (int l = 0; l < 32; l++) { for (int i = 0; i < txt.Length; i++) { char chr = txt[i]; if (chr == '0') { Matrix[k, l] = (int)char.GetNumericValue('0'); } else { if (chr == '1') Matrix[k, l] = (int)char.GetNumericValue('1'); } } } } } Anybody can help me how to do it? All your support would be highly appreciated.
-11697733 0You're wrong about what's causing that error. On windows *.exe has stopped working. generally means that your application has segmentation faulted.
This can be caused by any read or write out of the memory bounds, which generally means you messed up with a free()/delete, a malloc()/new, or a NULL somewhere, but with more code, or without further explanation, I cannot diagnose further.
I have a large bit stream. (e.g. 10110001010101000.....001 size thousands or millions)
I want to assign this bit stream into a one column vector x.
x = zeros(n,1); I have tried to use some mod or rem operations, there will have some problems.
I guess it caused by the integer size.
I want to ask is there any good method to solve this problem?
Thanks for reading.
-15976195 0This is my OK code in QT 4.7:
//add combobox list QString val; ui->startPage->clear(); val = "http://www.work4blue.com"; ui->startPage->addItem(tr("Navigation page"),QVariant::fromValue(val)); val = "https://www.google.com"; ui->startPage->addItem("www.google.com",QVariant::fromValue(val)); val = "www.twitter.com"; ui->startPage->addItem("www.twitter.com",QVariant::fromValue(val)); val = "https://www.youtube.com"; ui->startPage->addItem("www.youtube.com",QVariant::fromValue(val)); // get current value qDebug() << "current value"<< ui->startPage->itemData(ui->startPage->currentIndex()).toString();
-11761122 0 from o in dc.Orders group o by new { o.Product.ProdName, o.Size.Size } into g select new { g.Key.ProdName, g.Key.Size, Total = g.Sum(or => or.Qty))};
-38943954 0 If you want to return two values, return a std::vector with them. Maybe a std::pair, or a class. As far as why, this is just how C++ works. Comma is just an operator, like + or -. It discards its left operand and returns the right one. return returns the value of its expression from the function. The rest you can figure out yourself.
You can use the RowCommand instead, like..
protected void cgvProjectPropertyList_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Delete") { e.CommandArgument // will Return current Row primary key value, rather row Index } } and you need to make sure to register the event in the GridView OnRowCommand="cgvProjectPropertyList_RowCommand"
You need define your post contain some file inside with multipart HTML tag
<%= semantic_form_for @imgD, :html => { :multipart => true } do |form| %> <%= form.input :img%> <%= form.actions %> <%end%>
-11926172 0 I have js error , saying Object [object Object] has no method 'countdown' I have a website working fine in all browsers except IE. When I look at the console it says:
Object [object Object] has no method 'countdown' The website name is: http://www.rivalhost.com/
The problem is with menu. Please help me out of this guys. Thanks in advance
-27146581 0if(is_array($variable) && count($variable) > 0) { foreach($variable as $key => $value) { //Your code } )
-30258295 0 Is my HTTP protocol design correctly implemented in the coding? It's my very simple client-server application. Client sends some commands to the server and server gives back the output to the client. However, my special concern is about the GET command sent to the server. The client request GET filename to download a named file. That file ultimately gets downloaded into the client directory with the HTTP response headers, as I have designed my protocol.
Now I am afraid if my coding follows the protocol accurately. Especially the HTTP response headers with the Line break (in both client and server side).
PROTOCOL DESIGN:
Client:
syntax: GET namedfile CRLF CRLF meaning: downloading the named file from the server representation: text file server:
syntax: Status: ok CRLF Length: 20 bytes CRLF CRLF File contents meaning: The file exist in the server and ready to download representation: text file CODE:
ServerSide:
................. ................. else if (request.startsWith("GET")) { System.out.println(""); String filename = request.substring(4); File file = new File(System.getProperty("user.dir")); File[] files = file.listFiles(); if (fileExists(files, filename)) { file = new File(filename); int fileSize = (int) file.length(); outputToClient.print("Status OK\r\n" + "Size " + fileSize + "KB" + "\r\n" + "\r\n" + "File " + filename + " Download was successfully\r\n"); outputToClient.flush(); // reading files fis = new FileInputStream(file); os = socket.getOutputStream(); byte[] buffer = new byte[2^7-1]; int bytesRead = 0; while ((bytesRead = fis.read(buffer))!= -1) { os.write(buffer, 0, bytesRead); } os.close(); fis.close(); } else { outputToClient.print("Status 400\r\n" + "File " + filename + " not found\r\n" + "\r\n"); outputToClient.flush(); } } outputToClient.flush(); } ................. ................. ClientSide:
............ ............ if (request.startsWith("GET")) { File file = new File(request.substring(4)); is = socket.getInputStream(); fos = new FileOutputStream(file); byte[] buffer = new byte[socket.getReceiveBufferSize()]; int bytesReceived = 0; while ((bytesReceived = is.read(buffer)) >=0) { //while ((bytesReceived = is.read(buffer))>=buffer) { fos.write(buffer, 0, bytesReceived); } request = ""; fos.close(); is.close(); } ................. .................
-19470436 0 The PID is
PID := DWORD(List.Objects[Index]); Where Index is the index of the item of interest.
-23657120 0 argument getting truncated while printing in unix after merging filesI am trying to combine two tab seperated text files but one of the fields is being truncated by awk when I use the command (pls suggest something other than awk if it is easier to do so)
pr -m -t test_v1 test.predict | awk -v OFS='\t' '{print $4,$5,$7}' > out_test8 The format of the test_v1 is
478 192 46 10203853138191712 but I only print 10203853138 for $4 truncating the other digits. Should I use string format? Actually I found out after a suggestion given that pr -m -t itself does not give the correct output
478^I192^I46^I10203853138^I^I is the output of the command pr -m -t test_v1 test.predict | cat -vte I used paste test_v1 test.predict instead of pr and got the right answer.
-38632018 0Regarding the blank-page issue: You're just processing, not outputting anything. You could simply post a redirect-header at the end - possibly according to errors occuring or not.
// 307 Temporary Redirect header("Location: /foo.php",TRUE,307); ..or just output stuff after processing. A good practice might be to keep processing and the form-display in one file - then you could pre-populate the form with the fields that did not produce errors and mark those that failed so the user can try again.
Regarding the checkbox-group issue:
echo implode( ", ", $_POST['checkbox-group'] ); to prove to yourself you actually got something passed along:
header("Content-type:text/plain;charset=utf-8"); echo print_r($_POST,TRUE);
-39606139 0 canvas = this.transform.FindChild ("HealthCanvas").gameObject; hb = canvas.transform.FindChild ("HealthBar").gameObject;
-29433031 0 If the possible duplicate doesn't fulfil your needs here's a way to do it - Plunker.
JS
app = angular.module("app", []); app.directive("test", [ function() { return { restrict: "E", template: "<div ng-repeat='item in ts.items track by $index' ng-init='ts.blah($index, $last)'>{{$index}}</div>", scope: {}, controllerAs: "ts", bindToController: true, controller:function() { var ts = this; ts.items = [0, 1, 2, 3, 4]; ts.blah = function(index, last) { console.log(index, last); if (last) { // Do your stuff } } } } }]); Markup
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script> <link rel="stylesheet" href="style.css"> <script src="script.js"></script> </head> <body ng-app="app"> <test></test> </body> </html> The output from the console is:
0 false
1 false
2 false
3 false
4 true
so you should (in theory) be able to rely on the last repeat element being created last.
-33571948 0In your local copy of the repo, edit progressbar/__init__.py and change the following line:
__version__ = '2.3dev' to
__version__ = '2.3.1' Save the file, then reinstall with pip. Of course, without a pull request, this will only work locally for you.
Another option is to use the much more up-to-date progressbar2, on Github here. It has been validated to work up to Python 3.5. Obviously, you'll have to test your code to ensure it works with the new version, but this is probably your best bet.
I'm trying to do a fairly simple load function with Jquery (at least I think it is), but it simply isn't loading anything.
On this page here (http://new.visibilitysoftware.com/careers/), I am trying to load the div#center-stage from here: http://www.vspublic.com/VSCareers/Careers.aspx. I have tried it with and without the /careers.aspx. I have also tried it with #center-stage and #center-stage.content as jquery parameters for the function.
I'm sure it's something obvious, but I simply can't find it. I appreciate any help. Thanks
-9186364 0 How do I display a list of items from a Bean onto a JSF webpage?I'm new to JSF and in the process of learning im building an online book store application.
I have 1 class and 1 bean: Book.java and BookCatelogBean.java. The Book class has 3 properties: id, title, and author with it's corresponding getters and setters. The BookCatelogBean contains an ArrayList<Book> where I populate it with Books (in future I will connect it to a database).
I have two pages: index.xhtml and book.xhtml. I want to display the list of book titles on index.xhtml each formatted as a REST link and their ID to book.xhtml, like so: <h:link outcome="book?id=#{bookCatelogBean.id}" value="#{bookCatelogBean.title}" />
I know how to use BookCatelogBean to display 1 book but I want to display all of them? I have an idea to call a method from BookCatelogBean called getAllBooks() that returns each of the books titles but how would I return each one of them to index.xhtml as a JavaserverFace link instead of a string?
Thanks
Here is my code:
Book.java
package bookshop; import java.io.Serializable; public class Book implements Serializable { private int id; private String title; private String author; public Book(int id, String title, String author){ this.title = title; this.id = id; this.author = author; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } } BookCatelogBean.java
package bookshop; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; @ManagedBean @SessionScoped public class BookCatelogBean implements Serializable { private int currentItem = 0; private ArrayList<Book> books = new ArrayList<Book>(Arrays.asList( new Book(1, "Theory of Money and Credit", "Ludwig von Mises"), new Book(2, "Man, Economy and State", "Murry Rothbard"), new Book(3, "Real Time Relationships", "Stefan Molyneux"))); public String getTitle(){ return books.get(currentItem).getTitle(); } public int getId(){ return books.get(currentItem).getId(); } public String getAuthor(){ return books.get(currentItem).getAuthor(); } } index.xhtml
<?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html"> <h:head> <title>BookShop</title> </h:head> <h:body> <h:link outcome="book?id=#{bookCatelogBean.id}" value="#{bookCatelogBean.title}" /> </h:body> </html>
-945575 0 Well, it appears to work for me. I used this setting:
(setq gnus-parameters '(("regressions.*" (gnus-use-adaptive-scoring nil)) ("general-personal.*" (gnus-use-adaptive-scoring t)))) Perhaps your regexps don't match your group names? The above regexps will match groups that look like mail. and gmane. (the . being a real period).
The way I tested it was to enter each of the two groups and did an eval on the variable M-: gnus-use-adaptive-scoring RET - though you could also just do help on the variable C-h v gnus-use-adaptive-scoring RET.
Perhaps what you want is not to turn adaptive-scoring off, but just to turn scoring off. AFAIK, adaptive-scoring is Gnus trying to figure out scoring for the articles, but not the actual use of scoring.
So maybe this does what you want?
(setq gnus-parameters '(("mail\\..*" (gnus-use-scoring nil)) ("gmane\\..*" (gnus-use-scoring t))))
-22479171 0 conio.h was used in MS-DOS. Are you using MS-DOS? Probably not. Don't include this header.{} or ; to the end of each while loop. This is proper syntax. Otherwise, you will get a parser error.printf will return the number of characters printed. scanf on success, the function returns the number of items of the argument list successfully filled. This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of the end-of-file.&a[0][0]+4 are memory addresses. Each time you run this program, you will get different memory addresses. p=&a[0][0] will start p at the beginning to prepare it to print out the values in the next while loop.You can read more on pointer arithmetic of multi-dimensional arrays here.
-2378585 0If you have the relevant permissions within Management Studio, this shouldn't take too long to work out. It sounds like the bad-user AD group has limited permissions within SQL Server.
You need to check the settings in Security in the GUI, and check the mappings for each of these AD groups - clicking on the databases to see what permissions they have on each database.
-16822170 0 Convert Excel .xls to .csv, .xml or JSON in JavascriptUsing Javascript, specifically Google Apps Script (GAS), I need to convert an .xls file to JSON; but I would settle for .csv or .xml.
Does anyone know any way to do this? Some library, perhaps? Or a private script willing to share? (Note: GAS can not recognize ActiveXObject)
This question does not apply because I am asking for a solution coded in Javascript (or a workaround for Google Apps Script). (The answers to the above question focus on a Java solution and other various .csv to JSON converters.)
Yes, I know there is an open issue for GAS already in the works. But I was wondering if anyone has coded any .js workaround to do the job in the meantime?
-12542408 0There is no such thing as a line in the DOM. But you can scroll to a element. There is a really nice jQuery extension that does it scrollTo.
But to make a bookmark could be a bit messy. Because you need both jQuery and this plugin.
To make it work you would have to book mark with:
javascript: document.location = [website url] ; [jQuery's File content] ; [the plugin] ; [jQuery scrollTo code] Where [jQuery scrollTo code] would be something like:
$(...).scrollTo( $('ul').get(2).childNodes[20], 800 );
-34817983 0 It doesn't violate IEEE-754, because IEEE-754 defers to languages on this point:
A language standard should also define, and require implementations to provide, attributes that allow and disallow value-changing optimizations, separately or collectively, for a block. These optimizations might include, but are not limited to:
...
― Synthesis of a fusedMultiplyAdd operation from a multiplication and an addition.
In standard C, the STDC FP_CONTRACT pragma provides the means to control this value-changing optimization. So GCC is licensed to perform the fusion by default, so long as it allows you to disable the optimization by setting STDC FP_CONTRACT OFF. Not supporting that means not adhering to the C standard.
>>> float(str(0.65000000000000002)) 0.65000000000000002 >>> float(str(0.47000000000000003)) 0.46999999999999997 ??? What is going on here? How do I convert 0.47000000000000003 to string and the resultant value back to float?
I am using Python 2.5.4 on Windows.
-13313304 0 I want to draw a line and fill it with a repeating image in Objective CI don't need code, just a starting point. I have a drawing app on iPad where you draw a line from point a to point b. Between the 2 points the line is replaced with a repeating image.!
-6571186 0How about just causing an exception by hand, i.e. raise(SomeMeaningfulException)? That should get handled automatically by the errormiddleware.
-21740108 0 ExtJS debugging "[E] Layout run failed" (in a custom component)I have developed a custom kind of combo box that uses a grid instead of the standard combo picker (mainly to benefit from buffered rendering with huge data sets). I am now trying to make it compatible with Ext 4.2.1 but I ran into this error:
[E] Layout run failed Please, see the demo pages for test cases. The error is raised once for each combo, but only the first time it is expanded.
This error didn't happen with 4.2.0 (see demo page with 4.2.0). The breaking changes I had identified in 4.2.1 at the time were about the query filter, not rendering or layout... However, I have already been facing this error with 4.2.0 in a situation where the grid picker was sitting in a window, but it was in a code base with lots of overrides and that used the sandboxed version of Ext4... So I just hopped it was not coming from my component and silenced it (another demo page proves that grid picker + window is not enough to trigger the error).
The error doesn't seem to have any side effects, but it makes me feel bad.
Does anyone know what is causing that or, even better, what must be done to prevent it?
Or does someone understand Ext's layout engine well enough to give me some pieces of advice on how to track down this kind of error? Or at least give me reassurance that the error will remain harmless in any situation?
-20661904 0 LINQ create new object and order by propertywith this query I create a new object:
var allData = from op in _opg join tp in _tpg on op.DataGiorno equals tp.DataGiorno join ts in _tsg on op.DataGiorno equals ts.DataGiorno select new {op, tp, ts}; the main source, "_opg" is a List>. Basically as "op" is a DateTime type, I would order this new object by "op" in ascending way. Any hints?
-27504900 0 Android Bluetooth Paring Input DeviceI am trying to make a pairing by code and it works only for normal devices. If I use a bluetooth scanner it pairs with it but the device doesn't work till I go to android settings and select the Input Device checkbox. How can I do this by code?
Thank you.
Here is my pairing code:
public static BluetoothSocket createL2CAPBluetoothSocket(String address, int psm){ return createBluetoothSocket(TYPE_L2CAP, -1, false,false, address, psm); } // method for creating a bluetooth client socket private static BluetoothSocket createBluetoothSocket( int type, int fd, boolean auth, boolean encrypt, String address, int port){ try { Constructor<BluetoothSocket> constructor = BluetoothSocket.class.getDeclaredConstructor( int.class, int.class,boolean.class,boolean.class,String.class, int.class); constructor.setAccessible(true); BluetoothSocket clientSocket = (BluetoothSocket) constructor.newInstance(type,fd,auth,encrypt,address,port); return clientSocket; }catch (Exception e) { return null; } } private void doPair(final BluetoothDevice device, final int deviceTag) { try { Method method = device.getClass().getMethod("createBond", (Class[]) null); method.invoke(device, (Object[]) null); } catch (Exception e) { Log.e(LOG_TAG, "Cannot pair device", e); } BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) { final int state = intent.getIntExtra( BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR); final int prevState = intent.getIntExtra( BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR); if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) { Log.d(LOG_TAG, "Paired with new device"); if (listener != null) { listener.onBluetoothPairedDeviceChange(bluetoothAdapter .getBondedDevices().iterator().next() .getName(), deviceTag); } context.unregisterReceiver(this); } else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDING) { Log.d(LOG_TAG, "Cannot pair with new device"); if (listener != null) { listener.onBluetoothStatusChange(BluetoothHelper.IDLE_STATUS); } context.unregisterReceiver(this); } } } }; IntentFilter intent = new IntentFilter( BluetoothDevice.ACTION_BOND_STATE_CHANGED); context.registerReceiver(mReceiver, intent); }
-17684938 0 Something like this should give u all the filenames in the folder, for you to manipulate:
Dir["Tel/**/**/*.csv].each do |file| * update attribute of your model with the path of the file end
-33074533 0 The statndard way to interact with ajax in Wordpress through WP AJAX.You can do like this. $.ajax( { type: 'POST', url: "/wp-admin/admin-ajax.php?action=your_action_name", dataType: 'json', cache: false, data:{ your data should be here }, success: function(response) { alert('success'); }, error: function(xhr, textStatus, errorThrown) { alert('error'); } }); then in functions.php or plugin file you need to register a hook for ajax request.wp_ajax should be prefix your action hook name and then method for processing the request. add_action('wp_ajax','method_name'); function method_name(){ here is your code }
-29049704 0 Constructing a JavaScript Array prototype method I am new to constructing a JavaScript Array prototype. Please only paste previous links that are directly appropriate as I have been sourcing on SO and on w3school. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype
I would like to create a method for an array that checks if the 'id' field within the object does not already exist in the array. If not, then 'push' object into the array, else do nothing.
Each object has a unique 'id' field.
eg var array = [{ id: 001, title: 'some title'}, { id: 002, title: 'other title'}] var object = {id: 001, title: 'some title'} // if object.id does not exist in array... array.push(object) //else do nothing I would like the function to take the 'id' field as an argument so this function has wider use.
Are there any drawbacks to extending the array.Prototype? Otherwise I can do a for loop instead to do the check without the prototype constructor.
-13271633 0This DELETE all the records from the table abc with JOIN to another table. It deletes all the records in the table abc that has a RECORD_TYPE value equal to the RECORD_TYPE in the other table AND in the same time the value IN are equals in the two table.
It is a normal DELETE clause, Where the FROM can contain extra joined table as specified by the documentation:
-29819166 0FROM clause:
This extension, specifying a join, can be used instead of a subquery in the WHERE clause to identify rows to be removed.
set fix width in File Uploader as: style="width:300px". This will not distort the design and will restrict the filename within the given width limit
-38458655 0 How to make paths clickable in Visual Studio Code TerminalI have VSCode vs. 1.3. and I would like to be able to click in any valid path showed inside the integrated Terminal and get the file opened.
Do you know how can I achieve it?
Thanks!
-3434906 0TWebBrowser is a wrapper around IE ActiveX interface. So, in the end,
TWebBrowser = Internet Explorer
-8226513 0 The solution to your problem greatly depends on your code. You should definitively include the relevant code bits in your SO questions if you want to get help.
I'm going to make a guess and assume that your code looks similar to the MapView example:
http://developer.anscamobile.com/reference/index/nativenewmapview
If that's the case, the problem is that the location is retrieved very late.
local function callMap() -- Fetch the user's current location -- Note: in XCode Simulator, the current location defaults to Apple headquarters in Cupertino, CA local currentLocation = myMap:getUserLocation() local currentLatitude = currentLocation.latitude local currentLongitude = currentLocation.longitude ... What you want is that code executed earlier. Ideally, when the application starts. The user will get the "this application wants access to the GPS" message right away, so they will have more time to "approve" before seeing the mapview.
Another thing you can do is using a cache. Store the latest known location somewhere (a config file or the database, depending on your setup). When the connection is lost, or not yet retrieved, show the last known location on the map.
-33541798 0for k,v in pairs(t2) do t1[k] = v end key for string solution
-25518020 0Here is an additional option:
The way I solved this problem for my app was to define the colors in values/color.xml.
<resources> <color name="blue">#ff0099cc</color> <color name="dark_grey">#ff1d1d1d</color> <color name="white">#ffffffff</color> ... <color name="textview_background">@color/white</color> </resources> In the layout the TextView has:
android:background="@color/textview_background" If I want to get the background color in code I can just use:
getResources().getColor(R.color.textview_background) This gives me a Color object directly without worrying about getting the color from a Drawable.
See the equal height function. http://www.catswhocode.com/blog/8-awesome-jquery-tips-and-tricks Hope this help.
function equalHeight(group) { tallest = 0; group.each(function() { thisHeight = $(this).height(); if(thisHeight > tallest) { tallest = thisHeight; } }); group.height(tallest); } $(document).ready(function() { equalHeight($(".recent-article")); equalHeight($(".footer-col")); });
-25652504 0 In the basic example you need to include the ZeroClipboard.js script. I added:
<script src="ZeroClipboard.js"></script> to the html head section. Then - which was not so clear for me either - the main.js script needs to be added after the button. I didn't reference the file (which isn't in the package as far as I could tell), but included the script directly - this way:
<button id="copy-button" data-clipboard-text="Copy Me!" title="Click to copy me.">Copy to Clipboard</button> <script type="text/javascript"> var client = new ZeroClipboard( document.getElementById("copy-button") ); client.on( "ready", function( readyEvent ) { // alert( "ZeroClipboard SWF is ready!" ); client.on( "aftercopy", function( event ) { // `this` === `client` // `event.target` === the element that was clicked event.target.style.display = "none"; alert("Copied text to clipboard: " + event.data["text/plain"] ); } ); } ); </script> Hope this helps somebody (more than one year on I gues you have either solved it or moved on!!)
-27220201 0 Detecting or Preventing Calls to a Method from a Specific MethodI am writing a JUnit test for code submitted to a competition. The rules of the competition require that certain methods not be called from other methods. (I unfortunately can not change the rules.)
The contestants are all implementing an interface we supplied which includes an add(K key, V value) method and a delete(K key) method. We need to test that entries do not implement delete by adding every other element to a new object and return that object.
We are also trying to avoid adding dependencies outside of the Java core since we are using a lot of automated tools (like the Marmoset Project) to test the hundreds of submissions.
I read through the documentation for Java Reflection and Instrumentation and nothing jumped out at me.
We are using Java 8 if it makes a difference.
-32615341 0 Why is R prompting me and failing on `update.packages()`?I'm new to R and I've compiled it myself on Ubuntu 14.04.3 (x64). Note, I am up to date with the R source:
blong@work:~/Documents/Work/REPOS__svn/R/R-3-2-branch$ svn info |head -n 7 Path: . Working Copy Root Path: /home/blong/Documents/Work/REPOS__svn/R/R-3-2-branch URL: https://svn.r-project.org/R/branches/R-3-2-branch Relative URL: ^/branches/R-3-2-branch Repository Root: https://svn.r-project.org/R Repository UUID: 00db46b3-68df-0310-9c12-caf00c1e9a41 Revision: 69384 blong@work:~/Documents/Work/REPOS__svn/R/R-3-2-branch$ svn status -u Status against revision: 69392 Running configure and make in R's 3.2.2 branch have completed successfully and I'm able to use a variety of packages within an R session. However, I'd like to check that all of my libraries are up to date. In R 3.2.2 , I'm invoking update.packages(). When the function is invoked, I'm prompted to select a CRAN mirror :
Assuming everything is fine and this is a non-issue, I select the main ("O-Cloud [https]") mirror from the dialog. The dialog closes and I'm returned to my R prompt with a duplicate message saying "unsupported URL scheme".
Simultaneously, I receive an error in my R session upon invoking update.packages():
> getOption("repos") CRAN "@CRAN@" > update.packages() --- Please select a CRAN mirror for use in this session --- Error in download.file(url, destfile = f, quiet = TRUE) : unsupported URL scheme Warning: unable to access index for repository https://cran.rstudio.com/src/contrib: unsupported URL scheme > Considering that perhaps this is an issue with HTTPS, I try a non-SSL mirror and similarly nothing happens (perhaps there are no updates, but I'd like a message that tells me this). However, this time I don't receive the second "unsupported URL scheme" message after the dialog closes :
> update.packages() --- Please select a CRAN mirror for use in this session --- Error in download.file(url, destfile = f, quiet = TRUE) : unsupported URL scheme > It seems that under the hood, R uses a library called RCurl to do some of it's HTTP/S interaction. As far as I can tell, I'm using a supported version of curl / libcurl :
blong@work:~$ curl --version curl 7.35.0 (x86_64-pc-linux-gnu) libcurl/7.35.0 OpenSSL/1.0.1f zlib/1.2.8 libidn/1.28 librtmp/2.3 Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtmp rtsp smtp smtps telnet tftp Features: AsynchDNS GSS-Negotiate IDN IPv6 Largefile NTLM NTLM_WB SSL libz TLS-SRP Any thoughts on this? It seems similar to this mailing list discussion, but I'm not sure if this is an issue or I'm doing something wrong.
-19587903 0In a Terminal window type man ld and you'll get a description of the ld command and the arguments it takes. There you'll find -F specifies a directory to search for frameworks in. The Xcode generated command line contains:
-F/Users/thomaswickl/Development/Git\ Projects/quickquick2/QuickQuick2 -F\"/Users/thomaswickl/Development/Git\ Projects/quickquick2/QuickQuick2/..\" -F/Users/thomaswickl/Development/Git\ Projects/quickquick2 The second entry is actually redundant - it is the same as the third (as .. means parent) - but it looks like your problem is the way the path is escaped. To allow a space in a path you can either enclose it in quotes or precede the space with a backslash. Paths 1 & 3 use the backslash method, path 2 uses both and so the backslash is presumably treated as a literal character (that is what would happen in Terminal) and therefore the path is incorrect... (cross-eyed yet? ;-))
Maybe this double-escaping was introduced when the project was converted to Xcode 5. The paths are listed in your project's settings (sorry Xcode not to hand), hunt it out and remove it (as its a duplicate).
HTH.
-6967136 1 Is there any good alternative for python's webkit module that works on windows?Is there any official good alternative for webkit that works on windows?
-1329817 0.NET certainly allows you to use Visual Basic to write a Windows Service. I believe there is even a default project template to do so. Here is an tutorial as such: http://www.vbdotnetheaven.com/UploadFile/mahesh/Winservvb11172005233242PM/Winservvb.aspx
All .NET code is converted to an intermediary language that is executed, thus all .NET languages can be used to write a windows service.
-12800513 0You could do the fallowing...
var GroupSelectView = Backbone.View.extend({ el: $("select"), initialize: function() { var that = this; this.collection = new UserGroups(); this.collection.on( 'change', this.render, this ); // You could try this too, 1 is for 1 item is added, the other, when all items are changed // this.postCollection.on('add', this.addOne, this); // this.postCollection.on('reset', this.addAll, this); this.render(); }, render: function(){ _.each(this.collection.models, function(group){ $("<option/>", { value: group.get("Id"), text: group.get("Name")} ).appendTo(this.el) }, this); }, });
-21317940 0 Performing calculations on Django database values: views.py, template or Javascript? I have a Django project that interfaces with a PostgreSQL database; one of my tables is about 450 rows long and each row contains about a dozen columns.
Each column's value must be put into a different formula to produce the final data I want to display in the template layer, but each row will be processed with the same set of calculations. (In other words, I want to perform 12 different calculations 450 times each.)
My question is, of the following methods, which is the generally accepted method of doing so, and which is the best in terms of performance:
A) Write each calculation as a model method in models.py, query all objects of interest (again, about 450 of them) in views.py and pass them directly to the template, and then use Django's template language to write things like:
<table> {% for item in list %} <tr> <td>{{item.name}}</td> ... </tr> {% endfor %} </table> (where .name is a model method)
B) Peform the query and calculations in the views.py file and pass the results organized into one big dictionary or list or JSON to the template (and then parse it using template tags),
C) Pass all of the objects of interest to the template as in A), but perform calculations on each object's fields using Javascript or jQuery,
D) Combine B) and C) to perform all database queries in views.py and then pass the raw values as a big dictionary/list/JSON object to the template and perform calculations on those values using Javascript/jQuery.
To my mind, method A) seems the least efficient as it requires you to hit the database a ton of times in the template layer. But it makes writing the view and template extremely simple (just requires you to write 12 different model methods). Method B) seems to follow the general tenet of performing as much logic as possible in your view, and simply passing along the final results to be displayed in the template. But it makes the view function long and ugly. Methods C) and D) put most of load on the end user's browser, which seems like it could really take a load off the server, but then obviously won't work if the user has JS turned off.
But again, I'd like to know if there's an accepted best practice for this kind of situation, and whether that contradicts the fastest method from a computational standpoint.
And obviously, if I've missed the best method of all, please let me know what it would be.
-26837839 0 Finding the mean of more than one vectorI am tring to get the mean of three vectors but the mean function is not working.
Example:
A = [1 2 3 4 5]; B = [2 3 4 5 6]; C = [3 4 5 6 7]; V = mean(A,B,C); % should be [2 3 4 5 6] as each column is the some of the same column in A, B and C divided by three. Any Help?
-5733800 0if the dialog gets wider, but stays the same height, the number of rows should lessen, while the number of columns increases.
Wrap Layout might be what you are looking for.
-23019966 0give it a try
window.location.href.split("?")[0]
-13781982 0 Why not just make evey different view a different site, ie give the ads in each view a different id. It is a little bit of a pain to set this up if you have several applications/or lots of views, but I think that it should work.
-4840534 0You can get straight into programming with ruby.
In terms of generic things to know I suggest you read a book, so you get one consistent message explaining all the basics.
This is a great book to teach you programming in general and it teaches you using ruby. http://pragprog.com/titles/ltp2/learn-to-program
Also have a go with http://tryruby.org - Quick ruby tutorial in your browser
Finally check out the hackety-hack project it's designed to help people learn to program, although version 1 is only just out. http://hackety-hack.com/
-33824549 0This is what you want:
echo "$line" | sed -E 's/(QA.|DEV.)(.*)/<!-- \1\2 -->/' The first group could be prefixed by QA or DEV , use the | or operator.
A few alternatives:
$ echo "QA2 ABCDEFGHI"|sed -E 's/(.*)/<!-- \1 -->/' <!-- QA2 ABCDEFGHI --> $ echo "QA2 ABCDEFGHI"|awk '{print "<!-- "$0"-->"}' <!-- QA2 ABCDEFGHI-->
-17006528 0 You can configure IntelliJ to use a lot of different application containers, but each of them must be downloaded and installed separately. I currently have mine configured to serve via jetty, like eclipse, and also tomcat, tc-server, jboss, and node.js. It's pretty easy to set up.
-35531950 0Refer the sample here.
Code:
HTML:
<div ng-app="app" ng-controller="test as vm"> <div test-dir="user" ng-repeat="user in vm.users"> </div> </div> JS:
var app = angular.module('app', []); app.controller('test', function ($scope) { var vm = this; vm.users = [ { 'Name': 'Abc', 'Id': 1 }, { 'Name': 'Pqr', 'Id': 2 }, { 'Name': 'XYZ', 'Id': 3 } ]; $scope = vm; }); app.directive('testDir', function () { return { scope: { user: '=testDir' }, template: "<div><h4>{{user.Id}}) {{user.Name}}</h4></div>" } });
-32116366 0 The full method is pasted below. When calling JTable::getInstance you must pass $type as an argument. The getInstance method then uses $type to define $tableClass as you can see below.
// Sanitize and prepare the table class name. $type = preg_replace('/[^A-Z0-9_\.-]/i', '', $type); $tableClass = $prefix . ucfirst($type); The method then proceeds to load (import) the class if it's not already and then finally calls return new $tableClass($db);
So $tableClass is just a dynamic variable based on the $type argument.
In your example above:
$row = JTable::getInstance('K2Item', 'Table'); The $type and $prefix arguments are translated into the following:
return new TableK2Item($db);
So if you search for TableK2Item you should indeed find that class which has a hit() method.
So $tableClass is actually defined in the getInstance method.
Does this make sense?
/** * Static method to get an instance of a JTable class if it can be found in * the table include paths. To add include paths for searching for JTable * classes see JTable::addIncludePath(). * * @param string $type The type (name) of the JTable class to get an instance of. * @param string $prefix An optional prefix for the table class name. * @param array $config An optional array of configuration values for the JTable object. * * @return mixed A JTable object if found or boolean false if one could not be found. * * @link https://docs.joomla.org/JTable/getInstance * @since 11.1 */ public static function getInstance($type, $prefix = 'JTable', $config = array()) { // Sanitize and prepare the table class name. $type = preg_replace('/[^A-Z0-9_\.-]/i', '', $type); $tableClass = $prefix . ucfirst($type); // Only try to load the class if it doesn't already exist. if (!class_exists($tableClass)) { // Search for the class file in the JTable include paths. jimport('joomla.filesystem.path'); $paths = self::addIncludePath(); $pathIndex = 0; while (!class_exists($tableClass) && $pathIndex < count($paths)) { if ($tryThis = JPath::find($paths[$pathIndex++], strtolower($type) . '.php')) { // Import the class file. include_once $tryThis; } } if (!class_exists($tableClass)) { // If we were unable to find the class file in the JTable include paths, raise a warning and return false. JLog::add(JText::sprintf('JLIB_DATABASE_ERROR_NOT_SUPPORTED_FILE_NOT_FOUND', $type), JLog::WARNING, 'jerror'); return false; } } // If a database object was passed in the configuration array use it, otherwise get the global one from JFactory. $db = isset($config['dbo']) ? $config['dbo'] : JFactory::getDbo(); // Instantiate a new table class and return it. return new $tableClass($db); }
-5661392 0 You can't actually modify/save the image in javascript/jquery (as far as i know). You'll have to use server-side image manipulation libraries like gdlib (http://www.boutell.com/gd/) which is usually activated by default in php, or imagemagick (http://www.imagemagick.org/script/index.php)
-28815064 0My favorite method is to add a text-align: center; to the parent element, then use display: inline-block; instead of float: left;
.thumbsPanel { border: thin black dashed; width: 800px; height: 500px; margin: 0 auto; text-align: center; } .thumbs { display: inline-block; width: 100px; height: 100px; border: 0; margin: 0 1em 1em 0; } <div class="thumbsPanel"> <div class="thumbs"><a href="1.html"><img src="1.jpg"></a></div> <div class="thumbs"><a href="2.html"><img src="2.jpg"></a></div> <div class="thumbs"><a href="3.html"><img src="3.jpg"></a></div> </div> If you want to save modified source as html you can use different aproaches, depends on what you want to mainupulate. Sadly with javascript saveing file is tricky and depends on many things, so you could use option to copy paste file source manually or write your browser and settings specific file saver. I would prefer javascript+php combo solution. Or if there is no need to manipulate someting with javascript i would do it entirely in php.
Step 1 - open browser with console, in chrome and firefox CTRL+SHIFT+J And allow popups. Step 2 - open webpage you want Step 3 - Copy next code to console
//Script loading function function load_script( source ) { var new_script = document.createElement('script'); new_script.type = 'text/javascript'; new_script.src = source; new_script.className = 'MyInjectedScript'; document.getElementsByTagName('head')[0].appendChild(new_script); } function escapeHtml(unsafe) { return unsafe .replace(/&/g, "&") .replace(/</g, "<") .replace(/>/g, ">") .replace(/"/g, """) .replace(/'/g, "'"); } //Load jQuery, if page do not have it by default if (typeof(jQuery) != 'function') load_script('http://code.jquery.com/jquery-latest.js'); Step 4 - Do your manipulations in console
Step 5 - Copy next code to console
//In the end remove your injected scripts $('.MyInjectedScript').remove(); //Or jquery script will be in source //get Document source var doc_source = $('html',document).html(); doc_source = '<html>'+doc_source+'</html>'; var new_window = window.open('', '', 'scrollbars=yes,resizable=yes,location=yes,status=yes'); $(new_window.document.body).html('<textarea id="MySource">'+escapeHtml(doc_source)+'</textarea>'); STEP 6 - copy paste code from opened window textarea
If you want to do it with PHP you can easily download page with curl and manipulate content and save file as desired.
-9445375 0You can do this using an attribute on your wcf service:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] class MySingleton : ... {...} With this your WCF service has a single instance, that is used by all callers.
For details see: http://msdn.microsoft.com/en-us/magazine/cc163590.aspx
-26862782 0 How to use Otto event bus with Android AnnotationsI am working on an app where I want to use Android Annotations and Otto Bus Event from Square
For the integration of these two libraries together I have followed this link here. Also I have used the Otto 2.0-wip lib that is suggested there and not that from Otto Git.
This is how I do the implementation:
I created a singleton class for the bus:
@EBean(scope = EBean.Scope.Singleton) public class BusProviderAA extends BasicBus{ } I declare an object for this class inside my Fragment Class where I want to subscribe at events :
@Bean BusProviderAA ottoBus; @AfterInject protected void initAfterInjectMFragment() .... // my stuff here ottoBus.register(this); } @Override public void onStop() { super.onStop(); ottoBus.unregister(this); } @Subscribe public void onChangeUserDetailsEvent(ChangeUserDetailsEvent mEvent){ Log.e(" s onChangeUserDetailsEvent", "ss onChangeUserDetailsEvent"); if(mEvent.msg.contains("Data_changed")){ //TODO } } I post event to the bus from my communicator class when it gets callback from server communication. This is how I post event to my bus inside this class:
@Bean //To use this enhanced class in another enhanced class or in an enhanced Android component, use @Bean: BusProviderAA ottoBus; public void callbackResponse(....){ ....// my stuff here and after callback ottoBus.post(changeUserDetailsEvent(serverResponse.getMsg())); } @Produce public ChangeUserDetailsEvent changeUserDetailsEvent(String msg){ return new ChangeUserDetailsEvent(msg); } And this is my ChangeUserDetailsEvent class:
public class ChangeUserDetailsEvent { public final String msg; public ChangeUserDetailsEvent(String msg) { this.msg = msg; } } Problem: My problem is that my method which is subscribed at bus event onChangeUserDetailsEvent doesnt get called and I dont even know how to debug to fix this problem.
I should mention that bus event works perfectly when I implement it in a Fragment that doesn't use Annotations, and a Bus singleton without Annotation. This is the Bus singleton class when I don't use Annotations:
public class BusProvider { private static final Bus BUS = new BasicBus(); // me lib public static Bus getInstance(){ return BUS; } private BusProvider(){} } Thanks!
EDIT
I also have a problem when I update to androidannotations:3.2 changing my gradle file from:
compile 'org.androidannotations:androidannotations:3.1' apt 'org.androidannotations:androidannotations:3.1'
to:
compile 'org.androidannotations:androidannotations:3.2' apt 'org.androidannotations:androidannotations:3.2'.
For version 3.1 it compiles but doesnt work otto event bus. With version 3.2 it gives error.This means that AA library has made some changes that I need to implement or it has bugs. How can I find the solution ?
This is one of the errors(for demonstration): Error:(27, 25) error: cannot find symbol class UserAccountActivity_ which is a class that is activity.
This is my androidannotations.log:
17:26:05.187 [Daemon Thread 13] INFO o.a.AndroidAnnotationProcessor:84 - Initialize AndroidAnnotations 3.2 with options {androidManifestFile=C:\Users\Armando\Android Studio\Hu\app\build\intermediates\manifests\full\debug\AndroidManifest.xml, resourcePackageName=XXPack} 17:26:05.244 [Daemon Thread 13] INFO o.a.AndroidAnnotationProcessor:108 - Start processing for 15 annotations on 100 elements 17:26:05.273 [Daemon Thread 13] DEBUG o.a.h.AndroidManifestFinder:98 - AndroidManifest.xml file found with specified path: C:\Users\Armando\Android Studio\Hu\app\build\intermediates\manifests\full\debug\AndroidManifest.xml 17:26:05.279 [Daemon Thread 13] INFO o.a.AndroidAnnotationProcessor:171 - AndroidManifest.xml found: AndroidManifest [applicationPackage=XXPack, componentQualifiedNames=[XXPack.SplashScreen, XXPack.HomeActivity, XXPack.ActivityProve, XXPack.UserAccountActivity_, XXPack.CartActivity_, com.facebook.LoginActivity], permissionQualifiedNames=[android.permission.INTERNET, android.permission.READ_EXTERNAL_STORAGE, android.permission.write_external_storage], applicationClassName=null, libraryProject=false, debugabble=false, minSdkVersion=14, maxSdkVersion=-1, targetSdkVersion=21] 17:26:05.280 [Daemon Thread 13] INFO o.a.r.ProjectRClassFinder:50 - Found project R class: XXPack.R 17:26:05.286 [Daemon Thread 13] INFO o.a.r.AndroidRClassFinder:44 - Found Android class: android.R 17:26:05.304 [Daemon Thread 13] INFO o.a.p.ModelValidator:42 - Validating elements 17:26:05.304 [Daemon Thread 13] DEBUG o.a.p.ModelValidator:62 - Validating with EActivityHandler: [XXPack.CartActivity, XXPack.UserAccountActivity] 17:26:05.306 [Daemon Thread 13] DEBUG o.a.p.ModelValidator:62 - Validating with EFragmentHandler: [XXPack.fragments.AddAddressFragment, XXPack.fragments.AddressBookFragment, XXPack.fragments.ChangePasswordFragment, XXPack.fragments.MyOrdersFragment, XXPack.fragments.MyVouchersFragment, XXPack.fragments.NewsLetterFragment, XXPack.fragments.PaymentMethodFragment, XXPack.fragments.PersonalDataFragment, XXPack.fragments.UserAccountFragment] 17:26:05.308 [Daemon Thread 13] DEBUG o.a.p.ModelValidator:62 - Validating with EBeanHandler: [XXPack.bus.BusProviderAA, XXPack.communicator.UserAccountCommunicator] 17:26:05.308 [Daemon Thread 13] DEBUG o.a.p.ModelValidator:62 - Validating with EViewGroupHandler: [XXPack.layouts.AddressBookItem, XXPack.layouts.CartItem, XXPack.layouts.OrdersItem, XXPack.layouts.UserAccountListFooter, XXPack.layouts.UserAccountListHeader] 17:26:05.319 [Daemon Thread 13] DEBUG o.a.p.ModelValidator:62 - Validating with ItemClickHandler: [lv_user_account(int)] 17:26:05.321 [Daemon Thread 13] DEBUG o.a.p.ModelValidator:62 - Validating with OptionsMenuHandler: [XXPack.fragments.UserAccountFragment] 17:26:05.323 [Daemon Thread 13] DEBUG o.a.p.ModelValidator:62 - Validating with BeanHandler: [ottoBus, ottoBus, communicator] 17:26:05.324 [Daemon Thread 13] DEBUG o.a.p.ModelValidator:62 - Validating with ProduceHandler: [produceNonceEvent(XXPack.models.Nonce), produceErrorEvent(XXPack.models.ErrorCommunication), produceFeatureCategoryEvent(java.util.ArrayList<XXPack.models.SimpleCategory>), produceErrorEvent(XXPack.models.ErrorCommunication), produceProductEvent(java.util.ArrayList<XXPack.models.Product>), produceErrorEvent(XXPack.models.ErrorCommunication), changeUserDetailsEvent(java.lang.String), produceErrorEvent(XXPack.models.ErrorCommunication), produceUserEvent(XXPack.models.User), produceErrorEvent(XXPack.models.ErrorCommunication)] 17:26:05.325 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element ProduceHandler unvalidated by 17:26:05.325 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element ProduceHandler unvalidated by 17:26:05.325 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element ProduceHandler unvalidated by 17:26:05.325 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element ProduceHandler unvalidated by 17:26:05.326 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element ProduceHandler unvalidated by 17:26:05.326 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element ProduceHandler unvalidated by 17:26:05.326 [Daemon Thread 13] ERROR o.a.h.AnnotationHelper:126 - @com.squareup.otto.Produce can only be used on a method with zero parameter, instead of 1 17:26:05.327 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element ProduceHandler unvalidated by 17:26:05.327 [Daemon Thread 13] ERROR o.a.h.AnnotationHelper:126 - @com.squareup.otto.Produce can only be used on a method with zero parameter, instead of 1 17:26:05.327 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element ProduceHandler unvalidated by 17:26:05.327 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element ProduceHandler unvalidated by 17:26:05.328 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element ProduceHandler unvalidated by 17:26:05.328 [Daemon Thread 13] DEBUG o.a.p.ModelValidator:62 - Validating with SubscribeHandler: [onNonceEvent(XXPack.event.NonceEvent), onErrorEvent(XXPack.event.ErrorEvent), onFeaturesAndCategory(XXPack.event.FeatureCategoryEvent), onNonceEvent(XXPack.event.NonceEvent), onErrorEvent(XXPack.event.ErrorEvent), onUserEvent(XXPack.event.UserEvent), onChangeUserDetailsEvent(XXPack.event.ChangeUserDetailsEvent)] 17:26:05.328 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element SubscribeHandler unvalidated by 17:26:05.328 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element SubscribeHandler unvalidated by 17:26:05.328 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element SubscribeHandler unvalidated by 17:26:05.328 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element SubscribeHandler unvalidated by 17:26:05.328 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element SubscribeHandler unvalidated by 17:26:05.328 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element SubscribeHandler unvalidated by 17:26:05.328 [Daemon Thread 13] DEBUG o.a.p.ModelValidator:62 - Validating with AfterInjectHandler: [initAfterInjectCart(), initAfterInjectAddAddress(), initAfterInjectAddressBook(), initAfterInjectChangePass(), initAfterInjectAddressBook(), initAfterInjectPersonalData()] 17:26:05.328 [Daemon Thread 13] DEBUG o.a.p.ModelValidator:62 - Validating with AfterViewsHandler: [initAfterViewsCart(), initUserAccountAct(), initAddAddressFragment(), initAddressFragment(), initChangePassFragment(), initMyOrdersFragment(), initMyVoucherFragment(), initNewsLetterFragment(), initPaymentFragment(), initViewsAfterViews(), initUserAccountFragment()] 17:26:05.333 [Daemon Thread 13] INFO o.a.p.ModelProcessor:69 - Processing root elements 17:26:05.338 [Daemon Thread 13] DEBUG o.a.p.ModelProcessor:160 - Processing root elements EActivityHandler: [XXPack.UserAccountActivity, XXPack.CartActivity] 17:26:05.353 [Daemon Thread 13] DEBUG o.a.p.ModelProcessor:160 - Processing root elements EFragmentHandler: [XXPack.fragments.AddressBookFragment, XXPack.fragments.AddAddressFragment, XXPack.fragments.NewsLetterFragment, XXPack.fragments.MyOrdersFragment, XXPack.fragments.UserAccountFragment, XXPack.fragments.PaymentMethodFragment, XXPack.fragments.PersonalDataFragment, XXPack.fragments.ChangePasswordFragment, XXPack.fragments.MyVouchersFragment] 17:26:05.358 [Daemon Thread 13] DEBUG o.a.p.ModelProcessor:160 - Processing root elements EBeanHandler: [XXPack.bus.BusProviderAA, XXPack.communicator.UserAccountCommunicator] 17:26:05.358 [Daemon Thread 13] DEBUG o.a.p.ModelProcessor:160 - Processing root elements EViewGroupHandler: [XXPack.layouts.CartItem, XXPack.layouts.UserAccountListFooter, XXPack.layouts.OrdersItem, XXPack.layouts.AddressBookItem, XXPack.layouts.UserAccountListHeader] 17:26:05.363 [Daemon Thread 13] INFO o.a.p.ModelProcessor:77 - Processing enclosed elements 17:26:05.368 [Daemon Thread 13] INFO o.a.AndroidAnnotationProcessor:250 - Number of files generated by AndroidAnnotations: 18 17:26:05.368 [Daemon Thread 13] INFO o.a.g.ApiCodeGenerator:52 - Writting following API classes in project: [] 17:26:05.373 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.bus.BusProviderAA_ 17:26:05.388 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.layouts.AddressBookItem_ 17:26:05.456 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.layouts.CartItem_ 17:26:05.468 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.layouts.OrdersItem_ 17:26:05.480 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.layouts.UserAccountListFooter_ 17:26:05.491 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.layouts.UserAccountListHeader_ 17:26:05.500 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.CartActivity_ 17:26:05.514 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.UserAccountActivity_ 17:26:05.529 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.fragments.AddAddressFragment_ 17:26:05.546 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.fragments.AddressBookFragment_ 17:26:05.559 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.fragments.ChangePasswordFragment_ 17:26:05.587 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.fragments.MyOrdersFragment_ 17:26:05.600 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.fragments.MyVouchersFragment_ 17:26:05.613 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.fragments.NewsLetterFragment_ 17:26:05.624 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.fragments.PaymentMethodFragment_ 17:26:05.634 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.fragments.PersonalDataFragment_ 17:26:05.649 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.fragments.UserAccountFragment_ 17:26:05.664 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.communicator.UserAccountCommunicator_ 17:26:05.670 [Daemon Thread 13] INFO o.a.p.TimeStats:81 - Time measurements: [Whole Processing = 426 ms], [Generate Sources = 302 ms], [Process Annotations = 40 ms], [Extract Annotations = 27 ms], [Validate Annotations = 25 ms], [Find R Classes = 18 ms], [Extract Manifest = 6 ms], 17:26:05.671 [Daemon Thread 13] INFO o.a.AndroidAnnotationProcessor:122 - Finish processing
-35938700 0 Pointers do not keep information whether they point to single objects or for example first elements of arrays.
Consider the following code snippet
char *p; char c = 'A'; p = &c; putchar( *p ); char s[] = "ABC"; p = s; putchar( *p ); Thus you have to provide yourself the information about whether a pointer points to an element of an array.
You can do this in two ways. The first one is to specify the number of elements in the sequence the first element of which is pointed to by the pointer. Or the sequence must to have a sentinel value as strings have.
For example
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; for ( int *p = a; p < a + sizeof( a ) / sizeof( *a ); ++p ) ^^^^^^^^^^^^^^^^^^^^^^^^^^ { printf( "%d ", *p ); } printf( "\n" ); Or
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; int *p = a; do { printf( "%d ", *p ); } while ( *p++ != 0 ); ^^^^^^^^^ printf( "\n" ); These code snippets can be written as functions
void f( int a[], size_t n ) { for ( int *p = a; p < a + n; ++p ) { printf( "%d ", *p ); } printf( "\n" ); } Or
void f( int a[] ) { int *p = a; do { printf( "%d ", *p ); } while ( *p++ != 0 ); printf( "\n" ); } The same way an array of strings can be printed. Either you will report explicitly the number of elements in the array yourself. Or you can use a sentinel value as for example a null pointer or an empty string.
For example
#include <stdio.h> void PrintStringArray( char *s[], size_t n ) { for ( char **p = s; p < s + n; ++p ) { puts( *p ); } printf( "\n" ); } int main( void ) ^^^^^^^^^^^^^^^^ { char *list[] = { "Green", "Yellow", "Black", "White", "Purple", "Saphire" }; PrintStringArray( list, sizeof( list ) / sizeof( *list ) ); return 0; } Or
#include <stdio.h> void PrintStringArray( char *s[] ) { char **p = s; while ( *p != NULL ) { puts( *p++ ); } printf( "\n" ); } int main( void ) ^^^^^^^^^^^^^^^^ { char *list[] = { "Green", "Yellow", "Black", "White", "Purple", "Saphire", NULL ^^^^ }; PrintStringArray( list ); return 0; }
-13959172 0 Issue with JSON sending Hey guys so I am trying to have a JSON send over a value to another page in wordpress to create a session once a image is clicked on.
Here is the JSON code:
$('.item-post a').click(function() { var prodname = $('#hiddenpostitle'); $.post('/overviewcheck-515adfzx8522', { 'ProdName': prodname.val() }, function(response) { }, 'json' ); }); The #hiddenposttitle is the following: <?php echo "<input type='hidden' value='$title' id='hiddenpostitle' name='hiddenpostitle'/> "?>
So this sends to the overviewcheck page, which then has a template that has the follow:
<?php /* Template Name: overviewbackcheck */ session_start(); $prodname= $_POST['ProdName']; $_SESSION['overviewprod'] = $prodname; ?> Someone mentioned something about wordpress destroying sessions from calling session_start() but that's not the issue because I fixed that awhile ago, and have other sessions being made that work. It has to do something with the JSOn sending over and I am not to sure.
From here the overview page is opened with the following:
$(function() { $('.item-post a').colorbox({opacity:0.3, href:"../overviewa512454dzdtfa"}); }); This is the colorbox code that will open the file the within the file I have:
<?php echo $_SESSION['overviewprod']; ?> to echo it out.
Ultimately I am unable to echo out a session and it does not seem anything is being made.
If you could help me out that would be awesome because I need this finished! :)
-23753604 0 Add "Rubber Band" effect in android while changing background of applicationI am working on the application in which:
User will have a control to change the background and text (multiples) by doing horizontal swipe for BG and vertical swipe for text. In this case, if I am changing BG, text should remain constant and if I am changing text then BG should remain constant.
Also, I want to add Rubber Band effect like in iOS when user changes Text and BG.
I am thinking of twoway-view library to support for vertical and horizontal scrolling. But how to use this library in my case?
Any idea/solution will be appreciated.
-15131397 0function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); }
use this function to check each input
-18995593 0Look at this post How to write UTF-8 characters using bulk insert in SQL Server?
Quote: You can't. You should first use a N type data field, convert your file to UTF-16 and then import it. The database does not support UTF-8.
Original answers
look at the encoding of youre text file. Should be utf8. If not this could cause problems.
Open with notepad, file-> save as and choose encoding
After this try to import as a bulk
secondly, make sure the column datatype is nvarchar and not varchar. Also see here
-34470311 0 Search in JSON api url with ajaxI have an api URL it's output JSON, it is about daily deals like groupon.
I want to create a search form and client search in this json
Samle json url here
I'm decode JSON like that and show it but how to search in this api url i don't know.
$param = array( 'apiKey' => 'VN43ZG2LLHKHHIU6', 'publisherId' => 316, //'isPopular' => 'on', 'p' => $sayfasi, 'itemInPage' => $sayi ); if(isset($tagid) && $tagid !='') $param['tagIds[]'] = $tagid; if(isset($cityId) && $cityId !='') $param['cityId'] = $cityId; $jsonurl = 'http://api.myaffwebsiteurl.com/deal/browse.html?'.http_build_query($param); //$json = CurlConnect($jsonurl $json = file_get_contents($jsonurl); $json_output = json_decode($json); Search form should search in deals: title, description
Sample deals json block
"deals":[ { "id":"1041296", "title":"Tüm Cinemaximum'larda İndirimli Sinema Biletleri 9.50 TL'den Başlayan Fiyatlarla!", "description":"Cinemaximum İndirimli Bilet Fırsatı\r\nCinemaximum'larda indirimli bilet fırsatını kaçırmayın. ", "howToUse":null, "endDate":"2015-12-26 23:59:59", "discountPercent":"41", "country":"Turkey", "businessIds":"", "latLngs":"", "city":"", "provider":"Fırsat Bu Fırsat", "realPriceWithSymbol":"16 TL", "dealPriceWithSymbol":"9.50 TL", "showDealUrl":"http://www.firsatbufirsat.com/firsat/tum-cinemaximumlarda-indirimli-sinema-biletleri?pid=316", "buyDealUrl":"http://www.firsatbufirsat.com/satin-al/1041296/tum-cinemaximumlarda-indirimli-sinema-biletleri.html?pid=316", "image200_H":"http://img1.mekan.com/files/images/deal/image/200_H/104/1041296_b9ef.jpg?r=2", "timeLeft":43377 },...
-24710728 0 you need to set these attributes of elements as as:
$(document).ready(function () { $('#group').on('click', '.add_subgroup', function () { var i = $('div.subgroup').length; var where = $('#group'); var subgroup = $('#subgroup_hidden').clone(); var j = i + 1; subgroup.attr({ 'id': 'subgroup_' + j, 'class': 'subgroup' }).appendTo(where); subgroup.find('input, select, textarea').each(function(){ $(this).attr({ name: '', value: '' }) if($(this).is('textarea')) $(this).text(''); }) i++; }); $('#group').on('click', '.remove_subgroup', function () { $(this).closest('.subgroup').remove(); }); });
-27886245 0 How to change the URL after a navigation using jQuery Mobile's $.mobile.navigate I'm new to jQuery Mobile and I've been trying so hard (been googling for 2 days straight) to understand how the navigation to external pages works but finding it really hard so hopefully I can get a proper explanation here. From my searches I've found the $.mobile.navigate function but I haven't quite figured out how exactly to use it.
Basically what I have is a login.php page, after you successfully logged in you should be taken to the homepage.php, I've managed to make it so that the homepage.php's content is shown, but when it comes to the URL I can see for a split second that it changes to homepage.php but immidiately changes back to login.php. How can I make it so that it stays on homepage.php?
I navigate to homepage.php with $.mobile.navigate like so:
<input type="submit" form="login-form" name="submit_login" value="Logga in" id="submit-login"> $('body').on('click', '#submit-login', function() { $.mobile.navigate('../../includes/pages/homepage.php'); }); And currently my homepage.php file looks like this:
<div data-role="page" data-url="homepage" data-theme="b" id="homepage"> <div data-role="header">Some content here</div> <div data-role="main">Some content here</div> <div data-role="footer">Some content here</div> </div> I read somewhere that data-url is used for changing the url on navigation but I haven't been able to make any use of it from my attempts.
I want to set few woocommerce product price free based on warranty status.
Products are: $target_products = array('2917','1229','1277');
for Example : $warranty_status = 1 mean, valid for warranty .
if a customer has a valid warranty status the price of selective product will be free. So I try bellow code and I'm sucked at how to get all $target_products price & set their new value . I'm not sure which hook will work fine.
function warranty_free_price( $price, $product ) { global $current_user,$wpdb; $target_products = array('2917','1229','1277'); get_currentuserinfo(); $loggedin_user_id = $current_user->user_login ; //check for warranty status $warranty_status = $wpdb->get_var("SELECT warranty_stat FROM {$wpdb->prefix}wc_product_license_reg WHERE customer = '$loggedin_user_id'"); if(!$warranty_status == 1){ return; // 1 = valid for warranty }else{ if ( in_array ($product->product_id ,$target_products ) ) { foreach (----------){//help me to figure this out $price = $product->get_price(); }//end for each } // return warranty price return $price; } } add_filter('woocommerce_get_price_html', 'warranty_free_price', 10, 2); Please help...
-12575402 0 Split jQuery cycle pager into divsI have a jQuery cycle slider working fine, but the pager I need split into different places. The paging itself works, but the active slide is the same for each div - i.e. for the first slide, the first pager in each div will show as active. I'm having a hard figuring out how to solve this problem!
An example of what I'm trying to achieve is the paging of this site http://www.cote-carmes.com/en-en/rooms.php.
The idea of the markup is as follows:
<div id="home-content"> <div class="home-sub first"> <ul class="slide-nav"> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> </ul> </div> <div class="home-sub"> <ul class="slide-nav"> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> </ul> </div> <div class="home-sub"> <ul class="slide-nav"> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> </ul> </div> </div> And the jQuery I have as follows:
$('#home-slider').cycle({ pager: '#home-content ul', pagerAnchorBuilder: function(idx, slide) { // return selector string for existing anchor return '#home-content li:eq(' + idx + ') a'; } }); Please help!
-15872236 0Your code works fine for me. What error you might be having is in processFile function you are creating a file object from the fileName, which is not existing. Then might be trying to read the contents of the file which might be throwing you FileNotFoundException. just comment processFile function and your code will work.
-30209091 0 JComboBox does not trigger actionPerformed() when there is an exception on the AWT-EventQueue-0 thread //This is my test class Public class crazySwing extends JFrame { private DefaultListModel model; public crazySwing() { initUI(); } private void initUI() { Vector v= new Vector(); v.add(1); v.add(2); //comboxbox with 2 items JComboBox test = new JComboBox(v); test.addActionListener(new ClickAction()); createLayout(test); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); } private void createLayout(JComponent... arg) { JPanel pane = (JPanel) getContentPane(); GroupLayout gl = new GroupLayout(pane); pane.setLayout(gl); pane.setToolTipText("Content pane"); gl.setAutoCreateContainerGaps(true); gl.setHorizontalGroup(gl.createSequentialGroup() .addComponent(arg[0]) .addGap(200) ); gl.setVerticalGroup(gl.createSequentialGroup() .addComponent(arg[0]) .addGap(120) ); pack(); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { crazySwing ex = new crazySwing(); ex.setVisible(true); } }); } private class ClickAction extends AbstractAction { @Override public void actionPerformed(ActionEvent e) { System.out.println("testing on exception"); //This will trigger a null Pointer exception List test = null; test.get(0); } } } Hi guys, I'm working on a Java rich client and I encountered the above symptom. When the JComboBox is clicked for the first time, a null pointer exception will be thrown by the code and then, when I try clicking on the JComboxBox again, actionPerformed() is not triggered.
I have tried it on a JButton but it won't happen to a JButton.
This is not a question about how to resolve a NPE. Kindly read the posting title.
-30131063 0The myCar variable is not visible in displayMenu() method. Try passing it in as parameter like:
public static void displayMenu(Car[] myCar) Also, @ryekayo's suggestion will give you accurate results.
Also make sure that Car class has a toString() method in order to print it.
how do I make a class that MUST be instantiated it, or anything like that. If it is possible anyway..
-38003890 0 RecyclerView's textview store/restore state in android fragment not workingI am developing one android application my problem structure is like this.
One activity contains one fragment and this fragment contains one RecyclerView. RecyclerView item contains two textviews which displays simple text like this :
TextTitle TextValue --> item1 TextTitle TextValue --> item2 TextTitle TextValue --> item3 If User taps on text value, its value gets changed (Value is binary so it will be only two). If user change first two item's value by tapping and I want to restore those two values when I will come back to this fragment with a help of restore/save state.
I followed many articles and gather information that if I have to use proper unique id in item's view layout for both textviews then recyclerview state will be stored automatically, only just you need to save whole recyclerview state. Its not working in my case. What am I doing wrong? Do I need to fill adapter again?
any help would be appreciated.
@Override public void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(INSTANCE_STATE_CONTENT_RECYCLER_VIEW,recyclerView.getLayoutManager().onSaveInstanceState()); } // again restore it restore it if (recyclerViewState != null) { recyclerView.getLayoutManager().onRestoreInstanceState(recyclerViewState); recyclerViewState = null; } @Override public void onViewBound(@Nullable Bundle savedInstanceState) { //super.onViewBound(savedInstanceState); if (savedInstanceState != null) { recyclerViewState = savedInstanceState.getParcelable(INSTANCE_STATE_CONTENT_RECYCLER_VIEW); } // continue with my work. }
-8791424 0 Setting ASP.NET Cache control headers In my asp.net forms app. I'm trying to prevent caching of certain pages. to do so I've set a series of cache control headers using Response.AppendHeader e.g.
protected override void OnLoad(Eventargs e) { ... Response.ClearHeaders(); Response.AppendHeader("Cache-Control","no-cache"); .... base.OnLoad(e); } Trouble is when I view my site and look at the Net tab in the Firefox console to view the request/response headers I see a behavior as follows:
a POST request/response for the page1.aspx which triggers a redirect (to page2.aspx) the response here contains the correct headers.
a GET request/response for page2.aspx associated response has the cache-control header just has a value 'pre-check=0'
That second request seems to allow the caching to happen for the page.. note: page1.aspx and page2.aspx both have the OnLoad logic I describe above. Also if I take some action on page2.aspx, the POST response will again have the correct headers.
What am I missing here? My expectation was that with the logic in OnLoad should mean that I always get the headers in the response and therefore 'always' get the current version of the page?
What I'm seeing is firefox loading it's cached version of the page.
I'm considering creating a random identifier in the request url to force the matter, but that seems a little heavy handed.
-----update----- It seems that, this may be related to having the caching code in 'OnLoad'. I've added these headers to the Page_Load() of the page and it works fine? any thoughts.
-14909719 0 Naming convention for IDs in AndroidAndroid 2.3.3.
I have a question regarding naming the IDs in Android.
Let's say I have two buttons in Activity1 (save and cancel). I name them (IDs) as btnSave and btnCancel. Now I have Activity2, where in I have save and cancel buttons as well. Both does the same functionality. What will happen if I give the IDs as btnSave and btnCancel.
Will i face a problem while compiling? When I press, R.id. and ctrl+space, will I get two btnSave and btnCancel(s) to choose from?
And most importantly, Why should I name them differently, if I should?
-35683444 0 Getting the elapsed milliseconds from the beginning of the last secondBefore everything sorry for my english, i am italian, and italians are not so good with other langs... Anyway, here's my actual code:
time_t t = time(0); struct tm * now = localtime( & t ); cout << (now->tm_mday) << '/' << (now->tm_mon + 01) << '/' << (now->tm_year + 1900) << endl; cout << (now->tm_hour) << ':' << (now->tm_min) << ':' << (now->tm_sec) << endl; cout << ; system("cls");` Well, as you can see it prints out date(italian date order, so GG-MM-YYYY) and hour:mins:secs. Is there something like now->tm_millisecond? Or it's more complicated? As you can imagine i don't want the current date in millinseconds(millisecons passed till years 0) as almost everyone wants. I just want to get the elapsed time in MSs from the last beginning of a second. I am a beginner in c++, the basic code's took around the web. I just wan't the satisfaction to get itfinished. PLEASE DO NOT TELL ME TO MAKE BETTER THIS, TO MAKE BETTER THAT, TO USE A NEW WAY TO CLEAR SCREEN INSTEAD OF system("cls") RESPOND TO WHAT I ASKED.
Try changing the C# interface to take a ref parameter.
The question I have is kind of simular to this one - MySQL select 1 row from inner join
However, it was never really answered in the way that I needed it. So I thought I would ask.
I have a table A (tableA) and this table has a load of states in tableB. New states keep being added all the time.
TableB has a column 'State' which has a foreign key to TableA.Id. This table B has a value and timestamp
I am trying to get ONE query which will bring back ALL values in TableA, with an inner join to bring the LATEST 'value' of those rows from tableB. The latest being the one with the latest time.
I know how to do an inner join where it needs to be, and I know how to order a table to bring back the latest 'time' row, however I dont know how to put these two together and create a single query.
I'm sure I will have to have a Select within a select, which is fine. However, what I am trying to avoid is to bring a DataTable back with all my results from TableA and do a query for each of those on tableB seperately.
Any ideas?
EDIT - I have made a mistake with the question, I only really noticed when trying to implement one of the answers.
I have a foreign key between TableA.id and TableB.proId
TableA - 'Id', 'Name' TableB - 'Id', 'proId', 'State', 'time'
I want to bring back all values of TableA with a join on B, to bring back the 'State' of the Max time
-12681588 0 Is it possible to open a PDF with fancybox 2.1 in IE8?I'm working on a site that hosts a lot of PDF files and I want to open them in fancybox (2.1) for a preview. It works just fine in Chrome and Firefox. But it just won't work in IE8. I've tried linking directly to the PDF file, linking to an iframe, and linking to an embed tag (among other crazier things). I can't use google to wrap them. Here is a page that demonstrates the problem.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>My Page</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script> <script type="text/javascript" src="jquery.fancybox.js?v=2.1.0"></script> <link type="text/css" rel="stylesheet" media="screen" href="jquery.fancybox.css" /> </head> <body style="background-color:grey"> <p><a href="mypdffile.pdf" class="fancypdf">a link</a> to a PDF file.</p> <p><a href="#Frame1" class="fancy">a link</a> to an iframe with the pdf in it.</p> <div style="display:none"> <iframe id="Frame1" src="mypdffile.pdf" style='width:100%;' height="600" frameborder="0" allowTransparency="true"></iframe> </div> <p><a class="fancy" href="#mypdf" >a link</a> to a pdf in an embed tab</p> <div style="display:none"><div id="mypdf"> <embed src="mypdffile.pdf" type="application/pdf" width="640" height="480" /> </div></div> <script type='text/javascript'> $(function(){ $("a.fancypdf").fancybox({type:'iframe'}); $("a.fancy").fancybox(); }); </script> </body> </html> The results are different each time. In IE for the first link the spinner appears and hangs. For the second two, a fancybox popup appears, but it's empty. What am I doing wrong?
-38745811 0This is my Item model
public class Item { [Key] public int ID { get; set; } [Display(Name = "Nazwa przedmiotu")] [Required(ErrorMessage = "Nazwa przedmiotu jest wymagana.")] public string Nazwa { get; set; } [Required(ErrorMessage = "Kategoria jest wymagana.")] public string Kategoria { get; set; } public string Magazyn { get; set; } [Required(ErrorMessage = "Kod jest wymagany.")] public string Kod { get; set; } [Display(Name = "Ilość zakupiona")] //[Required(ErrorMessage = "Ilość ogólna jest wymagana.")] public double Ilosc_zakupiona { get; set; } [Display(Name = "Ilość wypożyczona")] //[Required(ErrorMessage = "Ilość wypożyczona jest wymagana.")] public double Ilosc_wypozyczona { get; set; } [Display(Name = "Ilość magazynowa")] //[Required(ErrorMessage = "Ilość magazynowa jest wymagana.")] public double Ilosc_magazynowa { get; set; } [Display(Name = "Ilość zużyta")] //[Required(ErrorMessage = "Ilość zużyta jest wymagana.")] public double Ilosc_zuzyta { get; set; } [Display(Name = "Straty")] //[Required(ErrorMessage = "Straty są wymagane.")] public double Straty { get; set; } public string Sektor { get; set; } [Display(Name = "Półka")] public string Polka { get; set; } [Display(Name = "Pojemnik")] public string Pojemnik { get; set; } } And the HttpPost function
[HttpPost] public ActionResult DodajPrzedmiot(Item itm) { if (ModelState.IsValid) { try { using (var db = new DatabaseContext()) { if (itm.Ilosc_zakupiona - itm.Ilosc_wypozyczona < 0) throw new ArgumentOutOfRangeException(); itm.Ilosc_magazynowa = itm.Ilosc_zakupiona - itm.Ilosc_wypozyczona; db.Items.Add(itm); //db.Database.ExecuteSqlCommand("INSERT INTO Items(Nazwa_przedmiotu, Kategoria, Kod, Ilosc_ogolna, Ilosc_pozostala, Ilosc_wypozyczona, Wartosc, Sektor, Regal) VALUES({0},{1},{2},{3},{4},{5},{6},{7},{8},{9})", itm.Nazwa_przedmiotu, itm.Kategoria, itm.Kod, itm.Ilosc_ogolna, itm.Ilosc_pozostala, itm.Ilosc_wypozyczona, itm.Wartosc, itm.Sektor, itm.Regal); db.SaveChanges(); } } catch (System.Data.Entity.Infrastructure.DbUpdateException) { ViewBag.ErrorMessage = "Istnieje już przedmiot o takiej nazwie i/lub kodzie!"; return View(); } catch (ArgumentOutOfRangeException) { ViewBag.ErrorMessage = "Ilość zakupiona i/lub wypożyczona nie mogą być mniejsze od zera!"; return View(); } } return View(); } Well it passes to the Post function and adds all information to database and in the same time it show the same error I wrote before.
-17863814 0Handling the TextChanged event should work, however you need to set the DropDownStyle to DropDownList so that the Text property can only be a given value. Then check to see that both comboboxes have values selected. something like this should work:
If ComboBox_Ticker.Text <> "" AndAlso DateTime.TryParse(ComboBox_Date.Text, Nothing) Then
-6723161 0 Simple example of CALayers in an NSViewI am trying to add several CALayers to an NSView but my view remains empty when shown:
Here is my code:
- (id)initWithFrame:(NSRect)frame { self = [super initWithFrame:frame]; if (self) { self.layer = [CALayer layer]; self.wantsLayer = YES; CALayer *newLayer = [CALayer layer]; NSImage *image = [NSImage imageNamed:@"page.png"]; newLayer.backgroundColor = [NSColor redColor].CGColor; newLayer.contents = (id)[image CGImageForProposedRect:NULL context:NULL hints:nil]; newLayer.frame = NSMakeRect(100,100,100,100);//NSMakeRect(0,0,image.size.width,image.size.height); newLayer.position = CGPointMake(20,20); [self.layer addSublayer:newLayer]; } return self; }
DO have any idea (or example of code) to perform this task?
Thanks and regards,
-39332949 0I am not really sure what you mean by integrating bootstrap with Meanjs, according to me it is already integrated in the default app. If you go to config/assets/default.js and config/assets/production.js (one is for development and the other for production) under client.lib.css and client.lib.js the bootstrap modules are specified. These modules are loaded in modules/core/server/views/layout.server.view.html just under the comments <!-- Application CSS Files --> and <!--Application JavaScript Files--> when the application starts.
If you want to upgrade to the latest Bootstrap just change the version number in your bower.json file and run the command bower update.
I want to learn and work with initialize.php so I try to build simple php file like index.php and just to see if it call to hello.php I got some truble on my local host using windows xp.
the details are:
http://127.0.0.1/www/oop/shape2/index.php the file index.php
<?php defined('DS') ? null : define('DS', '/'); defined('SITE_ROOT') ? null :defined('SITE_ROOT', $_SERVER['DOCUMENT_ROOT']); defined('LIB_PATH') ? null : define('LIB_PATH', SITE_ROOT.DS.'includes'); echo (LIB_PATH.DS.'hello.php'); require_once(LIB_PATH.DS.'hello.php'); ?> the output is:
SITE_ROOT/includes/hello.php http://127.0.0.1/www/oop/shape2/includes/hello.php the file hello.php
<?php echo ('hi'); ?> if i run it I got hi
here is my local folder on windows: C:\Program Files\Zend\Apache2\htdocs\www\oop\shape2
what shell I do slove the problem. Thx
-519912 0If I am making changes to already written T-SQL, then I follow the already used convention (if there is one).
If I am writing from scratch or there is no convention, then I tend to follow your convention given in the question, except I prefer to use capital letters for keywords (just a personal preference for readability).
I think with SQL formatting as with other code format conventions, the important point is to have a convention, not what that convention is (within the realms of common sense of course!)
-29391036 0 How to remove unknown white border of asp:image inside panelI have white border of an asp:image control and i want to remove it but can't find where the problem is
here is my html and css:
<asp:Panel runat="server" CssClass="nav" ID="nav"> <asp:Image runat="server" ID="Logo" CssClass="logo" /> <asp:LinkButton runat="server" ID="lb1" CssClass="navButtons">Home</asp:LinkButton> <asp:LinkButton runat="server" ID="LinkButton1" CssClass="navButtons">Restorant</asp:LinkButton> <asp:LinkButton runat="server" ID="LinkButton2" CssClass="navButtons">Rooms</asp:LinkButton> <asp:LinkButton runat="server" ID="LinkButton3" CssClass="navButtons">Spa</asp:LinkButton> <asp:LinkButton runat="server" ID="LinkButton4" CssClass="navButtons">Contact</asp:LinkButton> <asp:LinkButton runat="server" ID="LinkButton5" CssClass="navButtons">Contact</asp:LinkButton> <asp:LinkButton runat="server" ID="LinkButton6" CssClass="navButtons">Contact</asp:LinkButton> </asp:Panel> the image with ID="Logo" is white bordered and i need to remove this border
CSS of image and Nav panel:
.logo { width:100%; height:150px; background-image:url(Background/logo.jpg); float:left; background-repeat:no-repeat; -moz-background-size: 100% 100%; -o-background-size: 100% 100%; -webkit-background-size: 100% 100%; background-size: 100% 100%; position:relative; border:none; } .nav { position:absolute; background-color:black; opacity:0.6; filter: alpha(opacity=60); height:550px; width:250px; z-index:3; max-height:550px; max-width:250px; }
-23553224 0 l is type of long ...
so you need to extract long instead of String like
videoLong = extras.getLong("videoId"); so the full implementation of second intent is
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final VideoView videoView; setContentView(R.layout.activity_play_video); Bundle extras; Long videoLong; if (savedInstanceState == null) { extras = getIntent().getExtras(); if (extras == null) { videoLong= null; } else { videoLong= extras.getLong("videoId"); System.out.println("video id intent 2 = " + videoLong); } }
-22543814 0 You could just use transitionTo().
Alternatively this answer suggests using
Ember.HistoryLocation.replaceState(<string>); or
router.replaceWith('index');
-18307596 0 How to check if two images are similar or not using openCV in java? I have to check if two images are similar or not in java using OpenCV, I am using OpenCV for that and using ORB
Here is my main class
System.out.println("Welcome to OpenCV " + Core.VERSION); System.loadLibrary(Core.NATIVE_LIBRARY_NAME);()); System.out.println(System.getProperty("user.dir")); File f1 = new File(System.getProperty("user.dir") + "\\test.jpg"); File f2 = new File(System.getProperty("user.dir") + "\\test2.jpg"); MatchingDemo2 m = new MatchingDemo2(); m.mth(f1.getAbsolutePath(), f2.getAbsolutePath()); And here is my MatchingDemo2.java file
public class MatchingDemo2 { public void mth(String inFile, String templateFile){ FeatureDetector detector = FeatureDetector.create(FeatureDetector.ORB); //Create descriptors //first image // generate descriptors //second image // generate descriptors System.out.println("size " + matches.size()); //HOW DO I KNOW IF IMAGES MATCHED OR NOT ???? //THIS CODE IS FOR CONNECTIONS BUT I AM NOT ABLE TO DO IT //feature and connection colors Scalar RED = new Scalar(255,0,0); Scalar GREEN = new Scalar(0,255,0); //output image Mat outputImg = new Mat(); MatOfByte drawnMatches = new MatOfByte(); //this will draw all matches, works fine Features2d.drawMatches(img1, keypoints1, img2, keypoints2, matches, outputImg, GREEN, RED, drawnMatches, Features2d.NOT_DRAW_SINGLE_POINTS); int DIST_LIMIT = 80; List<DMatch> matchList = matches.toList(); List<DMatch> matches_final = new ArrayList<DMatch>(); for(int i=0; i<matchList.size(); i++){ if(matchList.get(i).distance <= DIST_LIMIT){ matches_final.add(matches.toList().get(i)); } } MatOfDMatch matches_final_mat = new MatOfDMatch(); matches_final_mat.fromList(matches_final); for(int i=0; i< matches_final.size(); i++){ System.out.println("Good Matchs "+ matches_final.get(i)); } } } But when i check the Good Matchs i get this
size 1x328 Good Matchs DMatch [queryIdx=0, trainIdx=93, imgIdx=0, distance=52.0] Good Matchs DMatch [queryIdx=1, trainIdx=173, imgIdx=0, distance=57.0] Good Matchs DMatch [queryIdx=2, trainIdx=92, imgIdx=0, distance=53.0] Good Matchs DMatch [queryIdx=3, trainIdx=80, imgIdx=0, distance=26.0] Good Matchs DMatch [queryIdx=5, trainIdx=164, imgIdx=0, distance=40.0] Good Matchs DMatch [queryIdx=6, trainIdx=228, imgIdx=0, distance=53.0] Good Matchs DMatch [queryIdx=7, trainIdx=179, imgIdx=0, distance=14.0] Good Matchs DMatch [queryIdx=8, trainIdx=78, imgIdx=0, distance=61.0] Good Matchs DMatch [queryIdx=9, trainIdx=166, imgIdx=0, distance=69.0] Good Matchs DMatch [queryIdx=10, trainIdx=74, imgIdx=0, distance=65.0] Good Matchs DMatch [queryIdx=11, trainIdx=245, imgIdx=0, distance=38.0] Good Matchs DMatch [queryIdx=12, trainIdx=120, imgIdx=0, distance=66.0] Good Matchs DMatch [queryIdx=13, trainIdx=244, imgIdx=0, distance=41.0] Good Matchs DMatch [queryIdx=14, trainIdx=67, imgIdx=0, distance=50.0] Good Matchs DMatch [queryIdx=15, trainIdx=185, imgIdx=0, distance=55.0] Good Matchs DMatch [queryIdx=16, trainIdx=97, imgIdx=0, distance=21.0] Good Matchs DMatch [queryIdx=17, trainIdx=172, imgIdx=0, distance=67.0] Good Matchs DMatch [queryIdx=18, trainIdx=354, imgIdx=0, distance=67.0] Good Matchs DMatch [queryIdx=19, trainIdx=302, imgIdx=0, distance=53.0] Good Matchs DMatch [queryIdx=20, trainIdx=176, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=21, trainIdx=60, imgIdx=0, distance=66.0] Good Matchs DMatch [queryIdx=22, trainIdx=72, imgIdx=0, distance=62.0] Good Matchs DMatch [queryIdx=23, trainIdx=63, imgIdx=0, distance=54.0] Good Matchs DMatch [queryIdx=24, trainIdx=176, imgIdx=0, distance=63.0] Good Matchs DMatch [queryIdx=25, trainIdx=49, imgIdx=0, distance=58.0] Good Matchs DMatch [queryIdx=26, trainIdx=77, imgIdx=0, distance=52.0] Good Matchs DMatch [queryIdx=27, trainIdx=302, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=28, trainIdx=265, imgIdx=0, distance=71.0] Good Matchs DMatch [queryIdx=29, trainIdx=67, imgIdx=0, distance=49.0] Good Matchs DMatch [queryIdx=30, trainIdx=302, imgIdx=0, distance=64.0] Good Matchs DMatch [queryIdx=31, trainIdx=265, imgIdx=0, distance=65.0] Good Matchs DMatch [queryIdx=32, trainIdx=73, imgIdx=0, distance=73.0] Good Matchs DMatch [queryIdx=33, trainIdx=67, imgIdx=0, distance=55.0] Good Matchs DMatch [queryIdx=34, trainIdx=283, imgIdx=0, distance=63.0] Good Matchs DMatch [queryIdx=35, trainIdx=145, imgIdx=0, distance=60.0] Good Matchs DMatch [queryIdx=36, trainIdx=71, imgIdx=0, distance=54.0] Good Matchs DMatch [queryIdx=37, trainIdx=167, imgIdx=0, distance=67.0] Good Matchs DMatch [queryIdx=38, trainIdx=94, imgIdx=0, distance=60.0] Good Matchs DMatch [queryIdx=39, trainIdx=88, imgIdx=0, distance=68.0] Good Matchs DMatch [queryIdx=40, trainIdx=88, imgIdx=0, distance=69.0] Good Matchs DMatch [queryIdx=41, trainIdx=179, imgIdx=0, distance=28.0] Good Matchs DMatch [queryIdx=42, trainIdx=64, imgIdx=0, distance=61.0] Good Matchs DMatch [queryIdx=43, trainIdx=223, imgIdx=0, distance=71.0] Good Matchs DMatch [queryIdx=44, trainIdx=80, imgIdx=0, distance=30.0] Good Matchs DMatch [queryIdx=45, trainIdx=196, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=46, trainIdx=52, imgIdx=0, distance=65.0] Good Matchs DMatch [queryIdx=47, trainIdx=93, imgIdx=0, distance=60.0] Good Matchs DMatch [queryIdx=48, trainIdx=187, imgIdx=0, distance=49.0] Good Matchs DMatch [queryIdx=49, trainIdx=179, imgIdx=0, distance=50.0] Good Matchs DMatch [queryIdx=50, trainIdx=283, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=51, trainIdx=171, imgIdx=0, distance=61.0] Good Matchs DMatch [queryIdx=52, trainIdx=302, imgIdx=0, distance=60.0] Good Matchs DMatch [queryIdx=53, trainIdx=67, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=54, trainIdx=15, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=55, trainIdx=173, imgIdx=0, distance=66.0] Good Matchs DMatch [queryIdx=56, trainIdx=302, imgIdx=0, distance=56.0] Good Matchs DMatch [queryIdx=57, trainIdx=47, imgIdx=0, distance=56.0] Good Matchs DMatch [queryIdx=58, trainIdx=187, imgIdx=0, distance=58.0] Good Matchs DMatch [queryIdx=59, trainIdx=344, imgIdx=0, distance=64.0] Good Matchs DMatch [queryIdx=60, trainIdx=164, imgIdx=0, distance=65.0] Good Matchs DMatch [queryIdx=61, trainIdx=125, imgIdx=0, distance=50.0] Good Matchs DMatch [queryIdx=62, trainIdx=77, imgIdx=0, distance=72.0] Good Matchs DMatch [queryIdx=63, trainIdx=22, imgIdx=0, distance=79.0] Good Matchs DMatch [queryIdx=64, trainIdx=82, imgIdx=0, distance=69.0] Good Matchs DMatch [queryIdx=65, trainIdx=93, imgIdx=0, distance=63.0] Good Matchs DMatch [queryIdx=66, trainIdx=241, imgIdx=0, distance=35.0] Good Matchs DMatch [queryIdx=67, trainIdx=80, imgIdx=0, distance=18.0] Good Matchs DMatch [queryIdx=68, trainIdx=179, imgIdx=0, distance=20.0] Good Matchs DMatch [queryIdx=69, trainIdx=242, imgIdx=0, distance=50.0] Good Matchs DMatch [queryIdx=70, trainIdx=80, imgIdx=0, distance=22.0] Good Matchs DMatch [queryIdx=71, trainIdx=179, imgIdx=0, distance=19.0] Good Matchs DMatch [queryIdx=72, trainIdx=92, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=73, trainIdx=94, imgIdx=0, distance=56.0] Good Matchs DMatch [queryIdx=74, trainIdx=173, imgIdx=0, distance=49.0] Good Matchs DMatch [queryIdx=75, trainIdx=94, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=76, trainIdx=94, imgIdx=0, distance=48.0] Good Matchs DMatch [queryIdx=77, trainIdx=92, imgIdx=0, distance=52.0] Good Matchs DMatch [queryIdx=78, trainIdx=80, imgIdx=0, distance=20.0] Good Matchs DMatch [queryIdx=80, trainIdx=119, imgIdx=0, distance=61.0] Good Matchs DMatch [queryIdx=81, trainIdx=228, imgIdx=0, distance=47.0] Good Matchs DMatch [queryIdx=82, trainIdx=179, imgIdx=0, distance=14.0] Good Matchs DMatch [queryIdx=83, trainIdx=227, imgIdx=0, distance=52.0] Good Matchs DMatch [queryIdx=84, trainIdx=84, imgIdx=0, distance=57.0] Good Matchs DMatch [queryIdx=85, trainIdx=245, imgIdx=0, distance=40.0] Good Matchs DMatch [queryIdx=86, trainIdx=58, imgIdx=0, distance=64.0] Good Matchs DMatch [queryIdx=87, trainIdx=14, imgIdx=0, distance=62.0] Good Matchs DMatch [queryIdx=88, trainIdx=187, imgIdx=0, distance=61.0] Good Matchs DMatch [queryIdx=89, trainIdx=185, imgIdx=0, distance=57.0] Good Matchs DMatch [queryIdx=90, trainIdx=178, imgIdx=0, distance=25.0] Good Matchs DMatch [queryIdx=91, trainIdx=220, imgIdx=0, distance=56.0] Good Matchs DMatch [queryIdx=92, trainIdx=205, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=93, trainIdx=60, imgIdx=0, distance=61.0] Good Matchs DMatch [queryIdx=94, trainIdx=44, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=95, trainIdx=16, imgIdx=0, distance=72.0] Good Matchs DMatch [queryIdx=96, trainIdx=157, imgIdx=0, distance=63.0] Good Matchs DMatch [queryIdx=97, trainIdx=135, imgIdx=0, distance=52.0] Good Matchs DMatch [queryIdx=98, trainIdx=60, imgIdx=0, distance=61.0] Good Matchs DMatch [queryIdx=99, trainIdx=344, imgIdx=0, distance=60.0] Good Matchs DMatch [queryIdx=100, trainIdx=77, imgIdx=0, distance=67.0] Good Matchs DMatch [queryIdx=101, trainIdx=95, imgIdx=0, distance=76.0] Good Matchs DMatch [queryIdx=102, trainIdx=72, imgIdx=0, distance=45.0] Good Matchs DMatch [queryIdx=103, trainIdx=134, imgIdx=0, distance=70.0] Good Matchs DMatch [queryIdx=104, trainIdx=154, imgIdx=0, distance=54.0] Good Matchs DMatch [queryIdx=105, trainIdx=208, imgIdx=0, distance=77.0] Good Matchs DMatch [queryIdx=106, trainIdx=73, imgIdx=0, distance=79.0] Good Matchs DMatch [queryIdx=107, trainIdx=72, imgIdx=0, distance=61.0] Good Matchs DMatch [queryIdx=108, trainIdx=64, imgIdx=0, distance=73.0] Good Matchs DMatch [queryIdx=109, trainIdx=72, imgIdx=0, distance=63.0] Good Matchs DMatch [queryIdx=110, trainIdx=365, imgIdx=0, distance=66.0] Good Matchs DMatch [queryIdx=111, trainIdx=148, imgIdx=0, distance=64.0] Good Matchs DMatch [queryIdx=112, trainIdx=81, imgIdx=0, distance=42.0] Good Matchs DMatch [queryIdx=113, trainIdx=56, imgIdx=0, distance=62.0] Good Matchs DMatch [queryIdx=114, trainIdx=162, imgIdx=0, distance=48.0] Good Matchs DMatch [queryIdx=115, trainIdx=56, imgIdx=0, distance=56.0] Good Matchs DMatch [queryIdx=116, trainIdx=120, imgIdx=0, distance=58.0] Good Matchs DMatch [queryIdx=117, trainIdx=72, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=118, trainIdx=92, imgIdx=0, distance=63.0] Good Matchs DMatch [queryIdx=119, trainIdx=131, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=120, trainIdx=72, imgIdx=0, distance=46.0] Good Matchs DMatch [queryIdx=121, trainIdx=74, imgIdx=0, distance=78.0] Good Matchs DMatch [queryIdx=122, trainIdx=94, imgIdx=0, distance=56.0] Good Matchs DMatch [queryIdx=123, trainIdx=72, imgIdx=0, distance=52.0] Good Matchs DMatch [queryIdx=124, trainIdx=134, imgIdx=0, distance=71.0] Good Matchs DMatch [queryIdx=125, trainIdx=72, imgIdx=0, distance=46.0] Good Matchs DMatch [queryIdx=126, trainIdx=15, imgIdx=0, distance=73.0] Good Matchs DMatch [queryIdx=127, trainIdx=72, imgIdx=0, distance=50.0] Good Matchs DMatch [queryIdx=128, trainIdx=93, imgIdx=0, distance=56.0] Good Matchs DMatch [queryIdx=129, trainIdx=68, imgIdx=0, distance=46.0] Good Matchs DMatch [queryIdx=130, trainIdx=205, imgIdx=0, distance=65.0] Good Matchs DMatch [queryIdx=131, trainIdx=187, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=132, trainIdx=72, imgIdx=0, distance=47.0] Good Matchs DMatch [queryIdx=133, trainIdx=220, imgIdx=0, distance=57.0] Good Matchs DMatch [queryIdx=134, trainIdx=289, imgIdx=0, distance=60.0] Good Matchs DMatch [queryIdx=135, trainIdx=82, imgIdx=0, distance=65.0] Good Matchs DMatch [queryIdx=136, trainIdx=93, imgIdx=0, distance=53.0] Good Matchs DMatch [queryIdx=137, trainIdx=244, imgIdx=0, distance=18.0] Good Matchs DMatch [queryIdx=138, trainIdx=244, imgIdx=0, distance=25.0] Good Matchs DMatch [queryIdx=139, trainIdx=92, imgIdx=0, distance=66.0] Good Matchs DMatch [queryIdx=140, trainIdx=244, imgIdx=0, distance=20.0] Good Matchs DMatch [queryIdx=141, trainIdx=93, imgIdx=0, distance=45.0] Good Matchs DMatch [queryIdx=142, trainIdx=93, imgIdx=0, distance=51.0] Good Matchs DMatch [queryIdx=143, trainIdx=94, imgIdx=0, distance=51.0] Good Matchs DMatch [queryIdx=144, trainIdx=94, imgIdx=0, distance=40.0] Good Matchs DMatch [queryIdx=145, trainIdx=93, imgIdx=0, distance=47.0] Good Matchs DMatch [queryIdx=146, trainIdx=244, imgIdx=0, distance=28.0] Good Matchs DMatch [queryIdx=147, trainIdx=172, imgIdx=0, distance=77.0] Good Matchs DMatch [queryIdx=148, trainIdx=170, imgIdx=0, distance=72.0] Good Matchs DMatch [queryIdx=149, trainIdx=261, imgIdx=0, distance=72.0] Good Matchs DMatch [queryIdx=150, trainIdx=228, imgIdx=0, distance=55.0] Good Matchs DMatch [queryIdx=151, trainIdx=179, imgIdx=0, distance=19.0] Good Matchs DMatch [queryIdx=152, trainIdx=227, imgIdx=0, distance=60.0] Good Matchs DMatch [queryIdx=153, trainIdx=107, imgIdx=0, distance=56.0] Good Matchs DMatch [queryIdx=154, trainIdx=174, imgIdx=0, distance=41.0] Good Matchs DMatch [queryIdx=155, trainIdx=283, imgIdx=0, distance=76.0] Good Matchs DMatch [queryIdx=156, trainIdx=254, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=157, trainIdx=185, imgIdx=0, distance=51.0] Good Matchs DMatch [queryIdx=158, trainIdx=178, imgIdx=0, distance=30.0] Good Matchs DMatch [queryIdx=159, trainIdx=278, imgIdx=0, distance=53.0] Good Matchs DMatch [queryIdx=160, trainIdx=91, imgIdx=0, distance=62.0] Good Matchs DMatch [queryIdx=161, trainIdx=148, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=162, trainIdx=157, imgIdx=0, distance=63.0] Good Matchs DMatch [queryIdx=163, trainIdx=373, imgIdx=0, distance=73.0] Good Matchs DMatch [queryIdx=164, trainIdx=226, imgIdx=0, distance=48.0] Good Matchs DMatch [queryIdx=165, trainIdx=278, imgIdx=0, distance=64.0] Good Matchs DMatch [queryIdx=166, trainIdx=283, imgIdx=0, distance=62.0] Good Matchs DMatch [queryIdx=167, trainIdx=196, imgIdx=0, distance=64.0] Good Matchs DMatch [queryIdx=168, trainIdx=344, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=169, trainIdx=157, imgIdx=0, distance=53.0] Good Matchs DMatch [queryIdx=170, trainIdx=144, imgIdx=0, distance=79.0] Good Matchs DMatch [queryIdx=171, trainIdx=154, imgIdx=0, distance=61.0] Good Matchs DMatch [queryIdx=172, trainIdx=211, imgIdx=0, distance=75.0] Good Matchs DMatch [queryIdx=173, trainIdx=279, imgIdx=0, distance=64.0] Good Matchs DMatch [queryIdx=174, trainIdx=211, imgIdx=0, distance=79.0] Good Matchs DMatch [queryIdx=175, trainIdx=220, imgIdx=0, distance=68.0] Good Matchs DMatch [queryIdx=176, trainIdx=218, imgIdx=0, distance=45.0] Good Matchs DMatch [queryIdx=177, trainIdx=289, imgIdx=0, distance=75.0] Good Matchs DMatch [queryIdx=178, trainIdx=223, imgIdx=0, distance=63.0] Good Matchs DMatch [queryIdx=179, trainIdx=57, imgIdx=0, distance=65.0] Good Matchs DMatch [queryIdx=180, trainIdx=36, imgIdx=0, distance=73.0] Good Matchs DMatch [queryIdx=181, trainIdx=111, imgIdx=0, distance=72.0] Good Matchs DMatch [queryIdx=182, trainIdx=93, imgIdx=0, distance=65.0] Good Matchs DMatch [queryIdx=183, trainIdx=137, imgIdx=0, distance=63.0] Good Matchs DMatch [queryIdx=184, trainIdx=157, imgIdx=0, distance=60.0] Good Matchs DMatch [queryIdx=185, trainIdx=72, imgIdx=0, distance=61.0] Good Matchs DMatch [queryIdx=186, trainIdx=172, imgIdx=0, distance=47.0] Good Matchs DMatch [queryIdx=187, trainIdx=279, imgIdx=0, distance=69.0] Good Matchs DMatch [queryIdx=188, trainIdx=72, imgIdx=0, distance=55.0] Good Matchs DMatch [queryIdx=189, trainIdx=96, imgIdx=0, distance=61.0] Good Matchs DMatch [queryIdx=190, trainIdx=220, imgIdx=0, distance=68.0] Good Matchs DMatch [queryIdx=191, trainIdx=93, imgIdx=0, distance=48.0] Good Matchs DMatch [queryIdx=192, trainIdx=279, imgIdx=0, distance=54.0] Good Matchs DMatch [queryIdx=193, trainIdx=157, imgIdx=0, distance=54.0] Good Matchs DMatch [queryIdx=194, trainIdx=91, imgIdx=0, distance=65.0] Good Matchs DMatch [queryIdx=195, trainIdx=278, imgIdx=0, distance=66.0] Good Matchs DMatch [queryIdx=196, trainIdx=220, imgIdx=0, distance=57.0] Good Matchs DMatch [queryIdx=197, trainIdx=74, imgIdx=0, distance=63.0] Good Matchs DMatch [queryIdx=198, trainIdx=93, imgIdx=0, distance=34.0] Good Matchs DMatch [queryIdx=199, trainIdx=81, imgIdx=0, distance=53.0] Good Matchs DMatch [queryIdx=200, trainIdx=93, imgIdx=0, distance=45.0] Good Matchs DMatch [queryIdx=201, trainIdx=90, imgIdx=0, distance=52.0] Good Matchs DMatch [queryIdx=202, trainIdx=93, imgIdx=0, distance=52.0] Good Matchs DMatch [queryIdx=203, trainIdx=94, imgIdx=0, distance=42.0] Good Matchs DMatch [queryIdx=204, trainIdx=93, imgIdx=0, distance=35.0] Good Matchs DMatch [queryIdx=205, trainIdx=94, imgIdx=0, distance=44.0] Good Matchs DMatch [queryIdx=206, trainIdx=90, imgIdx=0, distance=72.0] Good Matchs DMatch [queryIdx=207, trainIdx=179, imgIdx=0, distance=54.0] Good Matchs DMatch [queryIdx=208, trainIdx=92, imgIdx=0, distance=48.0] Good Matchs DMatch [queryIdx=209, trainIdx=91, imgIdx=0, distance=61.0] Good Matchs DMatch [queryIdx=210, trainIdx=119, imgIdx=0, distance=77.0] Good Matchs DMatch [queryIdx=211, trainIdx=227, imgIdx=0, distance=66.0] Good Matchs DMatch [queryIdx=212, trainIdx=186, imgIdx=0, distance=56.0] Good Matchs DMatch [queryIdx=213, trainIdx=96, imgIdx=0, distance=69.0] Good Matchs DMatch [queryIdx=214, trainIdx=77, imgIdx=0, distance=52.0] Good Matchs DMatch [queryIdx=215, trainIdx=372, imgIdx=0, distance=67.0] Good Matchs DMatch [queryIdx=216, trainIdx=334, imgIdx=0, distance=69.0] Good Matchs DMatch [queryIdx=217, trainIdx=278, imgIdx=0, distance=67.0] Good Matchs DMatch [queryIdx=218, trainIdx=325, imgIdx=0, distance=61.0] Good Matchs DMatch [queryIdx=219, trainIdx=188, imgIdx=0, distance=60.0] Good Matchs DMatch [queryIdx=220, trainIdx=340, imgIdx=0, distance=56.0] Good Matchs DMatch [queryIdx=221, trainIdx=72, imgIdx=0, distance=64.0] Good Matchs DMatch [queryIdx=222, trainIdx=278, imgIdx=0, distance=69.0] Good Matchs DMatch [queryIdx=223, trainIdx=221, imgIdx=0, distance=72.0] Good Matchs DMatch [queryIdx=224, trainIdx=339, imgIdx=0, distance=74.0] Good Matchs DMatch [queryIdx=225, trainIdx=155, imgIdx=0, distance=66.0] Good Matchs DMatch [queryIdx=226, trainIdx=278, imgIdx=0, distance=56.0] Good Matchs DMatch [queryIdx=227, trainIdx=165, imgIdx=0, distance=78.0] Good Matchs DMatch [queryIdx=228, trainIdx=279, imgIdx=0, distance=71.0] Good Matchs DMatch [queryIdx=229, trainIdx=355, imgIdx=0, distance=65.0] Good Matchs DMatch [queryIdx=231, trainIdx=69, imgIdx=0, distance=80.0] Good Matchs DMatch [queryIdx=232, trainIdx=278, imgIdx=0, distance=65.0] Good Matchs DMatch [queryIdx=233, trainIdx=65, imgIdx=0, distance=71.0] Good Matchs DMatch [queryIdx=234, trainIdx=93, imgIdx=0, distance=79.0] Good Matchs DMatch [queryIdx=235, trainIdx=203, imgIdx=0, distance=78.0] Good Matchs DMatch [queryIdx=236, trainIdx=159, imgIdx=0, distance=70.0] Good Matchs DMatch [queryIdx=237, trainIdx=93, imgIdx=0, distance=45.0] Good Matchs DMatch [queryIdx=238, trainIdx=172, imgIdx=0, distance=58.0] Good Matchs DMatch [queryIdx=239, trainIdx=374, imgIdx=0, distance=67.0] Good Matchs DMatch [queryIdx=240, trainIdx=278, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=241, trainIdx=223, imgIdx=0, distance=55.0] Good Matchs DMatch [queryIdx=242, trainIdx=365, imgIdx=0, distance=58.0] Good Matchs DMatch [queryIdx=243, trainIdx=91, imgIdx=0, distance=62.0] Good Matchs DMatch [queryIdx=244, trainIdx=238, imgIdx=0, distance=57.0] Good Matchs DMatch [queryIdx=245, trainIdx=299, imgIdx=0, distance=62.0] Good Matchs DMatch [queryIdx=246, trainIdx=289, imgIdx=0, distance=63.0] Good Matchs DMatch [queryIdx=247, trainIdx=93, imgIdx=0, distance=41.0] Good Matchs DMatch [queryIdx=249, trainIdx=5, imgIdx=0, distance=56.0] Good Matchs DMatch [queryIdx=250, trainIdx=93, imgIdx=0, distance=53.0] Good Matchs DMatch [queryIdx=251, trainIdx=93, imgIdx=0, distance=34.0] Good Matchs DMatch [queryIdx=252, trainIdx=97, imgIdx=0, distance=34.0] Good Matchs DMatch [queryIdx=253, trainIdx=93, imgIdx=0, distance=37.0] Good Matchs DMatch [queryIdx=254, trainIdx=174, imgIdx=0, distance=55.0] Good Matchs DMatch [queryIdx=255, trainIdx=91, imgIdx=0, distance=72.0] Good Matchs DMatch [queryIdx=256, trainIdx=81, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=257, trainIdx=92, imgIdx=0, distance=57.0] Good Matchs DMatch [queryIdx=258, trainIdx=212, imgIdx=0, distance=76.0] Good Matchs DMatch [queryIdx=259, trainIdx=119, imgIdx=0, distance=67.0] Good Matchs DMatch [queryIdx=260, trainIdx=228, imgIdx=0, distance=73.0] Good Matchs DMatch [queryIdx=261, trainIdx=119, imgIdx=0, distance=68.0] Good Matchs DMatch [queryIdx=263, trainIdx=266, imgIdx=0, distance=74.0] Good Matchs DMatch [queryIdx=264, trainIdx=319, imgIdx=0, distance=72.0] Good Matchs DMatch [queryIdx=265, trainIdx=157, imgIdx=0, distance=76.0] Good Matchs DMatch [queryIdx=266, trainIdx=365, imgIdx=0, distance=65.0] Good Matchs DMatch [queryIdx=267, trainIdx=341, imgIdx=0, distance=76.0] Good Matchs DMatch [queryIdx=268, trainIdx=303, imgIdx=0, distance=63.0] Good Matchs DMatch [queryIdx=269, trainIdx=313, imgIdx=0, distance=69.0] Good Matchs DMatch [queryIdx=271, trainIdx=350, imgIdx=0, distance=62.0] Good Matchs DMatch [queryIdx=272, trainIdx=313, imgIdx=0, distance=68.0] Good Matchs DMatch [queryIdx=278, trainIdx=267, imgIdx=0, distance=69.0] Good Matchs DMatch [queryIdx=280, trainIdx=223, imgIdx=0, distance=71.0] Good Matchs DMatch [queryIdx=281, trainIdx=267, imgIdx=0, distance=71.0] Good Matchs DMatch [queryIdx=283, trainIdx=334, imgIdx=0, distance=72.0] Good Matchs DMatch [queryIdx=284, trainIdx=313, imgIdx=0, distance=63.0] Good Matchs DMatch [queryIdx=285, trainIdx=78, imgIdx=0, distance=76.0] Good Matchs DMatch [queryIdx=286, trainIdx=312, imgIdx=0, distance=73.0] Good Matchs DMatch [queryIdx=287, trainIdx=271, imgIdx=0, distance=68.0] Good Matchs DMatch [queryIdx=288, trainIdx=170, imgIdx=0, distance=64.0] Good Matchs DMatch [queryIdx=289, trainIdx=278, imgIdx=0, distance=64.0] Good Matchs DMatch [queryIdx=290, trainIdx=282, imgIdx=0, distance=70.0] Good Matchs DMatch [queryIdx=291, trainIdx=91, imgIdx=0, distance=65.0] Good Matchs DMatch [queryIdx=292, trainIdx=334, imgIdx=0, distance=67.0] Good Matchs DMatch [queryIdx=293, trainIdx=80, imgIdx=0, distance=72.0] Good Matchs DMatch [queryIdx=294, trainIdx=92, imgIdx=0, distance=47.0] Good Matchs DMatch [queryIdx=295, trainIdx=301, imgIdx=0, distance=44.0] Good Matchs DMatch [queryIdx=297, trainIdx=220, imgIdx=0, distance=78.0] Good Matchs DMatch [queryIdx=298, trainIdx=374, imgIdx=0, distance=76.0] Good Matchs DMatch [queryIdx=300, trainIdx=329, imgIdx=0, distance=74.0] Good Matchs DMatch [queryIdx=302, trainIdx=285, imgIdx=0, distance=77.0] Good Matchs DMatch [queryIdx=305, trainIdx=271, imgIdx=0, distance=80.0] Good Matchs DMatch [queryIdx=307, trainIdx=350, imgIdx=0, distance=76.0] Good Matchs DMatch [queryIdx=308, trainIdx=320, imgIdx=0, distance=71.0] Good Matchs DMatch [queryIdx=309, trainIdx=163, imgIdx=0, distance=76.0] Good Matchs DMatch [queryIdx=310, trainIdx=170, imgIdx=0, distance=73.0] Good Matchs DMatch [queryIdx=311, trainIdx=357, imgIdx=0, distance=65.0] Good Matchs DMatch [queryIdx=312, trainIdx=320, imgIdx=0, distance=62.0] Good Matchs DMatch [queryIdx=314, trainIdx=342, imgIdx=0, distance=75.0] Good Matchs DMatch [queryIdx=315, trainIdx=162, imgIdx=0, distance=72.0] Good Matchs DMatch [queryIdx=316, trainIdx=239, imgIdx=0, distance=74.0] Good Matchs DMatch [queryIdx=317, trainIdx=171, imgIdx=0, distance=56.0] Good Matchs DMatch [queryIdx=318, trainIdx=244, imgIdx=0, distance=61.0] Good Matchs DMatch [queryIdx=319, trainIdx=369, imgIdx=0, distance=77.0] Good Matchs DMatch [queryIdx=320, trainIdx=346, imgIdx=0, distance=67.0] Good Matchs DMatch [queryIdx=322, trainIdx=158, imgIdx=0, distance=78.0] Good Matchs DMatch [queryIdx=325, trainIdx=92, imgIdx=0, distance=73.0] Good Matchs DMatch [queryIdx=326, trainIdx=236, imgIdx=0, distance=76.0] Good Matchs DMatch [queryIdx=327, trainIdx=162, imgIdx=0, distance=70.0] The number of matches that i get is same for the same image as well as for different images I am really confused ? Can you one explain how to compare two images and tell if they are similar or not using OpenCV
Here is somewhat that i am trying to achieve
-27589943 0 docker and elastic beanstalk container stopped unexpectedly and permission deniedI am trying to extend this docker image which is provisioned with ansible and build successfully on docker hub at least, part of this image includes a user called play which owns a directory called /home/play/Code that has 755 permissions. I am using boot2docker on mac
This is my docker file locally
FROM ir1sh/dockeractivator MAINTAINER Mark Moore EXPOSE 9000 which builds ok and when I run
docker run --rm -it -v "/my/local/dir:/home/play/Code" -p 9000:9000 300b01a6199c the container starts correctly and I get a session with user root starting in /home/play/Code. If I add -u play to that commade I get a session with the play user instead in the same directory.
Now if I push that container to elastic beanstalk with their cli tool I get the following error
Output: [CMD-AppDeploy/AppDeployStage0/AppDeployPreHook/04run.sh] command failed with error code 1: /opt/elasticbeanstalk/hooks/appdeploy/pre/04run.sh b07ae15d619ad90441f6f410a31a7d51885151c92cd8675c5d8e47f63b43dd95 Docker container quit unexpectedly after launch: Docker container quit unexpectedly on Sun Dec 21 13:36:06 UTC 2014:. Check snapshot logs for details..
The logs aren't very enlightening
Now per another suggestion I dont have a CMD or an ENTRYPOINT in my docker file so I add those.
FROM ir1sh/dockeractivator MAINTAINER Mark Moore EXPOSE 9000 ENTRYPOINT ["/home/play/Code", "-DFOREGROUND"] CMD [] The image builds but now when I try docker run with the same options as above I get
exec: "/home/play/Code": permission denied2014/12/21 13:34:33 Error response from daemon: Cannot start container 2703462a68a32e8d774e9b4d8cbc3c809e79f53bb1d08f0398b45436d07546a3: exec: "/home/play/Code": permission denied
This happens whether I try to start the session as root or as play. I get the same error if I push this dockerfile to elastic beanstalk so its not related to boot2docker Any idea what my permission problem is here? I have tried changing that directories permission to 777 to no avail
edit1: running as privileged also does not help
edit2: changing the dockerfile to
FROM ir1sh/dockeractivator MAINTAINER Mark Moore EXPOSE 9000 CMD ["bash"] Allows me to run the container locally but afterpushing to elastic beanstalk I get the container quit unexpectedly error again
-7626779 0netstat -a -o prints it. I suppose they are on the same machine becase you are listening on 127.0.0.1.
-14387562 0As is often the case for maintaining the state of a table view cell, the right answer is to keep the state in your model. In other words, if tempArray is your model containing a collection of objects that describe the table's contents, add a BOOL attribute to those objects meaning something like userAdded.
Then your "cell was inserted" pseudo-code can become:
MyModelClass *modelElement = [tempArray objectAtIndex:indexPath.row]; if (modelElement.userAdded) { cell.mylabel.textColor = [UIColor redColor]; } else { cell.mylabel.textColor = [UIColor blackColor]; }
-4895049 0 I'm assuming the solution you're mentioning in the comment is something like this:
Start at the left or right (so index = 0), and scan which bits are set (upto 100 operations). Name that set x. Also set a variable block=0.
At index=1, repeat and store to set y. If x XOR y = 0, both are identical sets, so move on to index=2. If it x XOR y = z != 0, then range [block, index) is contiguous. Now set x = y, block = index, and continue.
If you have 100 bit-arrays of length 22 each, this takes something on the order of 2200 operations.
This is an optimum solution because the operation cannot be reduced further -- at each stage, your range is broken if another set doesn't match your set, so to check if the range is broken you must check all 100 bits.
-40844610 0 Represent Runner competitors using Java multithreadingI need to represent 10 runner who run on a 100 meter track , and display the winner ( who finishes the track first ) and the time he took to finish the track . I am beginner so I got multiple error in order to achieve this.
-26288956 0 Regx + Java : split a text into words and removing punctuation only if they are alone or at the endI am trying to split a string into words but I want to keep, "a.b.c" as a word, and remove the punctuation only if it is alone or at the end of a word e.g.
"a.b.c" --> "a.b.c" "a.b." --> "a.b" e.g
String str1 = "abc a.b a. . b, , test"; should return "abc","a.b","a","b","test"
-40867029 0 How to remove defalult text when using RAF eg(Ad 1 of 1) I am working on RAF(Roku Advertising Framework) using bright script.
On above image we seeing (Ad 1 of 1) when playing ads. Please give me suggestions to solve this issue, Any help much appreciated.
You have to define a JUnit task in your ant script.
<junit> <test name="my.test.TestCase"/> </junit> See JUnit Task for documentation.
-16246009 0 One to one OPTIONAL relationshipTraditional EF questions starts with: My models are
public class Ingredient { public int IngredientID { get; set; } public virtual RequestedIngredient RequestedIngredient { get; set; } // other stuff } public class RequestedIngredient { [Key] string BlahBlahBlah { get; set; } public int? IngredientID { get; set; } public virtual Ingredient Ingredient { get; set; } } Somewhere in dbContext...
modelBuilder.Entity<Ingredient>() .HasOptional<RequestedIngredient>(e => e.RequestedIngredient) .WithOptionalPrincipal(e => e.Ingredient) .Map(e => e.MapKey("IngredientID")) .WillCascadeOnDelete(false); But I get Schema specified is not valid. Errors: (195,6) : error 0019: Each property name in a type must be unique. Property name 'IngredientID' was already defined.
If I remove IngredientID from RequestedIngredient, the db will be created just as I want to. But I have no access to IngredientID. How can I set this up to have access to foreign key?
-11369249 0You cannot directly tell it to call the super method. target is only a pointer to an object, super does not have a separate pointer address from your self instance.
Also by assigning the target to self.superclass you are telling the target to be the class. Therefore your trying call a class method rather than an instance method which is not what you want to do.
The only way to do this would be to assign target to self and have a separate method such as:
- (void)callSuperMethod { [super playNarrationForPage:[NSNumber numberWithInt:1]]; }
-37905075 0 What is it that requires the environment variable be set?
I would try to use a different approach if possible. If you are expecting to act on the environment variable in ansible, you could instead set the value in an inventory group_vars file which would only be in effect for local provisioning vagrant. Other environments could use different values for the same variable by updating the appropriate inventory group_vars file.
-2753572 0If I don't need a copy of the original value, I don't declare a new variable.
IMO I don't think mutating the parameter values is a bad practice in general,
it depends on how you're going to use it in your code.
I am fetching data from the indexed database in HTML 5, I am able to successfully get the values but I want it to bind it to some data-grid view of ASP.NET
The code which I am using to get the values from the indexed database is
if(currentDatabase) { var objectStore = currentDatabase.transaction([objStore]).objectStore(objStore); var traveller = []; objectStore.openCursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var v = cursor.value; traveller.push("id ="+v.id); traveller.push("Name ="+v.traveler); traveller.push("Destination ="+v.destination); traveller.push("Transportation ="+v.transportation); cursor.continue(); } this allows me to store the data in the array, how can I bind it to datagrid view,
-21218932 0"Auto-increment" is always a problem when working with a distributed system, as it creates a bottle-neck: Each new increment needs to read the previous data .. like some other parallel requests.
Generally speaking, "auto-increment" restricts parallelism, specially on distributed systems.
-19018984 0Just create one view for that and use <include ... /> to include that view to your Activity's layout. In each Activity you have to modify it independently.
Sharekit provides a generic sharing mechanism but also exposes individual services. For instance, if you were to share a URL on twitter, you could write the following code:
#import "ShareKit/Core/SHK.h" #import "ShareKit/Sharers/Services/Twitter/SHKTwitter.h" ... SHKItem *item = [SHKItem URL:url title:@"A title"]; [SHKTwitter shareItem:item]; This is all explained in the documentation, but don't fear exploring the header files of the individual services.
-23180307 0 How I can access to a returned data of a function with use the reflect package?I have a function of the IndexController type:
func (this IndexController) ActionIndex() map[string]string { return map[string]string{"Name": "Hello from the actionIndex()!"} } It is used so:
routerInstance := router.Constructor(request) controllerObject := controllers[routerInstance.GetRequestController(true)] outputData := reflect.ValueOf(controllerObject).MethodByName(routerInstance.GetRequestAction(true)).Call([]reflect.Value{}) fmt.Println(outputData) Now for example, how to show the Name element of outputData? I try to print so:
fmt.Println(outputData["Name"]) But program will exit with error:
# command-line-arguments ./server.go:28: non-integer array index "Name" I will be thankful!
-7018489 0 How can I send a REST XML POST request via curl?Basically, I have a project set up in Restlet which uses JAXRS for mapping resources to paths and uses JAXB for serializing and deserializing XML to/from Java types. I'm currently trying to send a POST request in order to test whether it works, and I'm running into a bit of trouble. Here's my resource:
@Path("stream") public class StreamResource { @POST @Consumes("text/xml") @Produces("text/xml") public Stream save(Stream value) { logger.debug("saving new stream..."); return (Stream)this.streamPersistence.save(value); } } Here's my Stream class:
@XmlRootElement(name="stream") @XmlType(propOrder={"id", "streamName", "title", "description", fileSystemPath"}) public class Stream { private Long id; private String streamName; private String fileSystemPath; private String title; private String description; // getters/setters omitted for brevity } And here's how I'm invoking curl:
curl -X POST -d '<stream><streamName>helloWorld.flv</streamName><title>Amazing Stuff, Dude!</title><description>This stream is awesome-cool.</description><fileSystemPath>/home/rfkrocktk/Desktop/helloWorld.flv</fileSystemPath></stream>' --header 'Content-Type:"text/xml"' http://localhost:8888/stream Here's the error I'm getting from curl:
The given resource variant is not supported. ...and here's the error in Restlet:
15:02:25.809 [Restlet-961410881] WARN org.restlet.Component.Server - Error while parsing entity headers java.lang.IllegalArgumentException: Illegal token: "text at org.restlet.data.MediaType.normalizeToken(MediaType.java:647) at org.restlet.data.MediaType.normalizeType(MediaType.java:686) at org.restlet.data.MediaType.<init>(MediaType.java:795) at org.restlet.data.MediaType.<init>(MediaType.java:767) at org.restlet.engine.http.header.ContentTypeReader.createContentType(ContentTypeReader.java:84) at org.restlet.engine.http.header.ContentTypeReader.readValue(ContentTypeReader.java:112) at org.restlet.engine.http.header.ContentType.<init>(ContentType.java:99) at org.restlet.engine.http.header.HeaderUtils.extractEntityHeaders(HeaderUtils.java:664) at org.restlet.engine.http.connector.Connection.createInboundEntity(Connection.java:313) at org.restlet.engine.http.connector.ServerConnection.createRequest(ServerConnection.java:136) at org.restlet.engine.http.connector.ServerConnection.readMessage(ServerConnection.java:229) at org.restlet.engine.http.connector.Connection.readMessages(Connection.java:673) at org.restlet.engine.http.connector.Controller$2.run(Controller.java:95) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) at java.lang.Thread.run(Thread.java:679) What am I doing wrong here? This seems pretty straightforward, right?
-22954616 0 Android app is not running on device[2014-04-09 11:50:19 - Dex Loader] Unable to execute dex: java.nio.BufferOverflowException. Check the Eclipse log for stack trace. [2014-04-09 11:50:19 - audiomediaplayer1] Conversion to Dalvik format failed: Unable to execute dex: java.nio.BufferOverflowException. Check the Eclipse log for stack trace.
-5093337 0 jqGrid clientArray I am trying to use jqGrid clientArray to submit multiple updates at once. (I am trying to update multiple rows in one go).
onSelectRow: function(id){ if (id && id !== lastsel) { jQuery('#fnlusetaxlistings').saveRow(lastsel, true, 'clientArray'); jQuery('#fnlusetaxlistings').editRow(id, true, null, null); lastsel = id; } }, This works fine, but I have no idea that how to retrieve clientArray and send it to the server? If anyone can post an example of sending clientArray to server, it will be very helpful.
Thanks, Ashish
-5151363 0 creating multiple users for a c#.net winform application using sql server expressi have a single sql database in sql server express.
i have a login MAINLOGIN, for this database.
i want insertion of data in this database through multiple users, U1,U2,U3, each having different userids & passwords.
These users would be created by MAINLOGIN , manually or via the winform application.
So while creating MAINLOGIN , i would give him permission to further create logins.
For this what should i do?
i cannot create MULTIPLE users, because for one database, only one user can be created under one login.
so should i create multiple logins, L1,L2,L3, then map, U1, U2, U3 to them.
Or, is there a better way to do this? like application roles etc.
i dont want to use windows authentication. because if i know the system password, then i could simply connect sql via the application and insert wrong data.
-10081738 1 How to convert '[' to '[' use pythonI use this :
title=title.replace(u'【',u'[').replace(u'】',u'[') But Error:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 0: ordinal not in range(128)
-34746293 0 How to set InstanceContextMode through Custom Behavior implementing IServiceBehavior Is there a way to set the InstanceContextMode through a custom service behavior implementing IServiceBehavior --> ApplyDispatchBehavior
-9936812 0 Is there a maximum to the number of elements in std::bitset?Is there a maximum to the number of elements in an std::bitset?
In my code (VC++2010) 1<<20 crashes with a stack overflow, but 1<<19 works.
(I'm dealing with huge inputs.)
-30677861 0 Using Html.TextBox with custom property in mvc5if we have the below code,
<input id="Name" name="Name" type="text" data-bind="value: Name" class="title width-7" /> we can translate it using @Html.TextBoxFor to:
@Html.TextBoxFor(m => m.Name, new { data_bind="value: Name", @class = "title width-7" }) now I have this line that i can't translate the 'placeholder' attribute with @Html.TextBoxFor, how can I do that??
<input type="email" class="form-control" id="exampleInputEmail3" placeholder="Enter email"> thanks...
-10857964 0Others have given you the probability calculation, but I think you may be asking the wrong question.
I assume the reason you're asking about the probability of the priorities being unique, and the reason for choosing n^3 in the first place, is because you're hoping they will be unique, and choosing a large range relative to n seems to be a reasonable way of achieving uniqueness.
It is much easier to ensure that the values are unique. Simply populate the array of priorities with the numbers 1 .. n and then shuffle them with the Fisher-Yates algorithm (aka algorithm P from The Art of Computer Programming, volume 2, Seminumerical Algorithms, by Donald Knuth).
The sort would then be carried out with known unique priority values.
(There are also other ways of going about getting a random permutation. It is possible to generate the nth lexicographic permutation of a sequence using factoradic numbers (or, the factorial number system), and so generate the permutation for a randomly chosen value in [1 .. n!].)
-10551178 0You've in the preprocessing servlet already set the queryResult in the request scope.
request.setAttribute("queryResult",result); So you do not need to use <jsp:useBean> at all. Remove the following line altogether:
<jsp:useBean id="queryResult" class="uges.servlets.MyQuery" scope="request"/> Because your servlet has set it as a request attribute, the object is already in EL available by ${queryResult}. But due to the strange design of the class itself, it's hard to properly access it in EL, so you'll ineed need to resort to old school scriptlets. You only need to obtain it first by request.getAttribute("queryResult").
For a better design approach, check the servlets tag wiki page and JSP using MVC and JDBC.
-18845096 0Making some assumptions and, asserting that joining on the millisecond is nonsensical, fiddle here.
CREATE TABLE Withdrawl ( Timestamp TIMESTAMP PRIMARY KEY, Amount Decimal(60, 4) ); CREATE TABLE Deposit ( Timestamp TIMESTAMP PRIMARY KEY, Amount Decimal(60, 4) ); SELECT Timestamp, -Amount FROM Withdrawl UNION ALL SELECT Timestamp, Amount FROM Deposit ORDER BY Timestamp ASC; how about this,
SELECT Timestamp, Amount, NULL FROM Withdrawl UNION ALL SELECT Timestamp `time stamp`, NULL `amount withdrawal`, Amount `amount deposits` FROM Deposit ORDER BY Timestamp ASC;
-27409557 0 Your math problem is right here:
writeStream.Write(buffer, 0, bytesRead); bytesRead = responseStream.Read(buffer, 0, Length); var progress = bytesRead * 100.0 / writeStream.Length; bw.ReportProgress((int)progress,SummaryText); The return value from responseStream.Read is the number of bytes you read in that one read. It's not the total number of bytes read since you started reading from the file.
Also, dividing the number of bytes read by the total number written (i.e. writeStream.Length) isn't telling you anything useful.
If you want to update a progress bar, you have to know how many total bytes there are in the file, and how many total bytes you've read up to this point. So if the file is 1,000,000 bytes long, and you've read 450,000 bytes total, the progress would be 45% (i.e. 450000/1000000).
In your code, you have to get the file size from the FTP server. That's the total number of bytes you're going to download. Then you need keep track of how many bytes you've read up to this point. The basic idea is:
int totalBytesToBeRead = ??; // somehow get length. responseStream.Length doesn't work. int totalBytesRead = 0; int bytesRead = -1; while (bytesRead != 0) { bytesRead = responseStream.Read(...); // now add to the total totalBytesRead += bytesRead; var progress = totalBytesRead * 100.0 / totalBytesToRead; } The problem appears to be that FtpWebRequest doesn't supply a ContentLength, so you need some other way to get the length. The only thing that comes to mind is to request the length up front by doing a separate FtpWebRequest with the GetFileSize method. See Get File Size On An FTP in C# for an example.
Am i able to use a copy constructor with the new keyword? My code also shows the 2 obj pointers have the same memory address?
#include <iostream> using namespace std; class Person{ public: int age; Person() { } Person(const Person& p ) : age(p.age) { } }; int main() { Person *p = new Person(); p->age = 15; Person *y = p; // Person *z = new Person(p); why no work??? // p and y have the same memory addres?? std::cout << p; std::cout << y; return 0; }
-38509599 0 You probably want to use a SpannableString for this, which allows individual parts of a string to be rendered differently in a TextView.
Like so:
SpannableString str = new SpannableString("Highlighted. Not highlighted."); str.setSpan(new BackgroundColorSpan(Color.YELLOW), 0, 11, 0); textView.setText(str);
-14752765 0 What I surmise according to your question...
CREATE TABLE PEOPLE(ID INTEGER,PERSON VARCHAR(20),USERID INTEGER); CREATE TABLE TASKS(ID INTEGER,TASK VARCHAR(20),USERID INTEGER); CREATE TABLE TASKPERSON(ID INTEGER,PERSONID INTEGER,TASKID INTEGER);
INSERT INTO PEOPLE VALUES(1,"RAHUL",1); INSERT INTO TASKS VALUES(1,NULL,1); INSERT INTO TASKPERSON VALUES(1,1,NULL);
INSERT INTO PEOPLE VALUES(1,"RAUNAK",1); INSERT INTO TASKS VALUES(1,"R",1); INSERT INTO TASKPERSON VALUES(1,1,33);
INSERT INTO PEOPLE VALUES(2,"PARTH",2); INSERT INTO TASKS VALUES(2,"P",2); INSERT INTO TASKPERSON VALUES(2,2,22);
INSERT INTO PEOPLE VALUES(3,"KANISHK",3); INSERT INTO TASKS VALUES(3,"K",3); INSERT INTO TASKPERSON VALUES(3,3,33);
INSERT INTO PEOPLE VALUES(4,"HEENA",4); INSERT INTO TASKS VALUES(4,NULL,4); INSERT INTO TASKPERSON VALUES(4,4,NULL);
When not including "NOT IN", you will retrieve the list of those people who are not allocated.
SELECT P.*,P.ID FROM PEOPLE P LEFT JOIN TASKPERSON TP ON P.ID=TP.PERSONID WHERE P.USERID=1 AND TP.PERSONID IN(SELECT TP.PERSONID FROM TASKPERSON TP WHERE TP.PERSONID=1 AND TP.TASKID=33) GROUP BY P.ID
-2808430 0 HTMLEntities seems to work but you have an encoding problem. The terminal you're printing on is probably set up for a latin charset and barfs on the utf-8 characters output by your script.
In what environment are you running ruby ?
The reason '&' displays correctly is that it's an ascii character and thus will display the same in most encodings.The problem is that it's not supposed to happen alone in an xml document and could pose problems later when you feed your decoded file to hpricot. I believe the proper way would be to parse with hpricot and then pass what you're extracting from the document to HTMLEntity.
-6185136 0The two clauses: NewCount is Count + 1 and increment(NewCount,Count) basically have the same meaning. You didn't make clear that Count is an input variable and it has a base case of 1, so Prolog didn't know where to start unifying values for it. For example, you should use Count as an input argument as follows (it doesn't change much if compared with your version):
order([],[], _). order([Head|Tail],[(Count,Head)|NewTail], Count):- NewCount is Count + 1, order(Tail, NewTail, NewCount). order(List, Result ):- order(List, Result, 1).
-10423256 0 There are several ways to achieve this. You can track pitch (lower pitch values will be male, otherwise female). Or try to build a GMM (Sphinx cannot do this, but HTK can), with one model for male, other for female and another to children.
-10874316 0I would suggest to read the following article about SSL sockets in Erang that contains complete code of the SSL echo server and client.
Erlang SSL sockets example - ssl server & client)
-25727282 0Another option is placing an error container outside of your form group ahead of time. The validator will then use it if necessary.
<div class="form-group"> <label class="control-label" for="new-task-due-date">When is the task due?</label> <div class="input-group date datepicker"> <input type="text" id="new-task-due-date" class="required form-control date" name="dueDate" /> <span class="input-group-addon"> <span class="glyphicon glyphicon-calendar"></span> </span> </div> <label for="new-task-due-date" class="has-error control-label" style="display: none;"></label> </div>
-12277340 0 I've tried to produce a "simpler" query that works and so far nothing.
If I stick with your basic structure I can offer a slight improvement. Try this:
public static IObservable<T> FirstOrLastAsync<T>( this IObservable<T> source, Func<T, bool> pred) { return Observable.Create<T>(o => { var hot = source.Publish(); var store = new AsyncSubject<T>(); var d1 = hot.Subscribe(store); var d2 = hot .Where(x => pred(x)) .Concat(store) .Take(1) .Subscribe(o); var d3 = hot.Connect(); return new CompositeDisposable(d1, d2, d3); }); } It's not hugely better, but I like it better than using Amb. It's just a tad cleaner I think.
so is it possible to get the view object of a android default screen?
No. That app runs in another process. Its objects cannot magically transport themselves to your process.
i want to know how can i get content of device default screen content from my application
On Android 5.0+, with user permission, you can use the media projection APIs to take screenshots.
-38328767 0 Access Query Hangs w/ Where instead of Join on Memo fieldAccess 2013
UPDATE [1 Clean Reasons], Data, [Final Crosswalk] SET [Final Crosswalk].CR_ID = [1 Clean Reasons].[CR_ID] WHERE (((Data.Reason)=[1 Clean Reasons].[Reason])); I'm trying to build a record ID crosswalk table, "Final Crosswalk", I need to join Data.Reason = 1 Clean Reasons.Reason, but it's a memo field - thus the Where statement.
I can view this query, but I can't get it to export or update. I'm assuming it's an issue with the resource requirements of the Where statement (the table has ~1M records).
-3105308 0A while back someone posted an mpl::string to the boost groups. I think it may actually have gotten into the library. If that is the case you could implement something like this by providing your template string as a template parameter (an mpl::string) and then using some pretty profound meta-programming skills to parse the formatting bits in it. Then you'd use this information to chose an implementation that has the appropriate argument count and types.
No, I'm not going to do it for you :P It would be quite difficult. However, I do believe it would be possible.
-23471177 0Generally speaking, final would be more appropriate.
The important thing about modifiers is that the alter the reference, not the object referenced. e.g.
final int[] a = { 0 }; a[0] = 5; // ok, not final a = b; // not ok as it is final similarly
volatile int[] a = { 0 }; a[0] = 5; // not a volatile write a = b; // volatile write.
-30504174 0 Now, I access with the client and it shows the old data, I mean the database without the new row. Even if I 'update' a field in the admin, I won't see that 'update' with the client app.
The only thing that could cause this is if you don't COMMIT.
You must commit after DML changes to make sure the changes are permanent.
INSERT INTO sae_scenario_type ( id, name, description, locked ) VALUES ( SEQ_SAE_SCENARIO_TYPE.nextVAL, 'Direct_SQL_Insertion_1', 'Direct SQL Insertion from RfoAdmin 1', 'N' ); COMMIT; --> you are missing this From documentation,
-11774763 0COMMIT
Purpose
Use the COMMIT statement to end your current transaction and make permanent all changes performed in the transaction. A transaction is a sequence of SQL statements that Oracle Database treats as a single unit. This statement also erases all savepoints in the transaction and releases transaction locks.
You have to use .filter [docs]:
$('img').filter(function() { return this.src === $(this).attr('rel'); }); Note that rel is not a valid attribute for img elements. Therefore you might want to use data-* attributes to store the additional information.
Additional note: this.src will return the absolute URL, even if the src attribute contains a relative URL. If you want to get the actual value of the attribute, you have to use $(this).attr('src').
Applications to not get restore state functionality magically but they support APIs that help doing it. Some applications do it well, others less well and others not at all.
In practice, for the applications that support it, it works quite reliably, provided the logout went cleanly and you've not out of diskspace or something similar fatal.
-32195933 0You may consider changing your approach, especially if you are doing a lot of GUI updates from your background threads. Reasons:
What I prefer is to do polling the background thread data instead. Set up GUI timer for say 300ms, then check if there is any data ready to be updated, then do quick update with proper locking.
Here is code example:
private string text = ""; private object lockObject = new object(); private void MyThread() { while (true) { lock (lockObject) { // That can be any code that calculates text variable, // I'm using DateTime for demonstration: text = DateTime.Now.ToString(); } } } private void timer_Tick(object sender, EventArgs e) { lock(lockObject) { label.Text = text; } } Note, that while the text variable is updated very frequently the GUI still stays responsive. If, instead, you update GUI on each "text" change, your system will freeze.
-39122911 0you can also check status of response you are getting after hitting the API , like, means there is some problem in API
if(status!=200){
// do something
}
-2826213 0In the foreach loop, you already know that node is a /a/b in the original document - so to get just its c children simply use a relative xpath:
node.SelectNodes("c")
-26268269 0 Insertion sort while removing duplicates in C++ I am having trouble with my insertion sort method. It loops over an array of elements of a custom struct that holds the word and the number of occurrences. The array length is fixed at 1000. The sort removes duplicates. It think the problem is in the swap when a duplcate is found but I am using the same function for the sorting swap. I have played with it for a while and I just can seem to get it to work.
My program outputs the entire list, using length variable and outputs the following:
word occurences hello 500 hello 500 I know that the array holds 1000 elements of the word hello, so this output if confusing me.
void sortAndRemoveDuplicates(Word WordArray [],int &length){ /* Description: Sort the word array, removing duplicates */ for(int index=0;index<length-1;index++){ int idxMin=index; for(int idx=index;idx<length;idx++){ if(WordArray[idx].word<WordArray[idxMin].word){ idxMin=idx; } } // if duplicate if(WordArray[idxMin].word==WordArray[index-1].word){ WordArray[index-1].wordCount++; swap(WordArray[idxMin],WordArray[index]); length--; index--; } if(idxMin!=index){ swap(WordArray[idxMin],WordArray[index]); } } }; void swap(Word &x, Word &y){ /* Description: Swap two words */ Word temp; temp=x; x=y; y=temp; }; void printResults (string &filename, int &charCount, int &lineCount, int wordCount, Word WordArray[],int &length){ /* Description: Print the results of the program to cout */ cout<<"\tResults\n"; cout<<"Filename: "<<filename<<"\n"; cout<<"Character Count: "<<charCount<<"\n"; cout<<"Line Count: "<<lineCount<<"\n"; cout<<"Word Count:"<<wordCount<<"\n"; cout<<"\tWord\tCount\n"; int i=0; while(i<(length)){ cout<<"\t"; cout<<WordArray[i].word<<"\t"<<WordArray[i].wordCount<<"\n"; i++; } }; Thanks
-20036644 1 Python 3: check if the entire list is inside another listLet's say I have 2 lists:
a = [6,7,8,9,10]
b = [1,3,4,6,7,8,9,10]
I have a function that is used to find out if list a can be found in list b. If it is found, then it returns True. In my case it should return True because list a can be found at the end of list b. List a never changes and always contains the same numbers, whereas list b accepts numbers from the user and then uses sorted() method to sort numbers in ascending order. I should also add that the order does matter.
I have searched around and could find a subset method, which looks like this: set(a).issubset(set(b))) as well as using in method. Both of them did not work for me.
UPDATE: Using set(a).issubset(set(b))) for some reason always returns True. For example, if a = [1,1] and b = [0,1,2,3,4,5] then using subset method returns True, even though 1,1 cannot be found in b. I'm not looking if 1 is inside the list, I'm looking if 1,1 is inside the list.
Using in method when
a = [6,7,8,9,10]
b = [1,3,4,6,7,8,9,10] returns False.
Parsing XML with python using xml.sax, but my code fails to catch Entities. Why doesn't skippedEntity() or resolveEntity() report in the following:
import os import cStringIO import xml.sax from xml.sax.handler import ContentHandler,EntityResolver,DTDHandler #Class to parse and run test XML files class TestHandler(ContentHandler,EntityResolver,DTDHandler): #SAX handler - Entity resolver def resolveEntity(self,publicID,systemID): print "TestHandler.resolveEntity: %s %s" % (publicID,systemID) def skippedEntity(self, name): print "TestHandler.skippedEntity: %s" % (name) def unparsedEntityDecl(self,publicID,systemID,ndata): print "TestHandler.unparsedEntityDecl: %s %s" % (publicID,systemID) def startElement(self,name,attrs): # name = string.lower(name) summary = '' + attrs.get('summary','') arg = '' + attrs.get('arg','') print 'TestHandler.startElement(), %s : %s (%s)' % (name,summary,arg) def run(xml_string): try: parser = xml.sax.make_parser() stream = cStringIO.StringIO(xml_string) curHandler = TestHandler() parser.setContentHandler(curHandler) parser.setDTDHandler( curHandler ) parser.setEntityResolver( curHandler ) parser.parse(stream) stream.close() except (xml.sax.SAXParseException), e: print "*** PARSER error: %s" % e; def main(): try: XML = "<!DOCTYPE page[ <!ENTITY num 'foo'> ]><test summary='step: #'>Entity: ¬</test>" run(XML) except Exception, e: print 'FATAL ERROR: %s' % (str(e)) if __name__== '__main__': main() When run, all I see is:
TestHandler.startElement(), step: foo () *** PARSER error: <unknown>:1:36: undefined entity Why don't I see the resolveEntity print for # or the skipped entry print for ¬?
-18784452 0Keep a counter using long, take the modulus, you don't have to worry about overflow as it will increase by 60 per second and your code needs to run for 292471208678 years before overflow.
long alphacntr = 0; .... public void update(){ alphacntr += 3; int alpha = alphacntr%256; .... }
-11823032 0 Javascript onclick even on a div not working I have a div and when a user clicks on it using the onclick event, i'm calling a function:
function test(a) { alert(a); } <div onclick="javascript:test('zaswde');">sdfasdasdadasdasds</div> Update
<ul> <li> <div> <div onclick="javascript:alert('v'); "></div> </div> <div ></div> </li> </ul> Can't i use onclick on the div element?
I was missing the Accept Header. Now it is working fine.
-13790050 0There is also a new control bus component in camel 2.11 which could do what you want (source)
template.sendBody("controlbus:route?routeId=foo&action=stop", null);
-7894221 0 How to log into git bitbucket repository from jenkins I have a GIT repository on bitbucket, which I want my Jenkins Server to access automatically. This is only possible using public/private key authentication. So I created a key pair and uploaded the public key to bitbucket. The public and the private key are on my server in the .ssh folder of the tomcat user running jenkins. I am able to clone my project when I am logged in as that user on the server.
However I am unable to get jenkins to actually check out the code from bitbucket. It always says:
Permission denied (publickey). fatal: The remote end hung up unexpectedly Well I assume that this happens because when accessing the repository over ssh I need to provide the passphrase for my private key and jenkins is unable to do this automatically. I read that it is possible to avoid beeing asked for the passphrase by providing a config file inside the .ssh folder containing the following content:
Host bitbucket.org IdentityFile ~/.ssh/id_dsa I did so, but as soon as I provide that file I can no longer clone the repository from bitbucket. Not even directly from the server, getting the same error message as shown above.
Did anyone manage to make this setup work? I also read the following thread here on stackoverflow that was of no use to me: How do i set a private ssh key for hudson / jenkins to access bitbucket? and I checked that tomcat really runs under user tomcat6 by creating an empty test project that simply runs "whoami". So I am pretty much out of ideas for fixing the problem.
-13927364 0 WPF textbox with imageI'm doing a WPF login interface. In my login panel, I have one login TextBox and a PasswordBox. As what shown in the first image below, there is a little human logo in the login textbox and a lock in the password box. I set the image into the textbox background, and then when i try to insert some word into the login box, the words will overide the human logo(image B). Any advice to make it right?
My XAML:
<TextBox Width="380" Height="25" HorizontalAlignment="Center" Foreground="WhiteSmoke" BorderBrush="Transparent" > <TextBox.Background> <ImageBrush ImageSource="/icon/user_login.png" AlignmentX="Left" Stretch="None"></ImageBrush> </TextBox.Background> </TextBox> Image A:

Image B:

FYI for anyone else that stumbles on this:
We ended up taking a different direction. It seems that iPad/Safari get to choose what happens to your PDF. We ended up taking the route of minimizing links in PDFs instead. The closest we got to an actual solution was hacks that some PDF readers use to change the protocol: eg ghttp:// for url that opens in GoodReader. Did not find this to be an acceptable approach.
-9966782 0No, there is no way to access anonymous classes from anywhere, except from inside them (i.e. otherwise than by this reference). Or by an explicitly declared variable.
final Runnable r1 = new Runnable() {...}; Runnable r2 = new Runnable() { public void run() { synchronized(r1) {...} } };
-20802422 0 Parallel Issue: Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on I have this simple code:
Parallel.Invoke( () => picturebox_1.Refresh(), () => picturebox_2.Refresh()); and I'm getting this:
Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on.
How can I resolve this issue? I just want to run the refresh in parallel, the refresh method runs the Paint Event which has code to render an image...
Thanks!
-27659445 0You have misspelled method-signature:
<cc:attribute name="goToLastPage" method-signtature="java.lang.String action()" required="true"/>
-38498956 0 Try running Windows Update which will installing/fix any missing files
VS2015 Prerequisites failed to install
-30818251 0 using -sort in linuxI want to sort the input of the user with sort in a case (and function). But I never used this before. Do I have to use an array or something?
For example the user does:
bash test.sh 50 20 35 50 Normally in my script this would happen:
ping c -1 "192.168.0.$i" That results in
192.168.0.50 192.168.0.20 192.168.0.35 192.168.0.50 Now I want that the last numbers are sorted and also pinged from smallest to the biggest number like this: 20 35 50 and also that if you have 2 times the same number, the script only pings that number one time.
SortNumbers(){ } ... case -sort ) SortNumbers;; esac
-13417057 0 $('select').change(function(){ var sum = 0; $('select :selected').each(function() { sum += Number($(this).val()); }); $("#sum").html(sum); });
-24749150 0 iOs 8, start playing sound when in the background, alarm clock app I know there are many questions on SOF, but this is the "newest" one. The thing is, I'm trying to create and alarm app, and I know for a fact that there are alarm apps out there that works perfectly ( somehow ), even if the app is not running and is in the background.
My question is: how do you start playing sound after your app is already in the background ??
UILocalNotification is great, but you'll only get application:(_:didReceiveLocalNotification:) after the user has already clicked on your notification, so playing sound using AVAudioPlayer didn't work, i want to play sound regardless weather the user clicks on it or doesn't. Of course with Required background modes: App plays audio or streams audio/video using AirPlay in info.plist already set. Once the music starts playing, it keeps playing even if i go to the background.
I don't want to use UILocalNotificaation sound coz it's limited to 30 secs and only the able to play the sounds that are bundled with the application.
Any insights ? thoughts ??
Sample code:
var notif = UILocalNotification() notif.fireDate = self.datePicker.date notif.alertBody = "test" UIApplication.sharedApplication().scheduleLocalNotification(notif) the above code gets called when the user selects and alarm and clicks save.
and here's what's happening in AppDelegate:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { NSLog("launched") application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert | UIUserNotificationType.Badge, categories: nil )) AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil) AVAudioSession.sharedInstance().setActive(true, error: nil) self.sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("sound", ofType: "caf")) self.audioPlayer = AVAudioPlayer(contentsOfURL: sound, error: nil) return true } func application(application: UIApplication!, didReceiveLocalNotification notification: UILocalNotification!){ audioPlayer.play() NSLog("received local notif") } You need to hold a strong reference to the AVAudioPlayer btw, so it won't get released, and the audioplayer.play() won't do anything...
A trie (or prefix tree) sounds right up your alley. It can do the search on a prefix string of length m in O(m) I believe.
-19200839 0I solved my problem by creating a compound border attribute every time I set the border color, like this:
change: function(hex) { //console.log(hex + ' - ' + opacity); var curObj = window.curObj; var inner = '#' + $(curObj).attr("id") + ' .object_inner'; $(inner).css('border-color', hex); //hack for chrome to get around htmlpurifier bug dropping border-color defined in rgb on IMG tags. var border_all = $(inner).css('border'); if (border_all == '') { //ff returns empty string so we'll have to uild our own compound object var width = $(inner).css('border-top-width'); var color = $(inner).css('border-top-color'); $(inner).css('border','solid '+width+' ' + color); } else { //but for chrome it is enough to pull the compound out, then set it hard. The browser does the work. $(inner).css('border',border_all); } }
-21879741 0 I think you're working with windows form...
And I think the problem is that you want the listbox to be populated with the first item of the combobox when you load for the first time the winform
So, in the form_load event you should select the index in the combobox
private void EmployeeAttendence_Load(object sender, EventArgs e) { try { table = dbOperation.select("employs.emp_id, employs.emp_name, employs.emp_fname, designation.name from employs inner join designation on designation.id = employs.designation"); listView1.Items.Clear(); foreach (DataRow row in table.Rows) { listView1.Items.Add(row[0].ToString()); listView1.Items[listView1.Items.Count - 1].SubItems.Add(row[1].ToString()); listView1.Items[listView1.Items.Count - 1].SubItems.Add(row[2].ToString()); listView1.Items[listView1.Items.Count - 1].SubItems.Add(row[3].ToString()); listView1.Items[listView1.Items.Count - 1].SubItems.Add("P"); } table = dbOperation.select("* from designation"); comboBox1.Items.Clear(); comboBox1.DataSource = table; comboBox1.DisplayMember = "name"; comboBox1.ValueMember = "id"; comboBox1.SelectedIndex = 0; //this should raise the event comboBox1_SelectedIndexChanged(object sender, EventArgs e) and the listbox will be populated } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
-40781618 0 A questions about angular2 route Here is the official example of angular-router. https://angular.io/docs/ts/latest/guide/router.html#!#browser-url-styles https://angular.io/resources/live-examples/router/ts/plnkr.html
If I have requirements like this:When user did not log in,He can not see the top bar(menu list in the second row of the picture should be hidden),only after he logged in,the top bar is visible,I thought a lot about this but can not find the solution.I dont know how to use canActive hook to control it,anyone has an idea please tell me,thank u.
import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: ` <h1 class="title">Angular Router</h1> <nav> <a routerLink="/crisis-center" routerLinkActive="active">Crisis Center</a> <a routerLink="/heroes" routerLinkActive="active">Heroes</a> <a routerLink="/admin" routerLinkActive="active">Admin</a> <a routerLink="/login" routerLinkActive="active">Login</a> </nav> <router-outlet></router-outlet> ` }) export class AppComponent { } Let me be more clear about my question.When user loading page of structure like this.Where should I get and record the login status to achieve my goal,from route or somewhere else?
-11603549 0 AvalonEdit - Searching Completion DataI've wired up the CompletionData no problem, inserting etc into the Avalon Edit control.
The challenge is the searching algorithm.
In the example below, I want new-obj to "match" New-Object* in the list and not do a partial find on New-DataObject.
Is there a flag I can set? Or do I need to override the search and implement my own?
Thank you
Doug

In the XAML you're setting the property to the default value which will not cause the PropertyChanged handler to fire. The boilerplate Get and Set methods will never be called unless you call them from code because properties set in XAML call GetValue and SetValue directly (as is the case with wrapper properties on a normal DP).
To ensure the change handler is always called when a value is set you could use a Nullable<HorizontalAlignment> instead and set the default to null.
When using Hazelcast, I get warnings like:
Jun 21, 2015 11:10:15 AM com.hazelcast.partition.InternalPartitionService WARNING: [192.168.0.18]:5701 [5a11] [3.4.2] Following unknown addresses are found\ in partition table sent from master[Address[192.168.0.9]:5701]. (Probably they have recently joined or left the cluster.) { Address[192.168.0.13]:5701 } Jun 21, 2015 11:10:29 AM com.hazelcast.partition.InternalPartitionService WARNING: [192.168.0.18]:5701 [5a11] [3.4.2] Following unknown addresses are found\ in partition table sent from master[Address[192.168.0.20]:5701]. (Probably they have recently joined or left the cluster.) { Address[192.168.0.11]:5701 Address[192.168.0.17]:5701 } Warning: irregular exit, check log What is the cause, and do I have to take actions to avoid these warnings?
Details:
These warning occur at the end of my distributed computations, and not for all instances. So it is very likely that some other instances have terminated and thus "recently left the cluster" when this warning occurs.
But why does an instance leaving cause an unknown address? Does this mean the instance x giving the warning somehow found out that instance y has left, and the master hasn't yet found out and sends the address of y to x, causing this warning?
Should I take actions to avoid this warning? Does it mean that y forgets some cleanup it is supposed to do at the end so that the master immediately finds out that y leaves the cluster? The only cleanup the instances are performing is shutdown() of their HazelcastInstance.
Is the irregular exit at the end of my log messages caused by the inconsistency in the partition table?
-28614566 0The OS handles scheduling and dispatching of ready threads, (those that require CPU), onto cores, managing CPU execution in a similar fashion as it manages other resources. A cache-miss is no reason to swap out a thread. A page-fault, where the desired page is not loaded into RAM at all, may cause a thread to be blocked until the page gets loaded from disk. The memory-management hardware does that by generating a hardware interrupt to an OS driver that handles the page-fault.
-12009827 0Yes, this looks like VS2003 bug. Workaround is simple - use typedef, it works this way:
class A { public: int x; }; class B : public A { public: class A { public: int y; }; }; typedef B::A BA; class C: public BA {}; void f() { C cc; cc.y = 0; }
-27743941 0 Trigger is not going to execute for each Row. Change your trigger like this.
CREATE TRIGGER trig_INVOICE ON INVOICE after INSERT, UPDATE AS BEGIN UPDATE a SET AMOUNT = QUANTUM * p.price FROM INVOICE a JOIN inserted b ON a.PRODUCTID = b.PRODUCTID JOIN PRODUCT p ON a.PRODUCTID = p.PRODUCTID END
-27642754 0 Register a role resolver. See my example here: https://github.com/strongloop/loopback-example-access-control/blob/master/server/boot/create-role-resolver.js
-24281473 0 How to disable the dropdownlist in DetailView depending on the date?I'm using a DropDownList in the DetailView (EditMode) and I would like to disable it depending on the date of the system. For example : between the 18 June and the 20 June, make the dropdownlist disabled (gray).
Any idea ?
-11448125 0 Entity Framework - how to save entity without saving related objectsIn my Entity Framework, I have three related entities 'Client', 'ClientAddress' and 'LookupAddressType'. "LookupAddressType" is a master class specifying the type of available address type, like business address, residential address etc. ClientAddress depend on LookupAddresstype and Client. While saving a Client entity with relevant ClientAddress data, i'm getting following error.
"Violation of PRIMARY KEY constraint 'PK_LookupAddressType'. Cannot insert duplicate key in object 'dbo.LookupAddressType'. The statement has been terminated.
I do not need LookupAddressType to be inserted. Here I just need the relevant lookupAddressTypeId to be inserted in clientAddress entity.
The Saving code is like this:
Add(Client); _objectContext.SaveChanges(); how can i do this?
The Load Code is below:
private void LoadClientDetails(EFEntities.Client _Client) { EFEntities.LookupClientStatu clientStatus; var clientAddressList = new List<ClientAddress>(); if (_Client == null) { return; } //Assign data to client object _Client.ClientName = rtxtName.Text; _Client.Alias = rtxtAlias.Text; _Client.ClientCode =Int32.Parse(rtxtClientCode.Text); _Client.TaxPayerID = rtxtTaxPayerId.Text; if (rcboStatus.SelectedIndex != 0) { clientStatus = new EFEntities.LookupClientStatu { ClientStatusID = (Guid) (rcboStatus.SelectedValue), ClientStatusDescription = rcboStatus.Text }; _Client.LookupClientStatu = clientStatus; } //_Client.Modified = EnvironmentClass.ModifiedUserInstance.Id; _Client.EffectiveDate = rdtEffectiveDate.Value; if (rdtExpDate.Value != rdtExpDate.MinDate) { _Client.ExpirationDate = rdtExpDate.Value; } else { _Client.ExpirationDate = null; } _Client.StartDate = DateTime.Now; EFEntities.ClientAddress clientAddress = null; // Iesi.Collections.Generic.ISet<ClientAddress> clientAddress = new HashedSet<ClientAddress>(); foreach (var cAddress in _clientController.client.ClientAddresses) { clientAddress = cAddress; break; } if (clientAddress == null) { clientAddress = new EFEntities.ClientAddress(); } clientAddress.Address1 = rtxtClientAdd1.Text; clientAddress.Address2 = rtxtClientAdd2.Text; clientAddress.Address3 = rtxtClientAdd3.Text; // Address type details if (rcboClientAddType.SelectedIndex != -1) { clientAddress.LookupAddressType = new EFEntities.LookupAddressType { AddressTypeID = (Guid) (rcboClientAddType.SelectedValue), AddressTypeDescription = rcboClientAddType.Text }; //clientAddress.AddressType.Id = Convert.ToByte(rcboClientAddType.SelectedValue); } clientAddress.City = rtxtClientCity.Text; clientAddress.Client = _Client; \
_Client.ClientAddresses.Add(clientAddress); }
-15200646 0 Get actual size of a gzip file in android I am using GZIPInputStream to download pdf file I want to show the download progress of the file on a UI button. But, I am not getting the actual size of the file , what I am getting is compressed size due to which I am unable to show the correct download progress. This download progress is exceeding 100 as the actual file size is greater than the compressed size of file. Header content of file from server : - Following info I receive from server, from which I am using content-length which is giving compressed file size.
1.Connection 2.Content-Encoding 3.Content-length 4.Content-Type 5.Keep-Alive 6.Server 7.Date
Here is my code.
long fileLength = httpResponse.getEntity().getContentLength();// GZIPInputStream input = new GZIPInputStream(new BufferedInputStream(httpResponse.getEntity().getContent())); FileOutputStream output = new FileOutputStream(destinationFilePath); byte data[] = new byte[1024]; long total = 0; float percentage = 0; int count; currentDownloadingPercentage=0; while ((count = input.read(data)) != -1) { total += count; output.write(data, 0, count); // publishing the progress.... percentage = (float)total/(float)fileLength; percentage *= 100; if((int)percentage > (int)currentDownloadingPercentage) { currentDownloadingPercentage = percentage; Bundle resultData = new Bundle(); resultData.putBoolean(DOWNLOAD_FAILED, false); resultData.putInt(DOWNLOAD_PROGRESS ,(int)percentage); receiver.send(processID, resultData); resultData = null; } }
-22195100 0 Laravel 4 Migration has syntax error when adding Foreign Key I'm trying to create a pivot table to hold some relationship data for some basic ACL functionality.
The migration class:
Schema::create('group_user', function($table) { $table->increments('id'); $table->unsignedInteger('group_id'); $table->unsignedInteger('user_id'); $table->timestamps(); $table->softDeletes(); }); Schema::table('group_user', function($table) { $table->foreign('group_id') ->reference('id')->on('groups'); $table->foreign('user_id') ->reference('id')->on('users'); }); After running the migration command, I get the following error:
[Illuminate\Database\QueryException] SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at li ne 1 (SQL: alter table `group_user` add constraint group_user_group_id_foreign foreign key (`group_id`) references `groups` ()) As you can see, the SQL syntax to add the foreign key constraint is missing the 'id' column name for the referenced table. Is this a bug in Laravel or is there something wrong with my schema code?
-4102462 0I've used: Firebird, MySql, SQLite, Oracle and even Postgres long long ago.
-4592453 0I think your id column is varchar it schould be int
but maybe did can help you
http://support.microsoft.com/kb/209632
to order string as numeric
-31248738 0You may be running into Bug #69874 Can't set empty additional_headers for mail() if you haven't done anything stupid (i.e. forgot to sanitize the headers).
Test for the bug
$ php -d display_errors=1 -d display_startup_errors=1 -d error_reporting=30719 -r 'mail("test@email.com","Subject Here", "Message Here",NULL);' Warning: mail(): Multiple or malformed newlines found in additional_header in Command line code on line 1 Alternately if you know your PHP version (hint: php -v) you can check the changelog for the bug number (69874) to see whether the fix has been applied for your version.
A short-term fix is to replace calls to mail() like this
function fix_mail( $to , $subject , $message , $additional_headers =NULL, $additional_parameters=NULL ) { $to=filter_var($to, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES| FILTER_FLAG_STRIP_LOW| FILTER_FLAG_STRIP_HIGH); $subject=filter_var($subject, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES| FILTER_FLAG_STRIP_LOW| FILTER_FLAG_STRIP_HIGH); if (!$additional_headers) return mail( $to , $subject , $message ); if (!$additional_parameters) return mail( $to , $subject , $message , $additional_headers ); return mail( $to , $subject , $message , $additional_headers, $additional_parameters ); }
-30009395 0 PCA computation on 2D vectors of type double I am trying to run PCA on a dataset which I have stored into a 2D vector from a file as follows:
std::vector<std::vector<double> > tmpVec; while(std::getline(file, numStream)) { std::istringstream buffer(numStream); std::vector<double> line((std::istream_iterator<double>(buffer)), std::istream_iterator<double>()); tmpVec.push_back(line); i++; } Now I need to run PCA on this for which according to my understanding I need to convert this to type cv::Mat. This is being done as follows:
cv::Mat dst(row, col, CV_64F, &tmpVec); And thrn i run PCA on it as:
cv::PCA pca(dst, cv::Mat(), CV_PCA_DATA_AS_ROW, 2); When I try printing it out on screen after PCA computation i end up with garbage values. I just need to figure out how to run PCA on a 2D double vector. Any help with this or pointing me in the right direction would be great. Thanks in advance.
-15848598 0 Adding mysql user to databaseIs it possible to add mysql user into a database as column?
Lets say we have a following table:
CREATE TABLE message( id INT AUTO_INCREMENT NOT NULL, title VARCHAR(255), message TEXT, last_edited TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (id) ) ENGINE=INNODB; and we want to add 'editor' column which would get the current mysql user and insert it there and also updates it automatically similar to the behaviour of the TIMESTAMP datatype. Can this be done and if so what sort of datatype should I use (is there such a type as USER or should I use simple varchar) and what kind of syntax is involved?
-27102492 0ASP.net 5 ( MVC 6) still available as preview edition. Also they have changed some major changes so Owin the way it support in ASP.net MVC 5 will not support same way. As they have changed basic interface that support that functionality but today I came across article they provide information how can we use old Owin and integrate in ASP.net MVC 6.
http://blogs.msdn.com/b/webdev/archive/2014/11/14/katana-asp-net-5-and-bridging-the-gap.aspx
-10382834 0FB.login and FB.api doesn't provide you success/failure reporting just like you trying to implement it. There is no second argument for callbacks...
FB.login callback get one and only argument:
response from
FB.getLoginStatus,FB.loginorFB.logout. This response object contains:status
The status of the User. One of connected, not_authorized or unknown.
authResponse
The authResponse object.
FB.api callback get one and only arguments which is response from Graph API usually (but not always) containing data property, object fields, boolean false or error object (with message, type and code properties)
You can modify your loginHandler by correction of response callbacks to take care of right arguments:
function loginHandler(loginResponse){ try{ if(loginResponse.authResponse){ alert('i am if'); FB.api('/me', function(response) { alert("first name == " + response.first_name + "\n ln === " + response.last_name); }); } }catch(error){} }
-11380576 0 how to write the mongodb code in delphi This is the original code I tried:
obj = { sentence: "this is a sentece", tags: [ "some", "indexing", "words"] } and
findOne({tags: "words"}).name); I used the TMongWire as the wrapper of MongoDB for Delphi and I wrote this:
//var // d:IBSONDocument; d:=BSON([ 'id',mongoObjectID, 'sentence', 'this is a sentece', 'tags','["some", "indexing", "words"]' ]); FMongoWire.Insert(theCollection,d); it seem the codes above do the work
but when I query with the 'tags', it seems to not work for me
//var //q:TMongoWireQuery; //qb:IBSONDocument qb:=BSON(['tags', '"words"']); //*** q:=TMongoWireQuery.Create(FMongoWire); q.Query(mwx2Collection, qb); //*** How do I write the two lines with * asterisks?
-27485859 0It is not specific to Bootstrap.
Here is a solution using jQuery (works for bootstrap or non-bootstrap login box) :
$('.dropdown').on('mouseover', function () { $('.dropdown-menu', this).show(); }).on('mouseout', function (e) { if (!$(e.target).is('input')) { $('.dropdown-menu', this).hide(); } }); thanks to dtrunks for this solution : Div disappears when hovering the input autocomplete in Firefox
-37493718 0You should print values of x and y in your hopper function. Since chips2 contains indices in the matrix with value 2, then the index [9][9] will be contained in chips2 implying x = 9 or y = 9 at some point.
Therefore matrix[x+1][y+1] would mean matrix[10][10] which does not exist. You should review your code.
you should do:
if x < 8: if matrix[x+1][y+1] != 0 and matrix[x+2][y-2] == 0: #up + right . . . In that way, you don't perform a check on an index that is out of range
-34112530 0More elegant with shorter and more readable using java.util.Random and IntStream
Random random = new Random(); random.ints(10, 0, 10000).boxed().forEach(randomIntegers::add);
-25100976 0 How to rerun controllers after global data is resolved? I resolve data on application load in a run block...
.run(function($rootScope, $q, teams, schools, news, games){ // go out and grab all the relevant data $rootScope.showSplash = true; $q.all([ $rootScope.school = schools.get({id:1}), $rootScope.teams = teams.query({id:1}), $rootScope.news = news.query({id:1}), $rootScope.games = games.query({id:1}) ]).then(function(){ setTimeout(function(){ $rootScope.showSplash = false; $rootScope.$digest(); }, 1000); }) }) I have a controller whose scope should clone the data via $rootScope...
.controller('NewsDetailCtrl', function ($scope, $routeParams) { $scope.newss = $scope.news.filter(function(news){ return news.id == $routeParams.id; }).shift(); }); If the user is on the new-detail.html page, no data is present because the $scope clones an empty array. Is it possible to rerun the controllers when that information is received?
-25420424 0This library should do the trick. https://github.com/Pkmmte/PkRSS
It automatically handles all your RSS loading and parsing so you don't need to worry about it.
-8516141 0 Best approach for implementing Backbone js and jQueryCan some one help me to find the best approach? Its is documentcloud.
References between Models and Views can be handled several ways.
Thanks!
-13462999 0Dates in SQL are represented as #year/month/day#, eg. today's date would be #2012/11/19#, and to make DLookup work you have to use this syntax:
DLookup("HolidayDate", "Holidays", "HolidayDate=" & Format([EncDateTime],"\#yyyy/mm/dd\#")) to check if today is holiday, you could use this:
DLookup("HolidayDate", "Holidays", "HolidayDate=" & Format(Date(),"\#yyyy/mm/dd\#")) Yes, DLookup is slow, you should not use it in a query. To check if EncDateTime is a holiday, you should join EncData and Holidays togheter, with this SQL Code:
SELECT EncData.* FROM EncData INNER JOIN Holidays ON EncData.EncDateTime = Holidays.HolidayDate This should return all EncData rows that are hoildays. It should, but it probably doesn't. Notice that EncDateTime contains not only the date, but also the time, so it doesn't match with HolidayDate that contains just the date. This works instead:
SELECT EncData.* FROM EncData INNER JOIN Holidays ON DateValue(EncData.EncDateTime) = Holidays.HolidayDate And to extract all the rows in EncData, not just the holidays?
SELECT EncData.*, Holidays.HolidayDate FROM EncData LEFT JOIN Holidays ON DateValue(EncData.EncDateTime) = Holidays.HolidayDate Notice that when HolidayDate contains a date only when that day is holiday, otherwise it will be NULL.
These are just some basic ideas to start. But don't forget that you cans use wizards to make your query, then you can always see how your SQL code looks like.
-28321897 0Using Alex's answer I was able to move multiple issues from one sprint to another. Adding step by step incase it helps anyone else.
Sprint: {oldSprint} State: Submitted State: Open State: {In Progress} State: BlockedSprint Unscheduled Sprint newSprint. This'll first unassign the issue from the old sprint then assign it to the new sprint.I´m getting data from a database, the query works in the correct way, but I want to save that data in JsonArray.
while(rset.next()){ for(int i=0;i<numeroColumnas;i++){ json.addProperty(key[0], rset.getInt(key[0])); json.addProperty(key[1], rset.getString(key[1])); json.addProperty(key[2], rset.getString(key[2])); json.addProperty(key[3], rset.getInt(key[3])); json.addProperty(key[4], rset.getDouble(key[4])); json.addProperty(key[5], rset.getDouble(key[5])); } ajson.add(json); System.out.println("Cadena JSON:" +ajson.toString()); }
This code generates an incorrect output, I get repeat values:
Cadena JSON:[{"IDCOORD":1,"HORA":"2012-02-13 07:58:06.146","FECHA":"2012-02-13 >07:58:03","COOR_IDEQUIPO":1,"LATITUD":28.56245,"LONGITUD":-16.7000555}]
[{"IDCOORD":2,"HORA":"2012-02-13 07:59:41.881","FECHA":"2012-02-13 >07:59:39","COOR_IDEQUIPO":1,"LATITUD":-4.7152449,"LONGITUD":41.6514567}, {"IDCOORD":2,"HORA":"2012->02-13 07:59:41.881","FECHA":"2012-02-13 >07:59:39","COOR_IDEQUIPO":1,"LATITUD":->4.7152449,"LONGITUD":41.6514567}]
I´m pretty sure that I´m doing something wrong on while. Thanks in advance!
-35703857 0 Get files from remotePath that are not in localPath using C#I am using WINSCP functionality with an SSIS script task to move files from a remotePath to a localPath. I am also setting these files to readonly using:
File.SetAttributes(LocalPath, FileAttributes.ReadOnly); This works to set the attributes, it is just that since I have pulled some data from the remotePath that is already on the localPath, the readonly attribute gets set back to 0 and the archive attribute gets set to 1.
Is there an easy way that I can just pull the files from the remotePath that aren't already in the localPath?
This would eliminate any overwriting of files and also fix my readonly / archive attributes situation
-30881224 0I would also add that transactional databases are meant to hold current state and oftentimes do so to be self-maintaining. You don't want transactional databases growing beyond their necessary means. When a workflow or transaction is complete then move that data out and into a Reporting database, which is much better designed to hold historical data.
-37257833 0 Slider not appearingSo I'm working on a website and I need a drawer on the left side and on the right side. First, I've made the left one and it seems to be working great so I've decided to copy it and change the names and the CSS in order to make the same one appear on the right side, but it isn't showing at all.. I might've made a small mistake, I might've made a big one, but I can not find it. Hopefully some of ya'll could help me out with this. It's practically an X in the left corner of the window which slides in the drawer with info and the same thing should be for the right side as well.
$(document).ready(function() { $(".trigger-left").click(function() { $(".panel-slide-left").toggle("fast"); $(this).toggleClass("active"); return false; }); }); $(document).ready(function() { $(".trigger-right").click(function() { $(".panel-slide-right").toggle("fast"); $(this).toggleClass("active"); return false; }); }); .panel-slide-right { position: absolute; right: 0; display: none; background-color: #edf2f4; width: 330px; height: 100%; padding-left: 50px; padding-top: 50px; } .panel-slide-left p { margin: 0 0 15px; padding: 0; color: #ccc; } .panel-slide-right p { margin: 0 0 15px; padding: 0; color: #ccc; } .panel-slide-left a:hover, .panel-slide-left a:visited:hover { margin: 0; padding: 0; color: #fff; text-decoration: none; border-bottom: 1px solid #fff; } .panel-slide-left a:hover, .panel-slide-left a:visited:hover { margin: 0; padding: 0; color: #fff; text-decoration: none; border-bottom: 1px solid #fff; } a.trigger-left { position: absolute; text-decoration: none; top: 50px; left: 0; font-size: 16px; letter-spacing: -1px; font-family: verdana, helvetica, arial, sans-serif; color: #fff; padding-left: 20px; font-weight: 700; display: block; } a.trigger-right { position: absolute; top: 50px; right: 0; top: 50px; left: 0; font-size: 16px; letter-spacing: -1px; font-family: verdana, helvetica, arial, sans-serif; color: #fff; padding-left: 20px; font-weight: 700; display: block; } a.trigger-left:hover { position: absolute; text-decoration: none; top: 50px; left: 0; font-size: 16px; letter-spacing: -1px; font-family: verdana, helvetica, arial, sans-serif; color: #fff; padding-left: 20px; font-weight: 700; display: block; height: 50px; } a.trigger-right:hover { position: absolute; text-decoration: none; top: 50px; right: 0; font-size: 16px; letter-spacing: -1px; font-family: verdana, helvetica, arial, sans-serif; color: #fff; padding-left: 20px; font-weight: 700; display: block; height: 50px; } a.active.trigger-left { color: #fff; } a.active.trigger-right { color: #fff; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="panel-slide-left"> <div style="clear:both;"></div> <div class="columns"> <div class="colcenter"> <div class="checkbox"> <label> <input type="checkbox" value=""> <h5>Broadcast Language English</h5> </label> </div> <div class="checkbox"> <label> <input type="checkbox" value=""> <h5>Stream Language English</h5> </label> </div> </div> </div> <div style="clear:both;"></div> </div> <a class="trigger-left" href="#">X</a> <div class="panel-slide-right"> <div style="clear:both;"></div> <div class="columns"> <div class="colcenter"> <div class="checkbox"> <label> <input type="checkbox" value=""> <h5>Broadcast Language English</h5> </label> </div> <div class="checkbox"> <label> <input type="checkbox" value=""> <h5>Stream Language English</h5> </label> </div> </div> </div> <div style="clear:both;"> </div> <a class="trigger-right" href="#">X</a> One of several places this topic has been discussed is this StackOverflow question.
You need a simple regular language over c1 and c2. The automaton you might write has two states: an initial state, in which no c2 has been encountered in the input, and in which c1 and c2 are accepted, and a second state in which c2 has been seen, and in which only c1 is accepted. This language can be described by the regular expression (c1*c2c1*), or by the content model
<xs:sequence> <xs:element ref="c1" minOccurs="0" maxOccurs="unbounded"/> <xs:element ref="c2"/> <xs:element ref="c1" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> A more general form of the question (with two required elements) is described in this answer to a related SO question. As the number of required elements rises, the content model experiences combinatorial explosion; in those cases, the all-groups of XSD 1.1 are much more convenient.
-9382576 0figured it out. I need to learn more about git.
running git add . before my git commit fixed it.
This is a big subject indeed. When moving into microservices, you need to remember that a lot of your headaches are going to be operational (devops oriented) rather than "code".
Also, there's so much out there that at some point you will just need to make a decision, regardless if it's optimal. Things will change along the way in any case. Make the best decision you can at the moment, go with it, and tweak later.
Regarding your questions, REST is a common practice. There are also other options (WCF, Avro, whatever). Give yourself a timeline for a decision. If you know REST and feel comfortable with REST, take the decision. Try to see if you can build it so you can change / add other protocols later, but don't make it delay you too much.
Like Udi said, some architecture considerations are if you need to call this service sync or async (via a message bus). Also, yes, think about service discovery. There are several options (zookeeper, consul).
For some background and overview, try going through some of the resources:
http://blog.arkency.com/2014/07/microservices-72-resources/
This also gives a quick overview of microservices patterns:
http://microservices.io/patterns/microservices.html
But again, there's a lot of information and ways of doing things, don't get swamped.
-29124053 0Everytime a user selects a timerange, it creates a kind of placeholder event for visual feedback to the user. This isn't actually an event yet, and it is removed when the user makes another selection.
What you need to do, is add an actual event whenever a selection is made.
Use the select callback.
It's triggered every time the user selects (clicks and drags) a time slot. In it, call addEventSource to add it to the calendar as an actual event. And then call unselect to manually remove the placeholder.
select: function (start, end, jsEvent, view) { $("#calendar").fullCalendar('addEventSource', [{ start: start, end: end, }, ]); $("#calendar").fullCalendar("unselect"); }
-34438622 0 This is an open-ended question and there is no clear answer with different tradeoffs.. I'm not a PHP programmer, but something like the following should work.
# THESE PARAMETERS CONTROL THE RANKING ALGORITHM. $rescale = 0; $spread = 1; function rescore ($n) { return log($n) + $rescale; } function rank ($scores) { return 100 / (1 + exp(- $spread * array_sum(array_map("rescore", $scores)))); } You should choose $rescale so that the average score rescores to something close to 0. And play around with $spread until you're happy with how much your scores spread out.
The idea is that log turns a wide range of scores into numbers in a comparable range that can be positive or negative. Add a bunch of rescored scores together and you get an arbitrary real number. Then throw that into a logistic function (see https://en.wikipedia.org/wiki/Logistic_function for details) to turn that into a number in your desired range.
I'm developing Android app just for hobby, and I made an app, when I test on my phones works well, I tested on :
Works great, and no error at all... but when I tested on Samsung Galaxy S4, and Samsung Galaxy S3.. no background music (on Galaxy S4 and no background pics are shown ), and what I click I see report error message so application crushes..
Error Log:
03-20 16:55:07.366: D/skia(29417): --- allocation failed for scaled bitmap 03-20 16:55:07.376: D/AndroidRuntime(29417): Shutting down VM 03-20 16:55:07.376: W/dalvikvm(29417): threadid=1: thread exiting with uncaught exception (group=0x4206c700) 03-20 16:55:07.391: E/AndroidRuntime(29417): FATAL EXCEPTION: main 03-20 16:55:07.391: E/AndroidRuntime(29417): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.**********a/com.***********a.Info}: android.view.InflateException: Binary XML file line #2: Error inflating class <unknown> 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.app.ActivityThread.access$700(ActivityThread.java:159) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.os.Handler.dispatchMessage(Handler.java:99) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.os.Looper.loop(Looper.java:176) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.app.ActivityThread.main(ActivityThread.java:5419) 03-20 16:55:07.391: E/AndroidRuntime(29417): at java.lang.reflect.Method.invokeNative(Native Method) 03-20 16:55:07.391: E/AndroidRuntime(29417): at java.lang.reflect.Method.invoke(Method.java:525) 03-20 16:55:07.391: E/AndroidRuntime(29417): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046) 03-20 16:55:07.391: E/AndroidRuntime(29417): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862) 03-20 16:55:07.391: E/AndroidRuntime(29417): at dalvik.system.NativeStart.main(Native Method) 03-20 16:55:07.391: E/AndroidRuntime(29417): Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class <unknown> 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.view.LayoutInflater.createView(LayoutInflater.java:626) 03-20 16:55:07.391: E/AndroidRuntime(29417): at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.view.LayoutInflater.onCreateView(LayoutInflater.java:675) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:700) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.view.LayoutInflater.inflate(LayoutInflater.java:470) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.view.LayoutInflater.inflate(LayoutInflater.java:398) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.view.LayoutInflater.inflate(LayoutInflater.java:354) 03-20 16:55:07.391: E/AndroidRuntime(29417): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:361) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.app.Activity.setContentView(Activity.java:1956) 03-20 16:55:07.391: E/AndroidRuntime(29417): at *********.Info.onCreate(Info.java:16) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.app.Activity.performCreate(Activity.java:5372) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257) 03-20 16:55:07.391: E/AndroidRuntime(29417): ... 11 more 03-20 16:55:07.391: E/AndroidRuntime(29417): Caused by: java.lang.reflect.InvocationTargetException 03-20 16:55:07.391: E/AndroidRuntime(29417): at java.lang.reflect.Constructor.constructNative(Native Method) 03-20 16:55:07.391: E/AndroidRuntime(29417): at java.lang.reflect.Constructor.newInstance(Constructor.java:417) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.view.LayoutInflater.createView(LayoutInflater.java:600) 03-20 16:55:07.391: E/AndroidRuntime(29417): ... 23 more 03-20 16:55:07.391: E/AndroidRuntime(29417): Caused by: java.lang.OutOfMemoryError 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:596) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:444) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:832) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.content.res.Resources.loadDrawable(Resources.java:2988) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.content.res.TypedArray.getDrawable(TypedArray.java:602) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.view.View.<init>(View.java:3563) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.view.ViewGroup.<init>(ViewGroup.java:475) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.widget.LinearLayout.<init>(LinearLayout.java:176) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.widget.LinearLayout.<init>(LinearLayout.java:172) 03-20 16:55:07.391: E/AndroidRuntime(29417): ... 26 more Please any help ?
-17196396 0 PEAR and absolute pathsIn why doesn't PEAR use absolute paths? it's stated that PEAR doesn't use absolute paths so people can overwrite select PEAR libs with their own. Is that the only reason? And if so is there any evidence that people actually do that?
I mean, it seems like using absolute paths would resolve a lot of issues people have with using PEAR libs and if the only reason for not using absolute paths is a use-case that no one actually utilizes it seems like PEAR would be better off using them.
(I don't consider this question a duplicate but more as a followup; posting in the other question likely wouldn't get me any responses since that question's already been answered, so I post this new question)
-36494038 0 Is a variable declared under Grails(1.3.6) controller action and class variable thread safe?Is a variable declared under Grails(1.3.6) controller action and class variable thread safe? i.e
class TestController { String y //Is y thread-safe? def testAction = { String x //Is x thread-safe? } }
-13656801 0 Create a recursive function:
Semi-psuedo:
function dumpArr (arr){ foreach element in arr { if element is array/object{ dumpArr(element) }else{ echo element } } } then, you can use CSS to adjust the padding, margin, etc
-39226234 0It has not been mentioned yet, so I will point out that OpenCV has functions for scaling and rotating images, as well as an enormous number of other utilities. It may contain many features that are not relevant to the question, but it is very easy to setup and use for a library of its kind.
You can try to implement transformations like this manually, but the simple approach to scaling and rotating will generally result in a significant loss of detail.
Using OpenCV, scaling can be done like so:
float scaleFactor = 0.68f; cv::Mat original = cv::imread(path); cv::Mat scaled; cv::resize(original, scaled, cv::Size(0, 0), scaleFactor, scaleFactor, cv::INTER_LANCZOS4); cv::imwrite("new_image.jpg", scaled); This scales the image down by a factor of 0.68 using Lanczos interpolation.
I am not as familiar with rotations, but here's part of an example from one of the tutorials on the OpenCV website that I have edited down to the relevant parts. (The original had skew and translation in it also...)
/// Compute a rotation matrix with respect to the center of the image Point center = Point(original.size().width / 2, original.size().height / 2); double angle = -50.0; double scale = 0.6; /// Get the rotation matrix with the specifications above Mat rot_mat( 2, 3, CV_32FC1 ); rot_mat = getRotationMatrix2D(center, angle, scale); /// Rotate the image Mat rotated_image; warpAffine(src, rotated_image, rot_mat, src.size()); They have some very nice documentation too.
-25754243 0You could define a lambda function which calls your static function. Or simply store function name as a string in that variable. You would also have to implement a handler code for the class that calls a function from variable.
Resources: http://php.net/manual/en/function.forward-static-call-array.php
http://ee1.php.net/manual/en/function.func-get-args.php
Example for anonymous function:
<?php $function = new function(){ return forward_static_call_array(['class', 'function'], func_get_args()); }; ?> Testes this, works flawlessly.
-33727246 0Select the item you want to replace (double-click it, or CTRL-F to find it)...
Then do a (Ctrl - Apple - G) on Mac (aka. "Quick Find All"), to HIGHLIGHT all occurrences of the string at once.
Now just TYPE your replacement text directly... All selection occurrences will be replaced as you type (as if your cursor was in multiple places at once!)
Very handy...
-38067446 0Enumerable#group_by is a useful tool, but in this case it's not the best one.
If we start with a Hash whose default value is [0, 0] we can do (almost) everything—look up the month (or get the default value of it's a new month) and add 1 to the appropriate index (0 for false and 1 for true)—in a single step:
array = [["June", false], ["June", false], ["June", false], ["October", false]] hsh = Hash.new {|h,k| h[k] = [0,0] } array.each {|mo, bool| hsh[mo][bool ? 1 : 0] += 1 } p hsh.map(&:flatten) # => [["June", 3, 0], ["October", 1, 0]]
-29603764 0 using shared peferences to save colors I have an app that uses a color picking dialog to change the app background color, and the text color. The color picker works fine, but when the app closes for any reason it reverts back to default.
I have checked: http://developer.android.com/guide/topics/data/data-storage.html#pref and Android Shared preferences example
the below code is the result of my research. The problem I'm having is all my text fields start off without text color, when i use the color dialog the colors change just fine, but are not saved.
Any pointers on where I'm going wrong would be greatly appreciated.
public class TipCalculator extends ActionBarActivity implements ColorPickerDialog.OnColorChangedListener { //UI element objects to be manipulated. TextView tipper; TextView diner; /*few TextView items left out to save space*/ int color; RelativeLayout RLayout; private SharedPreferences preferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tip_calculator); preferences = getSharedPreferences("TipCalculator", MODE_PRIVATE); //color = preferences.getInt("TipCalculator", color); did not change anything color = preferences.getInt("bg_color", color); RLayout = (RelativeLayout) findViewById(R.id.RLayout);//layout object for background color manipulation bill = (EditText) findViewById(R.id.bill_amount_text);//UI elements placed in objects for text color manipulation billNtip = (TextView) findViewById(R.id.bill_tip_text); /*few TextView items left out to save space*/ bill.setSelection(bill.getText().length()); bill.addTextChangedListener(billWatcher); } @Override public void onPause(){// onStop does not seem to change how the app currently runs super.onPause(); /*preferences = getSharedPreferences("TipCalculator", MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); does not work*/ SharedPreferences.Editor editor = getSharedPreferences("TipCalculator", MODE_PRIVATE).edit(); //editor.putInt("TipCalculator", color); does not change anything editor.putInt("bg_color", color); editor.commit(); tipper.setTextColor(color); bill.setTextColor(color); /*few TextView items left out to save space*/ } @Override public void colorChanged(String key, int color) { color = newColor; if (decide.equals("font")) { tipper.setTextColor(color); bill.setTextColor(color); /*few TextView items left out to save space*/ } else if (decide.equals("background")) { RLayout.setBackgroundColor(color); } }
-34552806 0 I have just found out the error in my script. The 1st script works fine after correcting the error. I should have used th for the header row as I did in the html and not td. Also I have added the missing .hide() The 2nd script though hides the columns but will still show a space for any column it hides. Note that the correct script had been posted earlier but with toggle buttons, check box etc which didn't suite my desire. This script works fine without checkbox or toggle button.
<script> function finish(){ var sdtbl = document.getElementById('sdtbl'); var x = sdtbl.rows[0].cells.length; var y = sdtbl.rows.length; //Hide unused Bonus & Deduction payroll headers for (var i = 0; i < x; i++) { var hdr = sdtbl.rows[0].getElementsByTagName('th')[i]; var val = hdr.innerHTML; if (val === "") { $('#sdtbl tr').eq(0).find('th').eq(i).hide(); for (var j = 1; j < y; j++) { $('#sdtbl tr').eq(j).find('td').eq(i).hide(); } } } } </script>
-28148524 0 Object directory in Makefile.am My current Makefile.am looks something like this:
bin_PROGRAMS = MyProgram AM_CPPFLAGS = -I../shared MyProgram_SOURCES = main.cpp Source1.cpp ../shared/Source2.cpp clean : clean-am rm -f *~ rm -f DEADJOE distclean: distclean-am rm -f *~ rm -f DEADJOE rm -f Makefile rm -f *log This creates all the .o files in the current directory. How can I specify a different object directory in a Makefile.am? I failed to find this in the GNU documentation, although I am sure it must be there somewhere.
-4143703 0I had the same problem with Greek input, this patch from launchpad works for me too.
Thanks.
-25443975 0In the noscript section you could load a resource from your server. If the a visitor loads the resource, you know that he has JavaScript disabled.
I think that might have something to do that you haven't properly closed the files. I took the liberty to rewrite your code, without the chmod stuff (which I don't think is necessary)
filename = <your sourcefilename goes here> filename_gz = filename + ".gz" filepath = Rails.root + filename filepath_gz = Rails.root + filename_gz # gzip the file buffer = "" File.open(filepath) do |file| Zlib::GzipWriter.open(filepath_gz) do |gz| while file.read(4096, buffer) gz << buffer end end end # moves the filepath_gz to filepath (overwriting the original file in the process!) FileUtils.mv(filepath_gz, filepath) As you can see I've used File.open(path) and passed a block. This has the effect that the files will be closed automatically when the block exits. I've also changed the delete/rename code to simply move the gziped file to the original path, which has the same effect.
However, I strongly advice you to keep a backup of your original file.
-16060372 0 Rest web services - Synchronous or asynchrousI have one doubt in my mind, What is the default behavior of REST web services-Synchronous or asynchronous. If synchronous then can we create asynchronous.
-20153175 0These are 2 separate informations.
[[UIDevice currentDevice] name] // e.g. Raymonds iPhone What you want is the following:
[[UIDevice currentDevice] model] // e.g. iPhone, iPod touch, iPad, iOS Simulator // or [[UIDevice currentDevice] localizedModel], e.g. Le iPod (j/k) And for the device capacity, which there may be better examples, but this returns the space that is reported by the system:
- (NSString*)deviceCapacity { NSDictionary *attributesDict = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSTemporaryDirectory() error:NULL]; NSNumber *totalSize = [attributesDict objectForKey:NSFileSystemSize]; return [NSString stringWithFormat:@"%3.2f GB",[totalSize floatValue] /(1000*1000*1000)]; } Note that the above example may return "14.37 GB" for a 16GB device (where 14.37 is the number the iOS reports, presumably the space after iOS is installed. So you can look at it as the user partition excluding the root partition.
So to put it all together, use this:
[NSString stringWithFormat:@"%@ %@", [[UIDevice currentDevice] model], [self deviceCapacity]];
-3031818 0 You'll have to do quite a bit of drawing by yourself. This MSDN section deals with Custom Control Painting and Rendering and the documentation for Control.Region has a sample for making round buttons that you might be able to adapt.
I'd suggest having a look at the codeproject site as well, a lot of people have written articles there about customizing various controls
-33543346 0 Can I simplify WebRTC signalling for computers on the same private network?WebRTC signalling is driving me crazy. My use-case is quite simple: a bidirectional audio intercom between a kiosk and to a control room webapp. Both computers are on the same network. Neither has internet access, all machines have known static IPs.
Everything I read wants me to use STUN/TURN/ICE servers. The acronyms for this is endless, contributing to my migraine but if this were a standard application, I'd just open a port, tell the other client about it (I can do this via the webapp if I need to) and have the other connect.
Can I do this with WebRTC? Without running a dozen signalling servers?
For the sake of examples, how would you connect a browser running on 192.168.0.101 to one running on 192.168.0.102?
-39453787 0 SQL Server 2008 R2: trigger after updateThis is my first post so please bear with me. Here are the tables I'm working with and I'm only showing the relevant columns:
Movement:
id cnt_tare_weight chassis_tare_weight Stop:
movement_id order_id For each movement record, there are 2 or more stop records. The way this works, is that we create an order and create the stops. The stops are grouped into movements.
Here's some example data:
Movement:
id cnt_tare_weight chassis_tare_weight ------------------------------------------------- 1545257 4525.2 3652.2 1545258 null null Stop:
order_id movement_id ------------------------ 0933774 1545257 0933774 1545257 0933774 1545258 0933774 1545258 Here's what I am trying to accomplish:
When the cnt_tare_weight and/or chassis_tare_weight are updated in the movement record, I need to copy this data to all other movement records for that order. I want to use a trigger after update to do this.
Here is what I've come up with but and I'm not sure it will work. I would like to see if what I'm wanting do is correct or if I'm missing something.
Here's my SQL:
CREATE TRIGGER set_tare_weights ON movement AFTER UPDATE AS BEGIN SET NOCOUNT ON; DECLARE @movement_id AS INT; DECLARE @cnt_tare_weight AS DECIMAL(8,1); DECLARE @chz_tare_weight AS DECIMAL(8,1); DECLARE @order_id AS int; SELECT @movement_id = inserted.id FROM INSERTED IF update(cnt_tare_weight) BEGIN SET @cnt_tare_weight = 'Updated cnt_tare_weight' END IF update(chz_tare_weight) BEGIN SET @chz_tare_weight = 'Updated chz_tare_weight' END SELECT @order_id = order_id FROM stop WHERE movement_id = @movement_id UPDATE movement SET cnt_tare_weight = @cnt_tare_weight, chz_tare_weight = @chz_tare_weight WHERE @movement_id IN (SELECT DISTINCT movement_id FROM stop WHERE order_id = @order_id) AND id <> @movement_id END I have never created a SQL Server trigger before. I'm not sure if this will work or if I need to do something more. Do I need to create a trigger that calls a stored procedure? Or will the above work?
Thanks for any help!
-15071133 0As far as I know the content isn't loaded when the div's display style is set to none.
Try setting something like this
<div style="width: 1px; height: 1px; position: absolute; top: -9999px; left: -9999px;"> <div id="player"></div> </div>
-4076169 0 How remove "installed twice" errors in RCP Product I have an RCP product based on 2 features: my product feature and the org.eclipse.rcp feature. It worked perfectly at export time and at run time.
Last week I decided to add the error log view to my product. I simply added the view to my "persective" and the logview plugin as plugin dependency in my main plugin. Just work fine !!!
After exporting my product (through headless build) I noticed that when launching my product I have a lot of errors in the error log view (not acceptable for customers even if all is working fine). These errors are related to the RCP feature plugins and say:
the plugin org.eclipse.xxx (one error for each plugin of the RCP feature) has already been installed from /plugins/org.eclipse.xxx
Any idea on the way to avoid these errors ? I guess this means I have something wrong in my product configuration.
-35505766 0The best way around this would be a redesign, if at all possible.
You can even implement this retrospectively by adding a new column to replace the schema, for example: Profile, then merge all tables from each schema into one in a single schema (e.g. dbo).
Then your procedure would appear as follows:
create procedure dbo.usp_GetDataFromTable1 @profile int, @userid bigint as begin select a.EmailID from dbo.Table1 a where a.ID = @user_id and a.Profile = @profile end I have used an int for the profile column, but if you use a varchar you could even keep your schema name for the profile value, if that helps to make things clearer.
my suggestion is: just keep codding the way it is, until a problem rises or an extremely need for the change appears.
-21736951 0 Saving a CSV into a blobI would like to save CSV files that users upload to a blob. I would than like to retrieve the CSV file out of the blob in a format that I can use with the ruby CSV library. Any ideas on how I can accomplish that?
-23569281 0You can use the Environment.GetFolderPath method and Combine it into a real path:
String subPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),"Reports");
-32955638 0 How to rewrite this on jQuery I have ul with 5 li inside, need to select one of them with index [curSlide-1], I writed it on JS, but can't do that on jQuery:
var $bullets = $("ul").find(".bullet"); var curSlide = 5; document.getElementsByClassName("bullet")[curSlide-1].className = "bullet active-bullet"; I've tried to write it on jQuery, but it doesn't work:
$bullets[curSlide-1].addClass("active-bullet"); Can somebody tell how to rewrite it correctly?
-41074129 0 Facebook native ad won't click: AndroidI am creating a native ad on android using audience network. The problem is that the ads are shown but do not click.Whenever I click on any of the views I registered for clicking the ad, nothing happens. I am loading the ads into a custom listView with a custom adapter:
static StaticListView turning_up_lv; //My custom listview private static void showNativeAd() { nativeAd = new NativeAd(context, AD_ID); nativeAd.setAdListener(new AdListener() { @Override public void onError(Ad ad, AdError error) { } @Override public void onAdLoaded(Ad ad) { if (ad != nativeAd) { return; } isAdLoaded = true; if ((turning_up_lv.getAdapter()) != null && turning_up_lv.getCount() > 3) { ((MyAdapter) turning_up_lv.getAdapter()).addNativeAd(ad, false); } } @Override public void onAdClicked(Ad ad) { } }); nativeAd.loadAd(NativeAd.MediaCacheFlag.ALL); } Here is the code for the custom listview:
public class StaticListView extends ListView { public StaticListView(Context context) { super(context); } public StaticListView(Context context, AttributeSet attrs) { super(context, attrs); } public StaticListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(MEASURED_SIZE_MASK, MeasureSpec.AT_MOST)); getLayoutParams().height = getMeasuredHeight(); } }
And finally here is the part where I load the ad into the adapter. Note that I have removed some irrelevant parts since the adapter is so long
@Override public View getView(final int position, View convertView, final ViewGroup parent) { View row = convertView; MyViewHolder holder; if (row == null) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); row = inflater.inflate(R.layout.turning_up_item, parent, false); holder = new MyViewHolder(row); row.setTag(holder); } else { holder = (MyViewHolder) row.getTag(); } if (position == AD_INDEX && ad != null) { inflateAd((NativeAd) ad, holder, row); } else { //Load other listview items } } Here is the code for inflating the ad:
private void inflateAd(final NativeAd nativeAd, MyViewHolder holder, final View view) { // Create native UI using the ad metadata. // Setting the Text holder.time_tv.setText("Sponsored"); holder.native_ad_social_context.setText(nativeAd.getAdSocialContext()); holder.native_ad_call_to_action.setText(nativeAd.getAdCallToAction()); holder.native_ad_call_to_action.setVisibility(View.VISIBLE); holder.un_tu.setText(nativeAd.getAdTitle()); holder.comment_or_caption_tv.setText(nativeAd.getAdBody()); // Downloading and setting the ad icon. NativeAd.Image adIcon = nativeAd.getAdIcon(); NativeAd.downloadAndDisplayImage(adIcon, holder.ad_iv); // Downloading and setting the cover image. NativeAd.Image adCoverImage = nativeAd.getAdCoverImage(); int bannerWidth = adCoverImage.getWidth(); int bannerHeight = adCoverImage.getHeight(); DisplayMetrics metrics = context.getResources().getDisplayMetrics(); int mediaWidth = holder.native_ad_media.getWidth() > 0 ? holder.native_ad_media.getWidth() : metrics.widthPixels; holder.native_ad_media.setLayoutParams(new LinearLayout.LayoutParams( mediaWidth, Math.min( (int) (((double) mediaWidth / (double) bannerWidth) * bannerHeight), metrics.heightPixels / 3))); holder.native_ad_media.setAutoplay(AdSettings.isVideoAutoplay()); holder.native_ad_media.setNativeAd(nativeAd); addLoadedToMediaView = true; final ArrayList<View> clickableViews = new ArrayList<>(); clickableViews.add(holder.native_ad_media); clickableViews.add(holder.native_ad_social_context); clickableViews.add(holder.native_ad_call_to_action); nativeAd.registerViewForInteraction(view, clickableViews); }
-11333623 0 Rails app using stripe for payments: can't transmit plan_id from app to stripe website I'm trying to integrate stripe into my app. I'm following a Railscast (#288) but I'm getting the impression there a are few things that Ryan isn't mentioning explicitly.
My problem is that the plan_id on my app doesn't get transmitted over to Stripe. Once I generate a test transaction in my app and I log on to Stripe, it will show that a new customer with a valid card was created, but the plan_id isn't transmitted. I do have plans setup on stripe. But since no plan_id is submitted, the credit card never gets charged. So I've got customers, but no payments.
Here's my subscription/new.html.haml. I'm wondering if I need to assign a value to the hidden field "plan_id."
%p = @plan.name = @plan.price = form_for @subscription do |f| - if @subscription.errors.any? .error_messages %h2 = pluralize(@subscription.errors.count, "error") prohibited this subscription from being saved: %ul - @subscription.errors.full_messages.each do |msg| %li= msg = f.hidden_field :plan_id = f.hidden_field :stripe_card_token .field = f.label :email = f.text_field :email - if @subscription.stripe_card_token Credit card has been provided - else .field = label_tag :card_number, "Credit Card Number " = text_field_tag :card_number, nil, name: nil .field = label_tag :card_code, "Security Code on Card (CVV)" = text_field_tag :card_code, nil, name: nil .field = label_tag :card_month, "Card Expiration" = select_month nil, {add_month_numbers_true: true}, {name: nil, id: "card_month"} = select_year nil, {start_year: Date.today.year, end_year: Date.today.year+15}, {name: nil, id: "card_year"} .stripe_error %noscript JavaScript is not enabled and is required for this form. First enable it in your web browser settings. .actions= f.submit "Subscribe" Here's my subscription controller. The params(:plan_id) is passed using a string query.
def new @subscription = Subscription.new @plan = Plan.find_by_id(params[:plan_id]) end def create @subscription = Subscription.new(params[:subscription]) if @subscription.save_with_payment flash[:success] = "Thank you for subscribing!" redirect_to @subscription else render 'new' end end Here's my model for subscription.rb
class Subscription < ActiveRecord::Base has_many :users belongs_to :plan #validates_presence_of :plan_id, :email attr_accessible :stripe_card_token, :plan_id, :email attr_accessor :stripe_card_token def save_with_payment if valid? customer = Stripe::Customer.create(description:email, plan: plan_id, card: stripe_card_token) self.stripe_customer_token = customer.id save! end rescue Stripe::InvalidRequestError => e logger.error "Stripe error while creating customer: #{e.message}" errors.add :base, "There was a problem with your credit card." end end
-2988920 0 Getting list of states/events from a model that AASM I successfully integrated the most recent AASM gem into an application, using it for the creation of a wizard. In my case I have a model order
class Order < ActiveRecord::Base belongs_to :user has_one :billing_plan, :dependent => :destroy named_scope :with_user, ..... <snip> include AASM aasm_column :aasm_state aasm_initial_state :unauthenticated_user aasm_state :unauthenticated_user, :after_exit => [:set_state_completed] aasm_state : <snip> <and following the event definitions> end Now I would like to give an administrator the possibility to create his own graphs through the AASM states. Therefore I created two additional models called OrderFlow and Transition where there order_flow has many transitions and order belongs_to order_flow.
No problem so far. Now I would like to give my admin the possibility to dynamically add existing transitions / events to an order_flow graph.
The problem now is, that I do not find any possibility to get a list of all events / transitions out of my order model. aasm_states_for_select seems to be the correct candidate, but I cannot call it on my order model.
Can anyone help?
Thx in advance. J.
-5522604 0 Are there any tutorials on coding a parser for SVG files to be used by box2D?I am trying to create an iPhone game with fairly large levels. Hard coding the platforms and physics objects is very time consuming. I have seen some people have made their own parsers for svg files to use in box2D, and Riq is selling levelSVG but it is a little pricey for me at the moment, and I only need basic features. Is there a tutorial on how to code a parser available online?
-40290896 0I believe your call is matching the wrong overload of the helper method.
As written, it will match this signature:
public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues, object htmlAttributes) Notice there is no controller in there.
Try this instead:
@Html.ActionLink("View Staff", "Index", "Staff" , new { id = item.UnitCode }, null) Which should match the right signature with controller:
public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes)
-33207359 0 I would like to mention two things
AngularJs is not about DOM Manipulation.
working concept of directive ,it must be purely independent from the controller and all, must be working in all place.
In my view the directive triggering must be on the basis of data.
So there won't be a problem in using multiple directive in a single view if they are triggered according to data
-37277341 0 Check if all tuples in a list are different (ECLiPSe)I have a list with tuples like this:
[(1,2),(5,3),(6,7)] I'm trying to write a predicate that checks if all tuples in a list are different. The following line works for a list with integers but not for a list with tuples:
all_diff(L) :- \+ (select(X,L,R),member(X,R)). member/2 works fine to check if a tuple is in a list but it is the select/3 that has problems with tuples. It gives a type error.
How do I check if all tuples are different?
-20303123 0 Verdana font issueI must implement a website css from psd file. In psd some text is in Verdana, but when I use Verdana in css it appears thicker in a browser than Verdana in the psd file. Does anyone know the reason?
-2269515 0Although it is not object-oriented, Haskell offers a significant number of the features that interest you:
Syntax support for list comprehensions, plus do notation for a wide variety of sequencing/binding constructs. (Syntax support for dictionaries is limited to lists of pairs, e.g,
dict = ofElements [("Sputnik", 1957), ("Apollo", 1969), ("Challenger", 1988)] Functions support full closures and multiple return values using tuple types. Keyword arguments are not supported but a powerful feature of "implicit arguments" can sometimes substitute.
No runtime modification of classes, types or objects.
Avoidance of specificying classes/types everywhere through type inference.
Metaprogramming using Template Haskell.
Also, just so you will feel at home, Haskell has significant indentation!
I actually think Haskell has quite a different feel from Python overall, but that is primarily because of the extremely powerful static type system. If you are interested in trying a statically typed language, Haskell is one of the most ambitious ones out there right now.
-9026192 0I don't think there is an out-of-the-box solution to have 2 background colors.
The best solution would be to use gradient fills (fillcolor="orange:yellow") - but though this is in the documentation, I wasn't able to make it work on my box.
You could use HTML-like labels as a workaround. You may need to split the label to have it centered, depending on your needs:
a[shape="none", label=< <table cellpadding="0" cellborder="0" cellspacing="0" border="0"> <tr> <td bgcolor="orange">abc</td> <td bgcolor="yellow">def</td> </tr> </table> >] 
What's the right way to use sbt with 2.10 trunk? I tried the obvious:
james@James-Moores-iMac:~/workspace/Deleteme3$ cat build.sbt scalaVersion := "2.10.0-SNAPSHOT" But that gives:
james@James-Moores-iMac:~/workspace/Deleteme3$ sbt compile [info] Loading global plugins from /Users/james/.sbt/plugins [info] Set current project to default-ee38f7 (in build file:/Users/james/workspace/Deleteme3/) [info] Updating {file:/Users/james/workspace/Deleteme3/}default-ee38f7... [info] Resolving org.scala-lang#scala-library;2.10.0-SNAPSHOT ... [warn] module not found: org.scala-lang#scala-library;2.10.0-SNAPSHOT [warn] ==== local: tried [warn] /Users/james/.ivy2/local/org.scala-lang/scala-library/2.10.0-SNAPSHOT/ivys/ivy.xml [warn] ==== public: tried [warn] http://repo1.maven.org/maven2/org/scala-lang/scala-library/2.10.0-SNAPSHOT/scala-library-2.10.0-SNAPSHOT.pom [warn] ==== Scala-Tools Maven2 Repository: tried [warn] http://scala-tools.org/repo-releases/org/scala-lang/scala-library/2.10.0-SNAPSHOT/scala-library-2.10.0-SNAPSHOT.pom [warn] :::::::::::::::::::::::::::::::::::::::::::::: [warn] :: UNRESOLVED DEPENDENCIES :: [warn] :::::::::::::::::::::::::::::::::::::::::::::: [warn] :: org.scala-lang#scala-library;2.10.0-SNAPSHOT: not found [warn] :::::::::::::::::::::::::::::::::::::::::::::: [error] {file:/Users/james/workspace/Deleteme3/}default-ee38f7/*:update: sbt.ResolveException: unresolved dependency: org.scala-lang#scala-library;2.10.0-SNAPSHOT: not found [error] Total time: 1 s, completed Mar 18, 2012 10:39:29 AM james@James-Moores-iMac:~/workspace/Deleteme3$ Trying the suggestion of the new sbt launcher with -sbt-snapshot fails too:
james@James-Moores-iMac:/tmp/sfasdf$ sbt -sbt-snapshot compile Detected sbt version 0.12.0-SNAPSHOT Using /Users/james/.sbt/0.12.0-SNAPSHOT as sbt dir, -sbt-dir to override. Getting net.java.dev.jna jna 3.2.3 ... :: retrieving :: org.scala-sbt#boot-jna confs: [default] 1 artifacts copied, 0 already retrieved (838kB/13ms) Getting org.scala-sbt sbt 0.12.0-20120319-052150 ... :: retrieving :: org.scala-sbt#boot-app confs: [default] 38 artifacts copied, 0 already retrieved (7712kB/159ms) Getting Scala 2.9.1 (for sbt)... :: retrieving :: org.scala-sbt#boot-scala confs: [default] 4 artifacts copied, 0 already retrieved (19939kB/426ms) [info] Set current project to wand (in build file:/private/tmp/sfasdf/) Getting Scala 2.10.0-SNAPSHOT ... downloading http://scala-tools.org/repo-snapshots/org/scala-lang/scala-compiler/2.10.0-SNAPSHOT/scala-compiler-2.10.0-20120319.161232-290.jar ... [SUCCESSFUL ] org.scala-lang#scala-compiler;2.10.0-SNAPSHOT!scala-compiler.jar (28525ms) downloading http://scala-tools.org/repo-snapshots/org/scala-lang/scala-library/2.10.0-SNAPSHOT/scala-library-2.10.0-20120319.161232-293.jar ... [SUCCESSFUL ] org.scala-lang#scala-library;2.10.0-SNAPSHOT!scala-library.jar (16869ms) downloading http://scala-tools.org/repo-snapshots/org/scala-lang/jline/2.10.0-SNAPSHOT/jline-2.10.0-20120319.161232-290.jar ... [SUCCESSFUL ] org.scala-lang#jline;2.10.0-SNAPSHOT!jline.jar (1674ms) :: retrieving :: org.scala-sbt#boot-scala confs: [default] 4 artifacts copied, 0 already retrieved (21204kB/91ms) [info] Updating {file:/private/tmp/sfasdf/}default-59a990... [info] Resolving org.scala-lang#scala-library;2.10.0-SNAPSHOT ... [warn] module not found: org.scala-lang#scala-library;2.10.0-SNAPSHOT [warn] ==== local: tried [warn] /Users/james/.ivy2/local/org.scala-lang/scala-library/2.10.0-SNAPSHOT/ivys/ivy.xml [warn] ==== public: tried [warn] http://repo1.maven.org/maven2/org/scala-lang/scala-library/2.10.0-SNAPSHOT/scala-library-2.10.0-SNAPSHOT.pom [warn] :::::::::::::::::::::::::::::::::::::::::::::: [warn] :: UNRESOLVED DEPENDENCIES :: [warn] :::::::::::::::::::::::::::::::::::::::::::::: [warn] :: org.scala-lang#scala-library;2.10.0-SNAPSHOT: not found [warn] :::::::::::::::::::::::::::::::::::::::::::::: [error] {file:/private/tmp/sfasdf/}default-59a990/*:update: sbt.ResolveException: unresolved dependency: org.scala-lang#scala-library;2.10.0-SNAPSHOT: not found [error] Total time: 54 s, completed Mar 20, 2012 7:37:55 AM
-20915957 0 Thanks to all. The additional AND condition worked. I had actually tried that earlier but it didn't work when I was testing, in my haste I had not yet added the "completed" column to the table yet. Thanks again.
-20678586 0 Spring REST MultipartFile file is always null when do upload file@RequestMapping(value = "{fileName:.+}", method = RequestMethod.POST, consumes = { MediaType.MULTIPART_FORM_DATA_VALUE}) public ResponseEntity<ResponseEnvelope<String>> uploadFile( @RequestParam("ownerId") Long ownerId, @PathVariable("fileName") String fileName, @RequestBody MultipartFile file) throws Exception { ResponseEnvelope<String> env; if(null == certFileContent) { env = new ResponseEnvelope<String>("fail"); return new ResponseEntity<ResponseEnvelope<String>>(env, HttpStatus.OK); } service.uploadCertificate(ownerId, fileName, certFileContent.getBytes()); env = new ResponseEnvelope<String>("success"); return new ResponseEntity<ResponseEnvelope<String>>(env, HttpStatus.OK); } Why I always get the file value is null, I've configure the multipart support,see below,
-40803902 0
You need samsung certificate. Application with Certificate that created in Tizen Studio can be run only Emulator. Use Samsung Certificate if you want to run application on real device.
Refer this my answer.
-14940003 0Reserved words are a moving target. If the dbms doesn't expose them through a public interface, there isn't usually a good programmatic way to get to them.
If you don't want to guard them with brackets, you risk incorporating symbols that are not reserved in your currently used version of SQL Server, but are reserved in some future version.
I think your best bet is to use the quoting mechanism your dbms provides, since it's designed to deal with exactly this problem. For SQL Server, that means square brackets.
-3927498 0As far as I know, mongodb doesn't support queries against dynamic values. But you could use a javascript function:
scope :unresolved, :where => 'this.updated_at >= this.checked_at' To speed this up you could add an attribute like "is_unresolved" which will be set to true on update when this condition is matched ( and index that ).
-13303978 0Get rid of that new at the beginning. It's Charts.newColumnChart(), not new Charts.newColumnChart().
I think what you may be seeing is:
http://servername.domain.com/virtualdirectoryname/applicationname If you have named your virtual directory the same name as your application then I could see how that could confuse you. If you had no virtual directory and just your application at the root of the Default Web Site you'd be seeing:
http://servername.domain.com/applicationname Is your virtual directory the same name as your application name? If so, that is why you see this.
-980322 0Colon. Space + Underscore is used to split a single statement over multiple lines.
-21769708 0Your issue is not with Array, your question really involves escape sequences for special characters in strings. As the \ character is special, you need to first prepend it (escape it) with a leading backslash, like so.
"\\" You should also re-read your link and the section on escape sequences.
-15846134 0You probably want to declare fields, and get the values of the parameters in the constructor, and save the parameters to the fields:
public static class TCP_Ping implements Runnable { // these are the fields: private final int a; private final String b; // this is the constructor, that takes parameters public TCP_Ping(final int a, final String b) { // here you save the parameters to the fields this.a = a; this.b = b; } // and here (or in any other method you create) you can use the fields: @Override public void run() { System.out.println("a: " + a); System.out.println("b: " + b); } } Then you can create an instance of your class like this:
TCP_Ping ping = new TCP_Ping(5, "www.google.com");
-2987260 0 you have to MIME-encode your post: a binary post in an NNTP newsgroup is like a mail with an attachment.
the file has to be encoded in ASCII, generally using the base64 encoding, then the encoded file is packaged iton a multipart MIME message and posted...
have a look at the email module: it implements all that you want.
i encourage you to read RFC3977 which is the official standard defining the NNTP protocol.
for the second part of your question:
use StringIO to build a fake file object from a string (the post() method of nntplib accepts open file objects). email.Message objects have a as_string() method to retrieve the content of the message as a plain string.
In cake2 you can use a cleaner approach - with or without the new response object: http://www.dereuromark.de/2011/11/21/serving-views-as-files-in-cake2/
The headers will be set by cake itself from the controller. It's not good coding (anymore) to set them in the layout (I used to do that, as well^^).
These days the CakePdf plugin has matured quite a bit into a very useful tool for PDF generation. I recommend using that in Cake2.x.
See http://www.dereuromark.de/2014/04/08/generating-pdfs-with-cakephp
-15244567 0Your issue seems to be caused by the line break (which insert a space in the rendered html document). If you don't need that space b/w those two element then you can float both those element to left, it will ignore the space.
-9476616 0Create a new Map with refnum as key and qty as value.
Map<String,Integer> qtyMap=new HashMap<String,Integer>(); while iterating, try
String refNum=transItem.getRefNum(); // Mark for removal ? if this is not the first item in the list with the refnum boolean remove=true; Integer currentQty=qtyMap.get(refNum); if(currentQty==null){ currentQty=0; // this doesnt exist already in the map, this is the first item with this reference // number in the list, so you should keep this without removing remove=false; } currentQty=currentQty+transItem.getQty(); qtyMap.put(refNum,currentQty); // if the remove is true then remove this item from the list. if(remove){ groupTransItems.remove(); } This will sum up the qty for refnum's in the map and once your iteration is over, the map will have the sums of quantities for each refnum. You will have to iterate the list once more to set the current qty to each item from the map [EDIT] :- Added the iterating time removal.
-17431892 0I think the problem you are having is that the getQueryString method you are using is looking for the "?" operator in the URL, as in a traditional GET request (e.g. ?id=1). Instead, try passing the domain as a parameter in the controller method. For example:
In your routes file:
GET /customer/:domain controllers.Application.function(domain: String) Then in your Play controller (assuming Play Framework 2.x):
public static Result function(String domain){ //Do something with the passed domain string here return ok(...); }
-23815659 0 Timer thread has exited with code 259 (0x103) I want to make a clock which display UTC and Local together. So, I used Timer class from System.Threading like below:
private static object _lockObj = new object(); static bool isDisplaying = false; public MainWindow() { InitializeComponent(); System.Threading.Timer _timer = _timer = new System.Threading.Timer(timer_expired, null, 0, 1000); } private void timer_expired(object state) { if(!isDisplaying) lock (_lockObj) { this.Dispatcher.BeginInvoke(new Action(() => { this.UTC_TIME.Text = DateTime.UtcNow.ToString("MMM-dd HH:mm:ss"); this.LOCAL_TIME.Text = DateTime.Now.ToString("MMM-dd HH:mm:ss"); })); isDisplaying = false; } } But a few minutes later like 15 minutes or so, the clock stops. In a debug mode, I can see:
The thread 0x1e10 has exited with code 259 (0x103). How can I run this clock works all the time?
-18449819 0 what are the necessary steps to transfer the mastership of the clearcase stream to different location?I created one stream and now I would like to know the procedure to transfer the mastership of the stream in a different location? what are the steps should I follow?
Any help will be appreciated.
Thanks !!
-34393884 0 How to get image URL property from Wikidata item by API?I've made an android app that uses the JSON Google image search API to provide images but I have noticed that Google have stopped supporting it. I have also discovered that Wikidata sometimes provides a image property on some items, however I can't seem to get the URL location of the image using the Wikidata API.
Is there any way to get the image URL property from items in Wikidata?
-711966 0I think you'll have to use an XmlWriter. Or ToString.
Just found this article which seems to agree.
-6432324 0Ooo, a good question :)
As far as I know, Mark and Sweep is only used for reference counting event listeners since they're the only ones that can have 'weak listeners'. Everything else is straight up memory reference counting. Essentially, your biggest problem would be cleaning up event listeners, but if the event listeners are within your class (listening to itself, or it's children or even outside events) they should be GC'ed properly if the object is dereferenced throughout your app (don't store it somewhere else).
If you let object or properties be publically visible, it is possible for other classes to references them and it could prevent GC of your class (it really depends how it's referenced and all). The only to combat that is to try to encapsulate as much as possible (one class handles it's own dereferencing; look into IDisposable) so that others can't reference and try to adhere to good coding practices (preventing spaghetti code).
-30101110 0use if statement inside the click event
$("#primary-menu").on('click',function(){ if ($(window).width() <= 1024) { //.......... }else{ //.......... } });
-533541 0 One use could be dynamic control generation based on information that is only available from the bound data item at the time it is bound the Repeater.
-37448709 0 ActivityCompat.requestPermission not showing dialog when called inside onMenuItemClickHi i´m calling ActivityCompat.requestPermission inside my onMenuItemClick to grant the WRITE_EXTERNAL_STORAGE permission . However , ActivityCompat.requestPermissions is not executed .
My target is API 23
I have defined in my manifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18"/> and here is my code which i call inside the onMenuItemClick
case R.id.id_captura: if (ContextCompat.checkSelfPermission(ChatActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { dispatchTakePictureIntent(); } else { if (ActivityCompat.shouldShowRequestPermissionRationale(ChatActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) { } else { ActivityCompat.requestPermissions(ChatActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_EXTERNAL_STORAGE_CTE ); } } break; And here is my onRequestPermissionsResult
@Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case WRITE_EXTERNAL_STORAGE_CTE: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { dispatchTakePictureIntent(); } else { AlertDialog.Builder alertDialog = new AlertDialog.Builder(this).setTitle("Permissions").setMessage("Permissions not granted ").setPositiveButton("Accept", null); alertDialog.show(); } return ; } } } Aditionally I defined
private final int WRITE_EXTERNAL_STORAGE_CTE = 1;
-940648 0 eclipse plugin not loading dll due to long path I am building an eclipse plugin (a notes plugin, but its a eclipse plugin in the end). One of the plugins my plugin depends on needs to load a native dll.
The problem is, that fails depending on where in the disk such dll is. If it is longer than a certain threshold I get the error below
java.lang.UnsatisfiedLinkError: nlsxbe (The filename or extension is too long. ) at java.lang.ClassLoader.loadLibraryWithPath(ClassLoader.java:952) at java.lang.ClassLoader.loadLibraryWithClassLoader(ClassLoader.java:921) at java.lang.System.loadLibrary(System.java:452) at lotus.domino.NotesThread.load(Unknown Source) at lotus.domino.NotesThread.checkLoaded(Unknown Source) at lotus.domino.NotesThread.sinitThread(Unknown Source) at com.atempo.adam.lotus.plugin.views.TopicView.createPartControl(TopicView.java:609)
I have added the path to Path env var, and also registered the dll to no avail. My env is Ms vista profesional, java1.5, eclipse3.4 (and lotus 8)
Anyone out there have a clue?
Many thanks in advance.
-28317348 0Given your requirements, this block looks wrong to me:
if(array[i] % 2 !=0 && array[i] % 5 ==0){ odd++; } You're incrementing a counter, but you're not creating a sum of odd numbers. Nor are you printing it. Try this:
int total = 0; if ( array[i] % 2 != 0 && array[i] % 5 != 0) { // it's an odd number total += array[i]; } System.out.println("Total: " + total);
-36231293 0 must implement method doInBackground (params) I have a class extending AsyncTask which has to implement doInBackground method. I have the method defined below , still I have an error saying the class has to implement method.
public class MyDownloadJsonAsyncTask extends AsyncTask<Void , String, Bitmap> { private final WeakReference<RecyclerView_Adapter> adapterReference; MovieDataJson movieData; public MyDownloadJsonAsyncTask(RecyclerView_Adapter adapter) { adapterReference = new WeakReference<RecyclerView_Adapter>(adapter); } @Override protected MovieDataJson doInBackground(String... urls) { MovieDataJson threadMovieData = new MovieDataJson(); for (String url : urls) { threadMovieData.downloadMovieDataJson(url); } return threadMovieData; } @Override protected void onPostExecute(MovieDataJson threadMovieData) { movieData.moviesList.clear(); for(int i=0;i<threadMovieData.getSize();i++) { movieData.moviesList.add(threadMovieData.moviesList.get(i)); } if(adapterReference!=null) { final RecyclerView_Adapter adapter= adapterReference.get(); if(adapter!=null) adapter.notifyDataSetChanged(); } } }
and at @Override for each method above says method does not override method from its superclass
-5732436 0 ISerializable and DataContractUsing WCF In Silverlight services, typically we want to use the DataContract and Datamember attributes to opt into what we want to have serialized. This is what we send to and from the client. For most things this has never been a problem.
However, I have a few classes I am trying to share with my silverlight app, 'mature' classes, that I would like to send to the client full of data. These classes implement ISerializable which, doesn't like to play nice with the WCF service when I update.
I need to leave the ISerializable attribute on there because it is being used else where is some older code. Currently the way I see it is my best option being to have a new class to transfer the data through, if at all possible I would prefer not to have to write a class just for transfering the data but I am thinking that is what I am going to have to do.
Any Ideas on what I could do to get this to serialize through a service and still be able to keep the ISerializable tag on there?
-27712919 1 SQLAlchemy: order_by(None) for joinedload subclause queries?We are using SQLAlchemy 0.9.8 on Python 2.7.7 and Postgres 9.3.
We have a query that uses joinedloads to fully populate some Recipe objects using a single query. The query creates a large SQL statement that takes 20 seconds to execute - too long. Here's the rendered SQL statement on Pastebin.
The rendered SQL has an ORDER BY clause that Postgres explain says is the source of 99% of the time spent on this query. This appears to come from the relationship in the ORM model, which has an order_by clause.
However, we don't care about the order the results are returned for this query - we only care about the order when looking at a single object. If I remove the ORDER BY clause at the end of the rendered SQL statement, the query executes in less than a second - perfect.
We tried using .order_by(None) on the query, but that seems to have no effect. The ORDER BY seems to be related to the joinedloads, because if change the joinedloads to lazyloads, they go away. But we need the joinedloads for speed.
How can I get SQLAlchemy to omit the ORDER BY clauses?
FYI, here's the query:
missing_recipes = cls.query(session).filter(Recipe.id.in_(missing_recipe_ids)) if missing_recipe_ids else [] Here's an excerpt from the ORM class:
class Recipe(Base, TransactionalIdMixin, TableCacheMixin, TableCreatedModifiedMixin): __tablename__ = 'recipes' authors = relationship('RecipeAuthor', cascade=OrmCommonClass.OwnedChildCascadeOptions, single_parent=True, lazy='joined', order_by='RecipeAuthor.order', backref='recipe') scanned_photos = relationship(ScannedPhoto, backref='recipe', order_by="ScannedPhoto.position") utensils = relationship(CookingUtensil, secondary=lambda: recipe_cooking_utensils_table) utensil_labels = association_proxy('utensils', 'name') Our query() method looks something like this (some more joinedloads omitted):
@classmethod def query(cls, session): query = query.options( joinedload(cls.ingredients).joinedload(RecipeIngredient.ingredient), joinedload(cls.instructions), joinedload(cls.scanned_photos), joinedload(cls.tags), joinedload(cls.authors), )
-34886699 0 I found the solution, for anybody who cares.
I changed the command to execute a call to a batch script which then called the print command.
var directory = process.env['USERPROFILE'] + '\\Downloads\\'; var command = 'start cmd.exe /C ' + __dirname + '\\print.bat ' + directory + imageName + ' "EPSON TM-C3500"'; exec(command, {}, function(error, stdout, stderr){}); But then the batch script wasn't working... why? I don't know. I do know that adding a TIMEOUT 0 in the batch script fixed it.
TIMEOUT 0 rundll32 C:\\Windows\\System32\\shimgvw.dll ImageView_PrintTo /pt %*
-15433674 0 how to make a current website responsive? I want to make my current website responsive. It's a huge dynamic website and I do not want to make a separate website for mobile or change the <Doctype> or <html>. Is it possible to insert a script that changes the <Doctype> and <html> tags if a website is accessed via a mobile?
The most obvious tool would be SQL Profiler. It will monitor every SQL statement, and thus every data change, that gets sent to the server and show you metrics about that statement, the account under which the statement was executed and a host of other pieces of information and it comes free with most SQL Server versions. If you only want to see data changes, you can add filters to only show Insert, Update and Delete statements.
If what you are trying to do is compare two databases to see what data is different between them, then I'd recommend something like Red-Gate's Data Compare (no I do not work for them). It is not free but invaluable for this type of column value by column value comparison.
-4114670 0another approach
protected void Page_Load(object sender, EventArgs e) { List<string> list = new List<string>(); list.Add("Bread"); list.Add("Cheeze"); list.Add("Wine"); list.Add("Beer"); list.Add("Waffles"); GridView1.DataSource = list; GridView1.DataBind(); GridView1.Columns.Add(new BoundField()); }
-37047991 0 pusher realtime user online status through webhooks I am working on an android app where I have done some realtime applications using pusher. I read about pusher webhooks and I couldn't quite understand the concept when I read it Here . I want to implement the online status to my contacts and I read about it that it can be done with webhooks here. Please can anyone explain the concept and usage of webhooks and how can I implement online status using it.
-30426727 1 How to avoid program freezing when connecting to serverI have a little script which filters those domain names which are not registred yet. I use pywhois module. The problem is that it suddenly freeze and do nothing after several (sometimes hundreds) of requests. I think it is not a ban because I can run the program right after freeze and it works.
I would like to avoid this freezing. My idea is to count runtime of the function and if the time cross some line (for example 10 seconds) it repeats the code.
Do you have any advice how to avoid the freezing? Or the better way to check domains?
Here is the code:
for keyword in keywords: try: details = pythonwhois.get_whois(keyword+'.com') except Exception as e: print e continue if 'status' not in details.keys(): print 'Free domain!' print keyword
-11087496 0 How to pick out/trim part of a string using Shell I am trying to trim this, which is stored in a variable called $line.
[2012-06-18 10:37:09,026 (there is a lot of text after this, i just cut it out) I am new to shell scripting and this is the code that i have
errortime= $line | cut -c2-10; it is giving me an error, what is the correct code to pull the date out of the variable $line.
-40225978 0 how to connect SQL server db with windows authentication from eclipse db perspectiveHow to connect SQL server db 2008 with windows authentication from eclipse db perspective.
I don't have permission to put sqlserver .dll file on java library path or system 32 or even to set path to machine.
So I try to do that using some modification on eclipse.ini file. I try to add -Djava.library.path="sql server.dll" on eclipse.ini after -vm line but still it is throwing driver is not configured for Integrated Security.
-11713855 0Found the answer:
In Default.aspx, I needed to register the control by name rather than by namespace.
<%@ Register TagPrefix="a" Namespace="nestedcontroltest" Assembly="nestedcontroltest" %> Needs to be changed to
<%@ Register TagPrefix="a" TagName="MyControl" Src="~/MyControl.ascx" %> And then the control gets initialized properly, even when it's in the repeater. Perhaps a bug in ASP.net, or perhaps I needed to use the full assembly name? Regardless, thanks for all your help guys.
-13377784 0 Can't find the file path which created by myself in android source codeI am testing something.
I created assets folder in packages/apps/Camera/ and added the test.txt file in the folder.
But when I accessed the file in the onCreate() method according the following code fragment, I found I can't get the file.
File file = new File("/assets/test.txt"); BufferedReader reader = null; try { Log.v("jerikc","read the file"); reader = new BufferedReader(new FileReader(file)); String tempString = null; int line = 1; while ((tempString = reader.readLine()) != null) { Log.v("jerikc","line " + line + ": " + tempString); line++; } reader.close(); } catch (IOException e) { Log.v("jerikc","exception"); e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } The log were :
V/jerikc (3454): read the file
V/jerikc (3454): exception
I think I add the wrong path.("/assets/test.txt") . So what's the right path?
Some other informations:
Where my real code is a Util Class, there isn't the context. If I add the context, the code structure will have a big change.
Thanks.
-24074638 0 XML DTD parent object same with child objectFor an example. inside my xml
<?xml version="1.0"?> <!DOCTYPE expression SYSTEM "task3-1.dtd"> <expression> <left-bracket>(</left-bracket> <expression> <left-bracket>(</left-bracket> <expression> <number>24</number> <operation>+</operation> <number>24</number> </expression> <right-bracket>)</right-bracket> <operation>*</operation> <number>5</number> </expression> <right-bracket>)</right-bracket> <operation>-</operation> <number>6</number> </expression> When i try to run the dtd, it's always error that: The element "expression" has invalid child element 'number'. List of possible elements expected: 'left-bracket'
<!ELEMENT expression (left-bracket+,right-bracket,operation,number+)> <!ELEMENT left-bracket (#PCDATA)> <!ELEMENT right-bracket (#PCDATA)> <!ELEMENT operation (#PCDATA)> <!ELEMENT number (#PCDATA)>
-9307014 0 Assign a value to a variable with DataStore fields value I need to declare a variable TeacherName that will receive its value from the DataStore field 'NameT'
var storeTeacher = new Ext.data.JsonStore({ id: 'IDstoreTeacher', url: 'teacher.php', method: 'POST', baseParams:{task: "TEACHERNAME", parametar: idTeacher}, root: 'rows', fields: [{name: 'NameT', type: 'string', mapping: 'teacher_name'}], autoLoad: true }); var TeacherName = NameT; But in Firebug I always get the following error message: "Uncaught ReferenceError: NameT is not defined"
-19463130 0 how to know how many object type="file" there are in a jspi'm created a form to upload images into a blob field of a mysql database.
In a servlet i get the imagine inside a type="file" field in a jsp page.
Part filePart = request.getPart("Name_of_the_FILE_fields"); Now i want to allow user to upload more images at the same time, so i put in my jsp page a lot of type="file" field.
I thought that i could do something like this
Part filePart[] =request.getParameterValues("Name_of_the_FILE_fields"); but of course this is not the right way to do it.
-8240048 0Short answer: You cannot: AFAIK, currently there is no way to do it from sqlalchemy directly.
Howerever, you can use sqlalchemy-migrate for this if you change your model frequently and have different versions rolled out to production. Else it might be an overkill and you may be better off generating the ALTER TABLE ... scripts manually.
The issue is that when a UIimageView is subclassed and called from the storyboard a different method is called for the init.
-(id)initWithCoder:(NSCoder *)aDecoder { // As the subclassed UIImageView class is called from storyboard the initWithCoder is overwritten instead of init NSLog(@"%s",__PRETTY_FUNCTION__); self = [super initWithCoder:aDecoder]; if (self) { [self setupView]; } return self; } This resolves the issue of the rounded profile view not being called.
-6625258 0 how do I build a Facelets site at build-time?I want to use Facelets to build a static HTML prototype. This prototype will be sent out to people who do not have a running web application server such as Tomcat. Is there some way to compile a Facelets site at build-time (using Ant etc) into a set of flat HTML files?
In the simplest case we have two facelets like this:
<!-- layoutFacelet.xhtml --> <ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets"> <ui:insert name="content" /> </ui:composition> <!-- implementationFacelet.xhtml --> <ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" template="layoutFacelet.xhtml"> <ui:define name="content"> HELLO WORLD </ui:define> </ui:composition> The output would be a single html (e.g. "implementationFacelet.output.html") like:
HELLO WORLD In other words, Facelets is running at build-time rather than render-time, in order to produce static flat-file prototypes.
-14210141 0 How to get the saved value form my custom form field type in joomla?I have created my custom form field for a module.However, it work will but when ever i get back to the module i don't know what is the previous value or the saved value, because i didn't make it selected there.
<?php // Check to ensure this file is included in Joomla! defined('_JEXEC') or die('Restricted access'); jimport('joomla.form.formfield'); class JFormFieldSlidercategory extends JFormField { protected $type = 'Slidercategory'; // getLabel() left out public function getInput() { $db = JFactory::getDBO(); $query = $db->getQuery(true); $query->select('id,title'); $query->from('#__h2mslider_categories'); $db->setQuery((string)$query); $messages = $db->loadObjectList(); $options =''; if ($messages) { foreach($messages as $message) { $options .= '<option value="'.$message->id.'" >'.$message->title.'</option>'; } } $options = '<select id="'.$this->id.'" name="'.$this->name.'">'. '<option value="0" >--select a category--</option>'. $options. '</select>'; return $options ; } } I need the function that return me the saved value.
-23202916 0 Characters not properly displayed in serial monitor in arduinoCan anyone tell me why the characters are not getting printed properly in the serial monitor of Arduino? I am pasting the arduino code.
#include <SoftwareSerial.h> #include <LiquidCrystal.h> // initialize the library with the numbers of the interface pins LiquidCrystal lcd(12,11,5,4,3,2); int bluetoothTx = 15; int bluetoothRx = 14; SoftwareSerial bluetooth(bluetoothTx, bluetoothRx); int incomingByte; void setup() { pinMode(53, OUTPUT); Serial.begin(9600); lcd.begin(16, 2); lcd.clear(); bluetooth.begin(115200); // The Bluetooth Mate defaults to 115200bps delay(320); // IMPORTANT DELAY! (Minimum ~276ms) bluetooth.print("$$$"); // Enter command mode delay(15); // IMPORTANT DELAY! (Minimum ~10ms) bluetooth.println("U,9600,N"); // Temporarily Change the baudrate to 9600, no parity bluetooth.begin(9600); // Start bluetooth serial at 9600 lcd.print("done setup"); } void loop() { lcd.clear(); Serial.print("in loop"); //Read from bluetooth and write to usb serial if(bluetooth.available()) { Serial.print("BT here"); char toSend = (char)bluetooth.read(); Serial.print(toSend); lcd.print(toSend); delay(3000); }delay(3000); } Can anyone take a look into it. It does not print the character that I provide instead it prints something else like 'y' with 2 dots on top etc. Tried almost all the available solution.
-38794707 0Use x.fill(1). Make sure to return it properly as fill doesn't return a new variable, it modifies x
Is it possible to include the execution time of the just finished process - the output of the 'time' command - into the command prompt? We use zsh on linux and bash (msys) on windows machines so it would be nice to know how to do it in both.
-35956089 0I had the same problem. I solved it using Auth:login($array). Change your code to
public function postLogin(Request $request) { $this->validate($request, [ 'email' => 'required|email', 'password' => 'required' ]); $data = $request->input(); if(Auth::login($data)){ return redirect('/dashboard'); } return redirect()->back()->with(['fail' => 'Could not Login']); }
-20259706 0 You could easily put the lazy load logic within the viewmodel that holds your PImage1 property. Your property would need to return an ImageSource.
private ImageSource _source; public ImageSource PImage1 { get { if (_source == null) { using (var storage = IsolatedStorageFile.GetUserStoreForApplication()) { if (storage.FileExists("Image.jpg")) { var bitmap = new BitmapImage(); bitmap.SetSource(storage.OpenFile("Image.jpg", FileMode.Open)); _source = bitmap; return _source; } } LoadImage(); } return _source; } set { _source = value; OnPropertyChanged("PImage1"); } } Inside the LoadImage method, you'll make a request to get your image, save it to local storage, and then set the PImage1 property. Make sure to set the property on the UI thread
private void LoadImage() { // make a request to get the image. // Use your flavor of choice, WebRequest, HttpClient, WebClient Stream image = GetImageFromMyFavoriteHttp; using (var storage = IsolatedStorageFile.GetUserStoreForApplication()) { using (var file = storage.CreateFile("Image.jpg")) { image.CopyTo(file); } } Deployment.Current.Dispatcher.BeginInvoke(() => { var bitmap = new BitmapImage(); bitmap.SetSource(image); Image = bitmap; }); }
-31127333 0 You can copy the original list by slicing it:
a = [1, 2, 3] b = a[:] Or using the built in list list() funtion:
b = list(a) You could also use list comprehension in place of your nested for loops:
b = [[i if i else 1 for i in j] for j in a]
-2522163 0 Referencing a javascript file from a different domain is no problem. This is not cross site scripting, it's simply a cross site HTTP request. This is used a lot, e.g. by Google's JavaScript API Loader.
-36835788 0 Webdesign: Wrapping table suppresses scrollbars in IE 11 and FirefoxWe have to get a legacy web application to run in Internet Explorer 11 and Firefox. The application does not set any doctype and therefore sends both browsers into quirks mode.
We have a table that needs to be scrollable, which is embedded in a div with overflow: auto. This works on its own, but our web application embeds this div again in a table and wraps the table with another two divs. See the fiddle here:
https://jsfiddle.net/Tim_van_Beek/y7hsp1zp/3/
(Please use IE 11 or Firefox, the page does not work in Chrome at all.)
The wrapping table (the first -node in the HTML tree) seems to suppress the scrollbars. They reappear when one removes it. So while this structure does not have scrollbars (see fiddle above):
<div style="overflow: hidden;..."> <div ...> <table width="auto" height="auto" cellspacing="0" cellpadding="0"> <tbody> <tr> <td width="100%" height="100%" align="left" valign="top"> <div style="overflow: auto;"> ...table data to be scrolled ...this one does (remove the table, tbody, tr and td tags):
<div style="overflow: hidden;..."> <div ...> <div style="overflow: auto;"> ...table data to be scrolled It would seem that one needs to format the table in a certain way to get it to display scrollbars again (or rather: not suppress the scrollbars of its child node), any suggestions?
We cannot simply remove the table from our application without compromising the rest of the layout, but we can add/modify css at will.
-23713810 0you need to change this
<input type="hidden" name="id" value='<?php $id?>'> to
<input type="hidden" name="id" value='<?php echo $id?>'> (or)
<input type="hidden" name="id" value='<?=$id?>'>
-17942533 0 $_SESSION['userName'] = 'oneUser'; $activities = array(); $activityKeys = array('ID','name','spaces','date'); function getActivities() { global $activities,$activityKeys; $activities = array(); $contents = file('activity.txt'); foreach($contents as $line) { $activity = explode(':',$line); $data = array_combine($activityKeys,explode(',',$activity[0])); $users = isset($activity[1]) ? array_filter(explode(',',trim($activity[1]))) : array(); $activities[$data['ID']] = compact('data','users'); } } getActivities(); function userInActivity($activityID) { global $activities; return in_array($_SESSION['userName'],$activities[$activityID]['users']); } function saveActivities() { global $activities; $lines = array(); foreach($activities as $id => $activity) { $lines[$id] = implode(',',$activity['data']).':'.implode(',',array_filter($activity['users'])); } return file_put_contents('activity.txt',implode("\r\n",$lines)) !== false; } function bookActivity() { global $activities; if(isset($_POST['book'])) { $unbook = false; $bookID = intval($_POST['book']); if($bookID < 0) { //If a negative ID has been submitted, that means we are "unbooking" $unbook = true; $bookID = abs($bookID); //Set the ID back to the normal, positive value } if($unbook) { $users = $activities[$bookID]['users']; $userKey = array_search($_SESSION['userName'],$users); array_splice($activities[$bookID]['users'],$userKey,1); } else { $activities[$bookID]['users'][] = $_SESSION['userName']; } saveActivities(); } } bookActivity(); function activityList($form=true) { global $activities; if($form === true) echo '<form action="" method="post">'; ?> <table> <thead> <tr> <?php $firstKey = @array_shift(array_keys($activities)); foreach(array_keys($activities[$firstKey]['data']) as $index => $column) { echo '<th>'.$column.'</th>'; } ?> <th></th> </tr> </thead> <tbody> <?php foreach($activities as $activity) { echo '<tr>'; $id = $activity['data']['ID']; $activity['data']['spaces'] = $activity['data']['spaces']-count($activity['users']); foreach($activity['data'] as $item) { echo '<td>'.$item.'</td>'; } $booked = userInActivity($id,$_SESSION['userName']); $buttonText = $booked ? 'Unbook' : 'Book'; $val = $booked ? -$id : $id; echo '<td><button type="submit" name="book" value="'.$val.'">'.$buttonText.'</button></td>'; echo '</tr>'; } ?> </tbody> </table> <?php if($form === true) echo '</form>'; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Activities</title> </head> <body> <?php activityList(); ?> </body> </html>
-23033073 0 Queue is an interface not a class. LinkedList is an implementation of Queue interface.
You can think it like this.
Animal a = new Cat() Animal b = new Dog() Animal c = new Cow() a,b and c are all animals. But they are all different kind of animals.
There are other implementation of Queue interface like ArrayBlockingQueue and PriorityQueue. They all implement Queue interface but do things diffferently inside. http://docs.oracle.com/javase/7/docs/api/java/util/Queue.html http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html
You can think it like this. Animal a = new Cat() Animal b = new Dog() Animal c = new Cow()
-3404654 0For this problem you can use the STL's transform method to solve it:
std::string str = "simple"; std::transform(str.begin(), str.end(), str.begin(), std::tolower);
-39998537 0 Most appropriate way to store/retrieve User Input in a eCommerce iOS application? I'm a bit confused with Sqlite, Core Data, NSUserDefaultsand PropertyList. I know what is what, but not a very clear idea of about where to appropriately use them.
I know that there are lots of tutorials, but I'm good at learning through situation based understanding. So kindly do help me to understand this in the situation that I'm facing right now and to make use of the available options wisely.
I'm working on an ECommerce iOS (native) application, where I'm highly dependent on API's for data display. Now I'm in need of recording user's review for a product and send it over through an API.
ie. I have three components, rating title, rating value(for that title) and another rating title ID. I'm defining with an example, I need to store multiple rows with details,
Components Data to be stored **Title** - Quality | Value | Price | | **Rating** - 2 | 3 | 1 | | **TitleID** - 10 | 11 | 12 Like this, there will be so many entries, i.e, the number of components differs for various users, for some users, there might be more than three components, which must be saved & send through an API. So how should I save these data? which is the RIGHT way to save these data temporarily?
You can use any YAML parsing library, look here for example.
-33712033 0 the formulaire html and php/pdocan someone help me please I search from a week and the page post Notice: Undefined index: username in C:\Program Files\EasyPHP-DevServer-14.1VC9\data\localweb\test.php on line 17
Notice: Undefined index: password in C:\Program Files\EasyPHP-DevServer-14.1VC9\data\localweb\test.php on line 19
Notice: Undefined index: email in C:\Program Files\EasyPHP-DevServer-14.1VC9\data\localweb\test.php on line 21
and i don't find the problem in the code and please explaine i want to learn thank you
'<form action="test.php" method="post"> <input placeholder="username" type="text" name="username" ></input> <input placeholder="password"type="password" name="password" ></input> <input placeholder="email"type="email" name="email" ></input> <input type="submit" value="OK"/></input> </form> <?php $dsn = 'mysql:dbname=guyideas;host=localhost'; $user = 'root'; $password = ''; $dbh = new PDO($dsn, $user, $password); $username = $_GET['username']; $password = $_GET['password']; $email = $_GET['email']; $stmt = $dbh->exec('INSERT INTO `guyideas`.`users` (`username`, `password`, `email`) VALUES ("'.$username.'", "'.$password.'","email");'); ?>'
-25836757 0 How can I configure my Grunt.js file to copy a directory without a particular subdirectory during the build? Given that the Gruntfile is located in parent/aurora/Gruntfile.js,
I'd like to configure Grunt to do the following when the build command is executed:
https://github.com/antonpug/aurora/blob/master/Gruntfile.js
-9063466 0Luca Bolognese has written a great series of Write Yourself a Scheme in 48 Hours in F# where he used FParsec for parsing. The full source code with detailed test cases are online here.
The most relevant post is 6th one where he talked about parsing a simple Lisp-like language. This language is closer to JavaScript than to C just so you know.
Current series on his blog is parsing lambda expressions in F# (using FParsec) which could be helpful for you too.
-8818569 0 why such a difference in file contents C#My intention is to write a byte[] to a file. Code snippet is below:
byte[] stream = { 10, 20, 30, 40, 60 }; for (int i = 0; i < 2; i++) { FileStream aCmdFileStream = new FileStream(@"c:\binarydata.txt", FileMode.Append, FileAccess.Write, FileShare.None); StreamWriter aStreamWriter = new StreamWriter(aCmdFileStream); for (int ii = 0; ii < stream.Length; ii++) { aStreamWriter.Write(stream[ii]); aStreamWriter.WriteLine(); aStreamWriter.BaseStream.Write(stream,0,stream.Length); } aStreamWriter.Close(); } Output of this code snippet
(< (< (< (< (<10 20 30 40 60 (< (< (< (< (<10 20 30 40 60 When StreamWriter.Write() is used it dumps the values which are stored in array. But StreamWriter.BaseStream.Write(byte[],int offset, int length), the values are totally different. What is the reason for this?
Is it possible to simply do:
git add . That way you don't need to specifically reference the filenames that may have spaces (but will stage everything)
-36779978 0Well, it tries to link a static library into a dynamic one, and that static library (/opt/lib/python-3.5/lib/libpython3.5m.a) isn't suitable for that (compiled w/o -fPIC what makes it impossible to use it in a shared library). recompile that library with the flag (or simply supply one properly compiled) and re-try with Blender BPY.
I've just checked, Ubuntu-14.04 didn't have python-3.5 in the official repos, but there's a bunch of dedicated PPAs. But since it's the end of April of 16, it'd better to switch your apt sources.list to Xenial and update the system to the next LTS, if you feel brave, or just python if you don't :)
-25654501 0 URL redirection using powerdns and lua scriptingI am building an internal whitelist browsing filter server for a business. It is 95% operational. PowerDNS intercepts the DNS request and the LUA script correctly determines if the URL is whitelisted. The problem lies in the blacklist block page ... all I get is PAGE CANNOT BE DISPLAYED. The LUA script is getting to this line but the actual redirect never occurs:
return 0, {{qtype=pdns.A, content="1.2.3.4"}}
The 1.2.3.4 is where I put the actual IP of the PowerDNS server itself. Apache is not detecting that anything is getting to the server over port 80. If I navigate to 1.2.3.4 I do get the block page so I know apache is configured correctly and I have ServerAlias set to * to accept all domains. Thanks in advance.
I know you can put <% if %> statements in the ItemTemplate to hide controls but the column is still there. You cannot put <% %> statements into the LayoutTemplate which is where the column headings are declared, hence the problem. Does anyone know of a better way?
-40119204 0 With Javascript, How do I call a methods within another methodsvar hangman = { random: Math.floor((Math.random() * 3)), word_bank: ["hello", "bye", "hey"], select: "", guess: "", wins: 0, loss: 0, dashs: [], split: [], correct_letter: [], replace_dash: [], alphabet:['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' ], select_word: function() { this.select = this.word_bank[this.random]; }, dash: function() { for (var i = 0; i < this.select.length; i++) { if (this.select[i] == " ") { this.dashs.push(" "); } else { this.dashs.push("_"); } } }, split: function() { this.split = this.select.split(""); }, correct_i: function() { for (var i = this.select.length - 1; i >= 0; i--) { if (this.split[i] == this.guess) { this.correct_letter.push(i) } } }, replace_dash: function(){ for (var i = 0; i < this.correct_letter.length; i++) { this.dash[this.correct_letter[i]] = this.guess; } }, board_set: function(){ this.select_word(); this.dash(); this.split(); this.correct_letter = []; this.replace_dash = []; }, play_game: function(){ this.board_set(); console.log(hangman.dashs); console.log(hangman.split); var alphabet = this.alphabet; var gameboard = $("#game"); gameboard.html("<p>Game Board</p>" + this.dashs.join(" ")); document.onkeyup = function(e){ this.guess = String.fromCharCode(e.keyCode).toLowerCase(); if (alphabet.indexOf(this.guess) >= 0) { this.correct_i(); this.replace_dash(); console.log(correct_i); console.log(replace_dash); gameboard = $("#game"); gameboard.html("<p>Game Board</p>" + this.dashs.join(" ")); } } } }; hangman.guess = "e"; Within the play_game() I am trying to call the other methods within this method, but it keeps saying that the methods I am calling are not defined. I have tried to do:
hangman.correct_i(); hangman.replace_dash(); and that doesn't work either.
-18622073 0 Why jsf:binding attribute creates jsessionid cookie when used on input field?Why jsessionid cookie is created when I visit page that has jsf:binding attribute? If I remove jsf:binding no cookie is created. I'd like to have my page cookieless. The backing bean is annotated with these two Spring annotations: @Controller and @Scope("request").
<div class="form-group #{!username.valid ? 'has-error' : ''}"> <label for="username" class="col-md-2 control-label"> #{i18n['signup.username.text']} </label> <div class="col-md-4"> <input type="text" class="form-control" jsf:id="username" jsf:binding="#{username}" jsf:value="#{signUpBean.username}" jsf:maxlength="#{signUpBean.USERNAME_MAXLENGTH}" placeholder="#{i18n['signup.username.placeholder.text']}"> <f:ajax event="change" render="username-message" /> </input> </div> <h:message for="username" id="username-message" styleClass="col-md-6 help-block" /> </div>
-32963059 0 [EDIT from generator to function]
You can try a function:
def check_answer(question, answer): while True: current_answer = input(question) if current_answer == answer: break print "Something wrong with question {}".format(question) return current_answer answerX = check_answer("Question about X?\n", "TrueX") answerY = check_answer("Question about Y?\n", "TrueY") answerZ = check_answer("Question about Z?\n", "TrueZ") Not sure if you want to keep the values, but if you need to tweak it, this should give you hints.
Results:
Question about X? "blah" Something wrong with question Question about X? Question about X? "blah" Something wrong with question Question about X? Question about X? "TrueX" Question about Y? "TrueY" Question about Z? "blah" Something wrong with question Question about Z? Question about Z? "blah" Something wrong with question Question about Z? Question about Z? "TrueZ" Edit per comment:
def check_answer(question, answers): while True: current_answer = input(question) if current_answer in answers: break print "Something wrong with question {}".format(question) return current_answer answerX = check_answer("Question about X?\n", ("TrueX", "TrueY")
-40945088 1 What does numpy.cov actually do I am new to python and to linear algebra and I have a question about covariance of a matrix.
I have a 21 by 2 matrix, where the first column represents the average score(from 0 to 10) of the video games released that year and second columns are years ranging from 1996 to 2016.
I was playing around with the data and I noticed that by doing np.cov(X) I got a very interesting graph. I will list the graph below. It is my understanding that covariance shows the dependence among the variables in a dataset, but will it be correct to state that based on this covariance graph we can say that the average score of the games rises as the years rise ?
Thanks.
-5532477 0 C# Datagridview Edit CellI'm trying to put the cursor and focus in the last row and a specific cell with the column named 'CheckNumber'. I thought I had it with this:
var c = dataGridView1.RowCount; DataGridViewCell cell = dataGridView1.Rows[c-1].Cells[0]; dataGridView1.CurrentCell = cell; dataGridView1.BeginEdit(true); but it keeps coming up with this error:
Index -1 does not have a value.
Can someone please point me in the right direction!? This is driving me nuts.
Thank you!
-39932204 0 ASP.NET Identity Fluent NHibernate bind the mappings:https://nhibernateidentity.codeplex.com/documentation In this docs is written:
First you need install the package:
PM> Install-Package NHibernate.Identity After you installed you need to bind the mappings:
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<IdentityUser>()) How and where? Can someone try to explain. I want to use Nhiberant with Identity
-16686055 0This is something that's usually done through the web server, so the answer depends on whether you're using Apache, Nginx, or something else. Here's how I do it with Nginx.
I typically have a directory in my site root called controllers. All of the files in controllers correspond to URL paths. For example:
/controllers/home.php ---> http://example.com/home /controllers/about.php ---> http://example.com/about /controllers/contact.php ---> http://example.com/contact Then I use the web server (Nginx) to direct the traffic (which is what it's built to do). So if Nginx gets a request for http://example.com/home, then it looks in the controllers directory for a file called home.php. If the file exists, then Nginx serves it up. If the file doesn't exist, then Nginx serves up some fallback page. Here's what the Nginx configuration looks like:
server { listen 80; server_name example.com; root /srv/example; index index.php; rewrite ^/(.*)/$ /$1 permanent; location / { try_files $uri $uri/ /controllers$uri.php?$args; location ~ \.php$ { try_files $uri /index.php; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi_params; } } }
-4836365 0 I think you may combine following examples:
Load on demand: https://demos.telerik.com/aspnet-ajax/combobox/examples/loadondemand/wcf/defaultcs.aspx
Related combo boxes: https://demos.telerik.com/aspnet-ajax/combobox/examples/functionality/multiplecomboboxes/defaultcs.aspx
Overview: http://www.telerik.com/help/aspnet-ajax/combo_loadondemandoverview.html
I have a list of vectors, like this:
{x = 7, y = 0.}, {x = 2.5, y = 0.}, {x = -2.3, y = 0.}, {x = 2.5, y = 2.7}, {x = 2.5, y = -2.7} How do I convert these to data I can plot? I've been trying with the "convert" function, but can't get it to work.
When I manually convert it to something like [[7, 0], [2.5, 0], [-2.3, 0], [2.5, 2.7], [2.5, -2.7]] it works, though there has to be an automatic way, right?
A little more info about what I'm doing if you're interested:
I have a function U(x,y), of which I calculate the gradient and then check where it becomes 0, like this:
solve(convert(Gradient(U(x, y), [x, y]), set), {x, y}); that gives me my list of points. Now I would like to plot these points on a graph.
Thanks!
-36555353 0If you re-used the application name (deleted the old application and created a new one with the same name) it could take up to 24 hours for the dns to be routed to the correct server. if you are going to do rapid create/delete/create cycles, you should use different application names so that you don't have to wait on DNS updates.
-35848093 0As others have mentioned, you cannot do this. But instead you can use ArrayList (or any other List) and where needed, convert it to simple array, like this:
ArrayList<String> arrayList = new ArrayList<>(); String strings[] = (String[])arrayList.toArray();
-11305473 0 When the View is bound to the Model:
If the View needs to change or you have multiple views a change to the Model will cause changes to all the Views bound to that Model.
From the View's perspective, the object it is bound to might not be that intuitive; when you need to add a properties and/or commands to the the object do you add those to the ViewModel and keep the 'original' properties in the Model or do you modify the Model?
Having a ViewModel gives you an extra abstraction between a single Model and multiple (versions of) Views
All in all it is just a guideline but be aware that what seems OK today might be not so great when you need to modify/update the application.
-8635880 0No, your code is not threadsafe assuming that the window handle (FWnd) is created in main (GUI) thread. A standard VCL approach is to call all GDI functions in GUI thread, via Synchronize or Queue methods of TThread class.
ggplot(all, aes(x=area, y=nq)) + geom_point(size=0.5) + geom_abline(data = levelnew, aes(intercept=log10(exp(interceptmax)), slope=fslope)) + #shifted regression line scale_y_log10(labels = function(y) format(y, scientific = FALSE)) + scale_x_log10(labels = function(x) format(x, scientific = FALSE)) + facet_wrap(~levels) + theme_bw() + theme(panel.grid.major = element_line(colour = "#808080")) And I get this figure
Now I want to add one geom_line to one of the facets. Basically, I wanted to have a dotted line (Say x=10,000) in only the major panel. How can I do this?
-23180238 0Have you tried
Class.forName("com.foo.Foo"); Edit: To invoke the static method, you will need to do something like:
Class clazz = Class.forName("com.foo.Foo"); Method method = clazz.getMethod("methodName", String.class); Object o = method.invoke(null, "whatever"); This will depend on your method and its parameters. See the reflection tutorial for more on this: http://docs.oracle.com/javase/tutorial/reflect/
-30933595 0$result[0] is probably not an object.
try using print_r to print the contents of that variable after json_decode.
-32144964 0The thing that you are trying to do is to access the /storage folder just without read write permissions which is required by laravel.
Using File Manager
One of the easy and basic ways to change the permissions is through File manager in cPanel. To change the permissions for a file or folder in cpanel, please do the following:
- Click File Manager
- Click the name of the file for which you would like to change the permissions.
- Select the Change Permissions link at the top right of the page.
- Select the permissions you would like to set for the file.
- Click Change Permissions
Using FTP
Connect to FTP. Go to the file and right click. Choose Permissions or Attributes or Properties (depends on your program).
Using SSH or a script
This can be done with chmod command.
From HostGator website which is most probably your hosting provider.
EDIT: The directory should have the recursive mode enabled. You are not just giving permissions to one directory, but you are giving it to each and every subdirectory that you find inside that folder. If you still see an error, please post last few errors from your logs.(If it's stored which might not be there).
-35488437 0Unfortunately not all of the various components' command line flags are modifiable when starting a GKE cluster. If you're just trying to run a one-off load test, you could manually modify the flags passed to the Kubelet on each node, but since that flag isn't even controllable by Kubernetes's Salt templates, there isn't even an option to control it with an environment variable.
The value was chosen due to performance limitations and will be drastically bumped up (to 100) in version 1.2 of Kubernetes, which is scheduled for release in March.
-8216644 0So that I understand, you have not yet built any ORM Entities? (CFC for each table)
If you have not, all you have to do is setup all your tables (use cfbuilder with a RDS connection to build your ORM CFC files)
Once you have all your tables referenced in ORM Persisted CFC files, you can do this with a cfquery tag and dbtype = "HQL" and return the data with QueryConvertForGrid()
Then just return the data you want to your cfgrid via json or directly on the page into the cfgrid tag.
-37001712 0This worked for me,(Using ShareIntent)
private void shareOnTwitter(){ Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND); shareIntent.setType("text/plain"); // shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Extra Subject"); shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "check this application"); // shareIntent.putExtra(Intent.EXTRA_STREAM, "Extra Stream"); PackageManager pm = context.getPackageManager(); List<ResolveInfo> activityList = pm.queryIntentActivities(shareIntent, 0); for (final ResolveInfo app : activityList) { //"com.twitter.android.PostActivity".equals(app.activityInfo.name) if ((app.activityInfo.name).contains("twitter")) { final ActivityInfo activity = app.activityInfo; final ComponentName name = new ComponentName(activity.applicationInfo.packageName, activity.name); shareIntent.addCategory(Intent.CATEGORY_LAUNCHER); shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); shareIntent.setComponent(name); context.startActivity(shareIntent); break; } } } Just call shareOnTwitter() in you btn OnClickListener()
I had this problem also but it is on win10.. After I have tried a lots of different solution from web .. Finally.. it worked to change connection string to fix this problem.. But I changed "Provider=MSDAORA.1" to "Provider=OraOLEDB.Oracle"
I encountered this error when trying to debug to run a web application after publishing from VS 2012 to IIS 7.5. After some hair pulling, I realised that the problem was the fact that I did not change the jquery script and signalr paths when deploying.
To solve the issue I had to add the virtual directory name ("TestingChat") to the path of the script tags for jquery and signalr.
E.g. From this:
<script src="Scripts/jquery-1.8.2.min.js" ></script> <script src="/signalr/hubs"></script> To
<script src="/TestingChat/Scripts/jquery-1.8.2.min.js" ></script> <script src="TestingChat/signalr/hubs"></script>
-6731072 0 SHAREPOINT 2007 LLISTS created by helpdesk.wsp I am given a task to make a feature that autogenerates a ticket ID for a list. However, I found out that the template used for the site is a helpdesk.wsp template. Now, I am having problems stapling the said feature to Service Requests because it is currently under LLISTS and not LISTS.
See attached image.
Can someone help me on this?
Thanks. janejanejane
-5470117 0 UPDATE MySQL using VB.NETI am using VB.NET with a MySQL database. I want to update this code to do it all in ONE SQL instead of THREE. Anyone know how?
Here's the code I'm using, works fine but too slow with multiple lines...
If count3 = "1" Then Dim myCommand As New MySqlCommand Dim myAdapter As New MySqlDataAdapter Dim SQL As String myCommand.Connection = conn myAdapter.SelectCommand = myCommand SQL = "UPDATE employees SET emprole1 = '" & val2 & "' WHERE emprole1 = '" & val1 & "'" myCommand.CommandText = SQL myCommand.ExecuteNonQuery() SQL = "UPDATE employees SET emprole2 = '" & val3 & "' WHERE emprole2 = '" & val2 & "'" myCommand.CommandText = SQL myCommand.ExecuteNonQuery() SQL = "UPDATE employees SET emprole3 = '" & val4 & "' WHERE emprole3 = '" & val3 & "'" myCommand.CommandText = SQL myCommand.ExecuteNonQuery() End If
-7692638 0 Can you use the Set<T>() operation:
try { db.SaveChanges(); } catch { db.Set<T>().Remove(obj); } ?
-4606140 0Merging all the arrays together isn't necessary. Use sort to get the correct index ordering for the elements in @x:
@sort_by_x = sort { $x[$a] <=> $x[$b] } 0 .. $#x; # ==> (0, 2, 1) Then apply that index ordering to any other array:
@x = @x[@sort_by_x]; @y = @y[@sort_by_x]; @z = @z[@sort_by_x];
-32926966 0 PHP rename() not working I am trying to rename a duplicate file name upon upload of a new file with the same name. Everything is working great except for that I am getting an error:
<b>Warning</b>: rename(./uploads/484360_438365932885330_1444746206_n.jpeg,): No such file or directory in <b>/home/unisharesadmin/public_html/wp-content/themes/blankslate/check_duplicate_img.php</b> on line <b>36</b><br /> Despite confirming that the directory exists and that the file and directory are both writeable, PHP is still throwing this error. I have consulted countless threads on here already and none of them seem to help, as I cannot find any path or string error with my file path.
Thank you for any help you can provide!
Cheers Colin
Code:
<? require_once('../../../wp-config.php'); function RandomString($length = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } return $randomString; } $this_img = $_REQUEST['filename']; $path = './uploads/' . $this_img; $img_array = explode(".", $this_img); $new_img = RandomString() . '.' . $img_array[sizeof($img_array)-1]; $new_path = './uploads/' . $new_img; if (file_exists($path)) { query_posts('posts_per_page=-1'); while(have_posts()) { the_post(); if( strpos(get_post_meta(get_the_id(), 'imgurl1')[0], $this_img) !== false ) { //echo "this posts url1 matches, so update the existing files name and the posts refrence to it"; echo is_writeable("./uploads"); rename($path, $newpath); //echo update_post_meta(get_the_id(), 'imgurl1', get_template_directory_uri() . '/uploads/' . $new_img); } else if( strpos(get_post_meta(get_the_id(), 'imgurl2')[0], $this_img) !== false ) //this posts url2 matches { echo "this posts url2 matches, so update the existing files name and the posts refrence to it"; //rename($path, $newpath); //echo update_post_meta(get_the_id(), 'imgurl2', get_template_directory_uri() . '/uploads/' . $new_img); } } } else { echo 0; } ?>
-32861574 0 How to use file_get_contents on loop? I'm trying to use file_get_contents on loop, in order to fetch JSON string from an URL continuously (every second). And i need to store the result into a javascript variable. Here was my approach, but i didn't get any result from this. My page showed me nothing but endless loading.
<?php set_time_limit(0); while(true) { $jsonContent=file_get_contents('http://megarkarsa.com/gpsjson.php'); echo $jsonContent; sleep(10); } ?> And here my javascript code.
setInterval(function(){ var jsonUpdPostData = <?php echo $jsonContent; ?>; }, 100); What should i do to make it work? Any suggestion will be appreciated.
-847428 0You should use the following syntax:
<ul> $orders: {order| <li>Order $order.OrderId$</li> }$ </ul> The documentation about this feature is really hard to find, I found some info here (search for the pipe symbol |).
-8183890 0No, only tokenizer=porter
When I specify tokenizer=icu, I get "android.database.sqlite.SQLiteException: unknown tokenizer: icu"
Also, this link hints that if Android didn't compile it in by default, it will not be available http://sqlite.phxsoftware.com/forums/t/2349.aspx
-9887374 1 Find the two longest strings from a list || or the second longest list in PYTHONI'd like to know how i can find the two longest strings from a list(array) of strings or how to find the second longest string from a list. thanks
-39330493 0Can you try this:
RewriteEngine On RewriteCond %{THE_REQUEST} "^GET\s(.+)\s(.+)\sHTTP/1.1" RewriteRule ^ "%1\%20%2" [PT] Tested on Apache 2.4.6.
-16815474 0 Why did parseFrom() function hang using protobuf in java socket?I just want to create echo server/client using protobuf and java.
I tested with protobuf-java-2.4.1 and jdk1.7.
I wrote echo server code like below
// create server socket and accept for client connection. // ... link = servSock.accept(); Person person = Person.parseFrom(link.getInputStream()); // blocking position person.writeTo(link.getOutputStream()); I think it is not necessary to note Person.proto.
The client code is only send Person object using socket input stream and receive echo Person object.
// socket connect code was omitted. Person person = Person.newBuilder().setId(1).setName("zotiger").build(); person.writeTo(echoSocket.getOutputStream()); person = Person.parseFrom(echoSocket.getInputStream()); But server was blocked in parseFrom function when the server and client both run.
I found if i use writeDelimitedTo() and parseDelimitedFrom(), then that is ok. I don't understand why the writeTo() and parseFrom() function does not working.
Why did the server blocking in there?
Is it necessary to send some end signal from client side?
-17201906 0 Use of different object properties for same functionIn the avatar generator I'm working on I have several button events that do the same thing but with different body parts. I don't want to have different functions doing the same thing, so I want to use one function for all body parts.
Line 14 below uses the object propery 'AvGen.eyes.currEyesNr', but instead I want to use the one for the clicked button. What can I put in as an argument and how can I use the parameter in the function to be able to use the correct object parameter?
1. prevBodyBtn.on('click', function(){ 2. if (AvGen.theBody.currBodyNr > 0) { 3. changePart(-1); 4. } 5. }); 6. 7. prevEyesBtn.on('click', function(){ 8. if (AvGen.eyes.currEyesNr > 0) { 9. changePart(-1); 10. } 11. }); 12. 13. function changePart(direction) { 14. AvGen.eyes.currEyesNr += direction; // <-- this is now always 'AvGen.eyes.currEyesNr' but should be dynamic 15. 16. var body = AvGen.theBody.bodies[AvGen.theBody.currBodyNr], 17. eyes = AvGen.eyes.eyes[AvGen.eyes.currEyesNr], 18. nose = AvGen.nose.noses[AvGen.nose.currNoseNr]; 19. mouth = AvGen.mouth.mouths[AvGen.mouth.currMouthNr]; 20. 21. AvGen.addSVG(body, eyes, nose, mouth); 22. }
-21142228 0 You could use
socketl = new ServerSocket(port, 0); or even
socketl = new ServerSocket(port);
-13596956 0 I used a variation of Shawn's solution.. it looks nice on the Emulator.
1) Decide on the # of columns, I chose 4
2) Set the Column Width
float xdpi = this.getResources().getDisplayMetrics().xdpi; int mKeyHeight = (int) ( xdpi/4 ); GridView gridView = (GridView) findViewById(R.id.gridview); gridView.setColumnWidth( mKeyHeight );// same Height & Width 3) Setup the image in your adapter's getView method
imageView = new ImageView( mContext ); // (xdpi-4) is for internal padding imageView.setLayoutParams(new GridView.LayoutParams( (int) (xdpi-4)/2, (int) (xdpi-4)/2)); imageView.setScaleType( ImageView.ScaleType.CENTER_CROP ); imageView.setPadding(1, 1, 1, 1); 4) Layout
<?xml version="1.0" encoding="utf-8"?> <GridView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/gridview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:numColumns="4" android:verticalSpacing="0dp" android:horizontalSpacing="0dp" android:gravity="center" android:listSelector="@null" /> <!-- android:columnWidth="90dp" Specified in code android:stretchMode="columnWidth" no noticable change --> That's it.
-19013767 1 Using python docx to create a document and need to modify the paragraph style and save itI am trying to modify "Text Body" style for paragraph in word 2010 so that the Below paragraph spacing is much less. But when I change that value it will not save it so that when I reopen word the modifications are gone.
The reason I want to save it is that when the document gets created using python docx and I pass the paragraph function the style it will be with the new values. Anyone have any ideas about this?
-5833681 0Read up on thing called "Closure Tables". It might make few things easier for you.
-21249347 0For the $_POST variables use syntax as $_POST['your variable name']
I corrected your code as below:
<form action="test.php" method="post"> First Name: <input type="text" name="fname"><br> Last Name: <input type="text" name="lname"><br> E-mail: <input type="text" name="email"><br> <input type="hidden" name="submitted" value="1"> <input type="submit"> </form> <?php //If form was submitted if ($_POST['submitted']==1) { $errormsg = ""; //Initialize errors if ($_POST['fname']){ $fname = $_POST['fname']; //If fname was entered } else{ $errormsg = "Please enter first name"; } if ($_POST['lname']){ $lname = $_POST['lname']; //If lname was entered } else{ if ($errormsg){ //If there is already an error, add next error $errormsg = $errormsg . ", last name"; } else{ $errormsg = "Please enter last name"; } } if ($_POST['email']){ $email = $_POST['email']; //If email was entered } else{ if ($errormsg){ //If there is already an error, add next error $errormsg = $errormsg . " & email"; }else{ $errormsg = "Please enter email"; } } } if ($errormsg){ //If any errors display them echo "<div class=\"box red\">$errormsg</div>"; } //If all fields present if ($fname && $lname && $email){ //Do something echo "<div class=\"box green\">Form completed!</div>"; } ?>
-20537190 0 how to rectify "java.lang.NoClassDefFoundError" while using log4j in our class? I have downloaded "apache-log4j-2.0-beta9-bin" from http://logging.apache.org/log4j/ and extaracted it and added to my project. Then I wrote a configuration properties file in my project as below
# Define the root logger with appender file log = X:\logs log4j.rootLogger = DEBUG, FILE # Define the file appender log4j.appender.FILE=org.apache.log4j.FileAppender log4j.appender.FILE.File=${log}/log.out # Define the layout for file appender log4j.appender.FILE.layout=org.apache.log4j.PatternLayout log4j.appender.FILE.layout.conversionPattern=%m%n and I wrote sample program to test it, the sample program is shown below.
public class Log4jExample { static Logger log = Logger.getLogger(Log4jExample.class.getName()); public static void main(String[] args)throws IOException{ log.debug("Hello this is an debug message"); log.info("Hello this is an info message"); } } While executing it am receiving this error, please advice.
java.lang.NoClassDefFoundError: org/apache/flume/Event at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:186) at org.apache.logging.log4j.core.config.plugins.PluginManager.decode(PluginManager.java:241) at org.apache.logging.log4j.core.config.plugins.PluginManager.collectPlugins(PluginManager.java:152) at org.apache.logging.log4j.core.config.plugins.PluginManager.collectPlugins(PluginManager.java:130) at org.apache.logging.log4j.core.pattern.PatternParser.<init>(PatternParser.java:116) at org.apache.logging.log4j.core.pattern.PatternParser.<init>(PatternParser.java:102) at org.apache.logging.log4j.core.layout.PatternLayout.createPatternParser(PatternLayout.java:183) at org.apache.logging.log4j.core.layout.PatternLayout.<init>(PatternLayout.java:115) at org.apache.logging.log4j.core.layout.PatternLayout.createLayout(PatternLayout.java:219) at org.apache.logging.log4j.core.config.DefaultConfiguration.<init>(DefaultConfiguration.java:51) at org.apache.logging.log4j.core.LoggerContext.<init>(LoggerContext.java:63) at org.apache.logging.log4j.core.selector.ClassLoaderContextSelector.locateContext(ClassLoaderContextSelector.java:217) at org.apache.logging.log4j.core.selector.ClassLoaderContextSelector.getContext(ClassLoaderContextSelector.java:114) at org.apache.logging.log4j.core.selector.ClassLoaderContextSelector.getContext(ClassLoaderContextSelector.java:81) at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:83) at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:34) at org.apache.logging.log4j.LogManager.getContext(LogManager.java:200) at org.apache.log4j.Logger$PrivateManager.getContext(Logger.java:61) at org.apache.log4j.Logger.getLogger(Logger.java:39) at log4j.Log4jExample.<clinit>(Log4jExample.java:16) Caused by: java.lang.ClassNotFoundException: org.apache.flume.Event at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:423) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:356) ... 21 more Exception in thread "main" Java Result: 1
-17010055 0William Pugh, one of the authors of "JSR-133: Java Memory Model and Thread Specification" maintains a webpage about the memory model here:
http://www.cs.umd.edu/~pugh/java/memoryModel/
The complete JSR-133 can be found here:
http://www.cs.umd.edu/~pugh/java/memoryModel/jsr133.pdf
Also relevant is the Java Language Specification, Section 17.4 Memory Model:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4
-5639734 0Stumbled upon this question and thought I would offer an alternative. If you run into trouble with popup blockers, you can use plain old HTML to launch a url in a new window/tab. You won't have as much control over that is displayed (scrollbars, toolbar, etc), but it works even if javascript is disabled and is 508 compliant:
<a href="http://www.google.com/" target="_blank">Open new window</a> You can read more about the various target attributes here: https://developer.mozilla.org/en/HTML/Element/a
-16035475 0 Removing items from a dataset that have too few mentionsI am beginning R user and I have a question about a problem I encountered:
After some data cleaning, I needed to reduce the list to a more manageable size. Since I am interested in contributors who have donated more than once, I have decided to try to limit the size of the dataset like that.
The dataset is loaded as "cont"
My intention:
Map frequencies of mentions:
> table(cont$contributor_name) -> FreqCon > subset(FreqCon,Freq>4) -> FMI Insert an extra column as cont[,43] with name "include" that would say TRUE or FALSE for whether I should subset it
for(i in 1:dim(FMI)[1]){ + ifelse(cont[i,11] %in% FMI[,1],cont[i,43] <- TRUE, cont[i,43] <- FALSE) } Subset the dataset based on cont$include
I hope that is all relevant information. I am happy to provide more info if needed! Also:cont[,11] = cont$contributor_name
THE PROBLEM: Currently, R is working very hard, but does not seem to change anything in the column. I am confused as to what I am doing wrong, since I am not getting any warnings() or Errors.
Maybe I am trying to reinvent the wheel so any way of accomplishing what I set out to do would be much appreciated!
-15207852 0Take a look at these UIView methods. You subclass can override these methods and do what you require.
touchesBegan:withEvent:, touchesMoved:withEvent:, touchesEnded:withEvent:, touchesCancelled:withEvent:
I am writing a program which works with input/output and I have a problem with two functions in my code: copyText and print. They don't work at all and I can't understand the source of my problem. I will really appreciate any help. Thanks!
#include <iostream> #include <fstream> #include <cctype> using namespace std; void initialize(int&, int[]); void copyText (ifstream&, ofstream&, char&, int[]); void count(char, int[]); void print(ofstream&, int, int[]); int main() { int line; int letter[26]; char ch; ifstream infile; ifstream outfile; infile.open("input.txt"); outfile.open("output.txt"); initialize(line, letter); infile.get(ch); while(infile) { copyText(infile, outfile, ch, letter); line++; infile.get(ch); } print (outfile, line, letter); infile.close(); outfile.close(); return 0; } void initialize(int& loc, int list[]) { loc = 0; for (int i =0; i <26; i++) list[i] = 0; } void copyText(ifstream& in, ofstream& out, char& ch, int list[]) { while (ch != '\n') { out << ch; count (ch, list); in.get(ch); } out << ch; } void count(char ch, int list[]) { ch = toupper(ch); int index = static_cast<int>(ch)-static_cast<int>('A'); if (0 <= index && index < 26) list[index]++; } void print (ofstream& out, int loc, int list[]) { out << endl<< endl; out << " The number of lines is "<<loc <<endl; for (int i = 0; i<26; i++) out << static_cast<char>(i+static_cast<int>('A')) << "count = " <<list[i] << endl; }
-28943159 0 If you are trying it on same field you can try to build the query like this replace the 'reference' with your field name
reference:TSP AND reference:LAE AND NOT reference:N133
and for different fields with other combinations
reference:TSP AND name:Test AND NOT metadata:Superseded
reference:(TSP AND LAE) AND name:Test AND NOT metadata:Superseded
reference:(TSP AND LAE) AND name:(Test OR Wheel) AND NOT metadata:Superseded
reference:(TSP AND LAE) OR name:(Test OR Wheel) AND NOT metadata:Superseded
reference:(TSP AND LAE) OR name:(Test AND Wheel) AND NOT metadata:Superseded
For the disabled attribute I think it's the presence of the attribute that disables the element regardless of its value.
It guess one of the reasons could be to allow more values than just yes/no in the future. For instance, instead of visible=true/false, you can have visibility=visible/hidden/collapsed
-21205124 0 Log4j not workingI using common logging and jboss eap 6.2 in java application, log file is creating but empty and hibernate log also not working.
This is my jboss-deployment-structure.xml
<jboss-deployment-structure> <deployment> <exclusions> <module name="org.apache.commons.logging"/> <module name="org.apache.log4j"/> </exclusions> </deployment> <sub-deployment name="abc.war"> <exclusions> <module name="org.apache.log4j"/> <module name="org.apache.commons.logging"/> </exclusions> </sub-deployment> </jboss-deployment-structure> and this is my log4j.properties
log4j.rootLogger=DEBUG, FILE log4j.appender.FILE=org.apache.log4j.RollingFileAppender log4j.appender.FILE.File=c\:\\log\\eSocietySQLLog.log log4j.appender.FILE.ImmediateFlush=true log4j.appender.FILE.Threshold=debug log4j.appender.FILE.Append=true log4j.appender.FILE.MaxFileSize=10MB log4j.appender.FILE.MaxBackupIndex=5 log4j.appender.FILE.layout=org.apache.log4j.PatternLayout log4j.appender.FILE.layout.ConversionPattern=%d{HH:mm:ss,SSS} %-5p %c %n%m%C log4j.appender.FILE.DatePattern='.' yyyy-MM-dd-a and add JAVA_OPTS="$JAVA_OPTS -Dorg.jboss.as.logging.per-deployment=false" in standalone.conf of jboss eap 6.2.
-19926211 0 math.net DenseVectors vs DenseMatrix 1xn | nx1This is really simple stuff but, as I am a noob with math.net, I may need to be pointed in the right direction:
let a = new DenseVector([| 5.0; 2.0; 3.0; |]) let m = new DenseMatrix(3, 3, 1.0) let r = a * m let r2 = m * a results in:
> r;; val it : DenseVector = seq [10.0; 10.0; 10.0] > r2;; val it : DenseVector = seq [10.0; 10.0; 10.0] Matrix-Vector multiplication takes too much liberty here. I need to enforce proper dimensionality checks. Should I just work with DenseMatrix, creating 1xn, nx1 matrices? This basically makes Vectors and DenseVectors redundant in my case.
Okay, I solved my problem and would like to answer my own question. I figured it would be better for the other users here.
First, get the file here: http://www.JSON.org/json_parse.js
var geodata = json_parse("{{geodata|escapejs}}"); I just used escapejs: http://docs.djangoproject.com/en/dev/ref/templates/builtins/#escapejs
EDIT: Thanks to Ignacio Vazquez-Abrams. It was him that helped me in #python Freenode. Should have credited him when I made this post. I didn't know he was in Stackoverflow.
-27588019 0Manually adding all repositories will help:
{ "repositories": [ { "type": "package", "package": { "name": "fuel/auth", "type": "fuel-package", "version": "1.7.2", "dist": { "url": "https://github.com/fuel/auth/archive/1.7/master.zip", "type": "zip" }, "source": { "url": "https://github.com/fuel/auth.git", "type": "git", "reference": "1.8/develop" } } }, { "type": "package", "package": { "name": "fuel/email", "type": "fuel-package", "version": "1.7.2", "dist": { "url": "https://github.com/fuel/email/archive/1.7/master.zip", "type": "zip" }, "source": { "url": "https://github.com/fuel/email.git", "type": "git", "reference": "1.8/develop" } } }, { "type": "package", "package": { "name": "fuel/oil", "type": "fuel-package", "version": "1.7.2", "dist": { "url": "https://github.com/fuel/oil/archive/1.7/master.zip", "type": "zip" }, "source": { "url": "https://github.com/fuel/oil.git", "type": "git", "reference": "1.8/develop" } } }, { "type": "package", "package": { "name": "fuel/orm", "type": "fuel-package", "version": "1.7.2", "dist": { "url": "https://github.com/fuel/orm/archive/1.7/master.zip", "type": "zip" }, "source": { "url": "https://github.com/fuel/orm.git", "type": "git", "reference": "1.8/develop" } } }, { "type": "package", "package": { "name": "fuel/parser", "type": "fuel-package", "version": "1.7.2", "dist": { "url": "https://github.com/fuel/parser/archive/1.7/master.zip", "type": "zip" }, "source": { "url": "https://github.com/fuel/parser.git", "type": "git", "reference": "1.8/develop" } } }, { "type": "package", "package": { "name": "fuel/core", "type": "fuel-package", "version": "1.7.2", "dist": { "url": "https://github.com/fuel/core/archive/1.7/master.zip", "type": "zip" }, "source": { "url": "https://github.com/fuel/core.git", "type": "git", "reference": "1.8/develop" } } }, { "type": "package", "package": { "name": "fuel/docs", "type": "fuel-package", "version": "1.7.2", "dist": { "url": "https://github.com/fuel/docs/archive/1.7/master.zip", "type": "zip" }, "source": { "url": "https://github.com/fuel/docs.git", "type": "git", "reference": "1.8/develop" } } } ], "require": { "fuel/fuel": "dev-1.7/master" } }
-12889413 0id:
It will identify the unique element of your entire page. No other element should be declared with the same id. The id selector is used to specify a style for a single, unique element. The id selector uses the id attribute of the HTML element, and is defined with a "#".
class:
The class selector is used to specify a style for a group of elements. Unlike the id selector, the class selector is most often used on several elements.
This allows you to set a particular style for many HTML elements with the same class.
The class selector uses the HTML class attribute, and is defined with a "."
-23896055 0I have had this issue too, try removing the following from your CSS
background-attachment: fixed;
-25962925 0The Recurring Payments API is what you want. Specifically, Express Checkout would be for PayPal payments and Payments Pro (DoDirectPayment / PayFlow) would be for direct credit card processing without a PayPal account.
-30848914 0You have added the entry to root's crontab, while your Cloud SDK installation is setup for a different user (I am guessing ubu121lts).
You should add the entry in ubu121lts's crontab using:
crontab -u ubu121lts -e Additionally your entry is currently scheduled to run on the 0th minute every hour. Is that what you intended?
-38225269 0 DWARF reading not complete typesHow can I read a non complete types in DWARF dumps?
For example we have a derived class:
class Base { public: int Base_var1; int Base_var2; .... } class OtherClass : public Base { int OtherClass_var1; int OtherClass_var2; .... } OtherClass otherClass(); We compile this with GCC compiler and want to find all members of otherClass object. We get the next DWARF dump:
<1><20a>: Abbrev Number: 15 (DW_TAG_variable) <20b> DW_AT_name : otherClass <211> DW_AT_type : <0x131> <1><131>: Abbrev Number: 117 (DW_TAG_class_type) <132> DW_AT_name : OtherClass <133> DW_AT_declaration : 1 <134> DW_AT_sibling : <0x150> <2><135>: Abbrev Number: 45 (DW_TAG_member) <136> DW_AT_name : OtherClass_var1 <137> DW_AT_type : <0x12> <138> DW_AT_data_member_location: 2 byte block: 23 8 (DW_OP_plus_uconst: 8) ...... We have a variable otherClass, which have a type of 0x131. This type have DW_AT_declaration flag, which means that this is non complete type. Type at 0x131 have all members of it's main class (OtherClass_var1 and OtherClass_var2), but don't have any information about derived members.
If continue reading DWARF dump, then in some place we get this:
<1><500>: Abbrev Number: 150 (DW_TAG_class_type) <501> DW_AT_specification: <0x131> <502> DW_AT_byte_size : 2696 <503> DW_AT_containing_type: <0x560> <504> DW_AT_sibling : <0x36078> <2><135>: Abbrev Number: 45 (DW_TAG_member) <136> DW_AT_name : Base_var1 <137> DW_AT_type : <0x12> <138> DW_AT_data_member_location: 2 byte block: 23 8 ..... There is a definition for our base class and this definition have DW_AT_specification tag, which shows where to find a other part of this class (main part).
How can we correctly read this otherClass object? At this moment I have to store array of all types and when I get a DW_AT_declaration tag, I should go through array and find a type with specification to this type.
And how can I get a absolute address of derived members? We have a absolute address of variable otherClass. Then member OtherClass_var1 would have the same address as otherClass. Member OtherClass_var2 would have address of OtherClass_var1 plus a byte size of OtherClass_var1. But how can we calculate the address of derived members Base_var1 and Base_var2?
To link to a form you need:
Form2 form2 = new Form2(); form2.show(); this.hide(); then hide the previous form
-19262116 0-1006453 0I used documentMode instead of simply checking (if(document.querySelector)) to help me debug this problem further
That is one way. It's nice and simple, but a bit messy. You could get rid of the storyboard and on each tick, increment a local value by the tick interval and use that to set your time. You would then only have one time piece.
Or... A more elegant and re-usable way would be to create a helper class that is a DependencyObject. I would also just use a StoryBoard with a DoubleAnimation an bind the Storyboard.Target to an instance of the DoubleTextblockSetter. Set the storyboard Duration to your time and set the value to your time in seconds. Here is the DoublerBlockSetterCode.
public class DoubleTextBlockSetter : DependencyObject { private TextBlock textBlock { get; private set; } private IValueConverter converter { get; private set; } private object converterParameter { get; private set; } public DoubleTextBlockSetter( TextBlock textBlock, IValueConverter converter, object converterParameter) { this.textBlock = textBlock; this.converter = converter; this.converterParameter = converterParameter; } #region Value public static readonly DependencyProperty ValueProperty = DependencyProperty.Register( "Value", typeof(double), typeof(DoubleTextBlockSetter), new PropertyMetadata( new PropertyChangedCallback( DoubleTextBlockSetter.ValuePropertyChanged ) ) ); private static void ValuePropertyChanged( DependencyObject obj, DependencyPropertyChangedEventArgs args) { DoubleTextBlockSetter control = obj as DoubleTextBlockSetter; if (control != null) { control.OnValuePropertyChanged(); } } public double Value { get { return (double)this.GetValue(DoubleTextBlockSetter.ValueProperty); } set { base.SetValue(DoubleTextBlockSetter.ValueProperty, value); } } protected virtual void OnValuePropertyChanged() { this.textBlock.Text = this.converter.Convert( this.Value, typeof(string), this.converterParameter, CultureInfo.CurrentCulture) as string; } #endregion } Then you might have a format converter:
public class TicksFormatConverter : IValueConverter { TimeSpanFormatProvider formatProvider = new TimeSpanFormatProvider(); public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { long numericValue = 0; if (value is int) { numericValue = (long)(int)value; } else if (value is long) { numericValue = (long)value; } else if (value is double) { numericValue = (long)(double)value; } else throw new ArgumentException("Expecting type of int, long, or double."); string formatterString = null; if (parameter != null) { formatterString = parameter.ToString(); } else { formatterString = "{0:H:m:ss}"; } TimeSpan timespan = new TimeSpan(numericValue); return string.Format(this.formatProvider, formatterString, timespan); } public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } I almost forgot the TimespanFormatProvider. There is no format provider for timespan in Silverlight, so it appears.
public class TimeSpanFormatProvider : IFormatProvider, ICustomFormatter { public object GetFormat(Type formatType) { if (formatType != typeof(ICustomFormatter)) return null; return this; } public string Format(string format, object arg, IFormatProvider formatProvider) { string formattedString; if (arg is TimeSpan) { TimeSpan ts = (TimeSpan)arg; DateTime dt = DateTime.MinValue.Add(ts); if (ts < TimeSpan.FromDays(1)) { format = format.Replace("d.", ""); format = format.Replace("d", ""); } if (ts < TimeSpan.FromHours(1)) { format = format.Replace("H:", ""); format = format.Replace("H", ""); format = format.Replace("h:", ""); format = format.Replace("h", ""); } // Uncomment of you want to minutes to disappear below 60 seconds. //if (ts < TimeSpan.FromMinutes(1)) //{ // format = format.Replace("m:", ""); // format = format.Replace("m", ""); //} if (string.IsNullOrEmpty(format)) { formattedString = string.Empty; } else { formattedString = dt.ToString(format, formatProvider); } } else throw new ArgumentNullException(); return formattedString; } } All that stuff is re-usable and should live in your tool box. I pulled it from mine. Then, of course, you wire it all together:
Storyboard sb = new Storyboard(); DoubleAnimation da = new DoubleAnimation(); sb.Children.Add(da); DoubleTextBlockSetter textBlockSetter = new DoubleTextBlockSetter( Your_TextBlock, new TicksFormatConverter(), "{0:m:ss}"); // DateTime format Storyboard.SetTarget(da, textBlockSetter); da.From = Your_RefreshInterval_Secs * TimeSpan.TicksPerSecond; da.Duration = new Duration( new TimeSpan( Your_RefreshInterval_Secs * TimeSpan.TicksPerSecond)); sb.begin(); And that should do the trick. An it's only like a million lines of code. And we haven't even written Hello World just yet...;) I didn't compile that, but I did Copy and Paste the 3 classes directly from my library. I've used them quite a lot. It works great. I also use those classes for other things. The TickFormatConverter comes in handy when data binding. I also have one that does Seconds. Very useful. The DoubleTextblockSetter allows me to animate numbers, which is really fun. Especially when you apply different types of interpolation.
Enjoy.
-4250209 0Well, just do what the error message tells you.
Don't call setContentView() before requestFeature().
Note:
As said in comments, for both ActionBarSherlock and AppCompat library, it's necessary to call requestFeature() before super.onCreate()
Probably by modifying the "System Power States" as described here (but in c#)
That article also describes a way to prevent the mobile device to sleep (which is not exactly what you may want), by calling the native function SystemIdleTimerReset() periodically (to prevent the device from powering down).
-6203699 0You can iterate over the returned drives from your WMI query and add the deviceid and "Disk GB" results to a string value. Then you can write the resulting string value to the Excel cell. One way to do this would be like this:
$a = New-Object -comobject Excel.Application $a.Visible = $True $b = $a.Workbooks.Add() $c = $b.Worksheets.Item(1) $outputstring = "" foreach ($drive in $driveinfo) { $outputstring += "$($drive.deviceid) $($drive."Disk GB") GB`n" } $c.cells.item(1,1) = $outputstring
-1809795 0 At the very least you can now output assembler from gcc like this:
gcc -c -S test.c -o test.asm
Then you can inspect the output of generated C code for educational purposes.
-16683226 0select color from table_name where width = $value and length = $value2 and height = $value3 I assume you mean using SQL....
-9861916 0It is ultimately up to the vendor to define the filesystem / filesystem layout. So it might be in a different place. If there is no customized definition then the libraries will be in /data/data/your.package.name/lib.
In case it is in a different directory then System.loadLibrary will know that and load the library from that place.
on a workstation-mac (MacPro) I found 3 NSNotification centers:
// 1. NSWorkspace Center let theWorkspaceCenter = NSWorkspace.sharedWorkspace ().notificationCenter // 2. NSDistributedNotification Center let theNSDistributedNotificationCenter = NSDistributedNotificationCenter.defaultCenter () // 3. Default Center let theDefaultCenter = NSNotificationCenter.defaultCenter () Are there any more NSNotification centers?
1. NSWorkspace Center
let theWorkspaceCenter = NSWorkspace.sharedWorkspace ().notificationCenter NSWorkspaceScreensDidWakeNotification NSWorkspaceWillUnmountNotification 2. NSDistributedNotification Center
let theNSDistributedNotificationCenter = NSDistributedNotificationCenter.defaultCenter () com.apple.HIToolbox.beginMenuTrackingNotification com.apple.HIToolbox.frontMenuBarShown com.apple.backupd.NewSystemBackupAvailableNotification com.apple.systemBeep com.apple.calendar.DayChanged 3. Default Center
let theDefaultCenter = NSNotificationCenter.defaultCenter () NSApplicationDidUpdateNotification NSViewNeedsDisplayInRectNotification NSWindowDidUpdateNotification Thanks for any hint!
-5573525 0Typically, how I like to do it is to have a couple of different directories. Something like this:
Trunk (deploy here)
- Production - Staging - Development/whatever Branches (develop here)
- Master Branch (primary) - Secondary/Tertiary Branches Tags (Archive here)
- Name a tag appropriately (timestamp, version, edits) Hope this helps. Feel free to ask questions.
-3667710 0You want to check out Integrated Windows Authentication. This will allow the Active Directory username and password (hashed) to be sent across the network to the server. If they pass you can redirect them to the site, and if not, push them to the login page.
-2690422 0 add(a,b) and a.add(b)how can i transform a method (that performs a+b and returns the result) from add(a,b) to a.add(b)?
i read this somewhere and i can't remember what is the technique called...
does it depends on the language?
is this possible in javascript?
-24927838 0 Accessing controller method from view in EmberI would like to call a controller method which is not necessarily an action from my view. How can I achieve this?
-12447922 0I don't think it's working smoothly. Calling openContextMenu(l) will cause item.getMenuInfo() to be null (inside method onContextItemSelected(MenuItem item)).
You should call l.showContextMenuForChild(v) instead of openContextMenu(l).
Yes, too many variables will blow the stack.
-14756318 0 How to disable a User Control to draw it's background (or Region)My question : How to disable a User Control to draw it's background (or Region)
Note : I already tried to override and empty OnPaintBackground or set background color to transparent.
I'm trying to bypass winform paint for my custom user controls in a custom container. For that I thought to give a try to this : Beginners-Starting-a-2D-Game-with-GDIplus
My setup is :
My render loop is inside the DrawingBoard with all elements specified in the previous link.
public DrawingBoard() { InitializeComponent(); //Resize event are ignored SetStyle(ControlStyles.FixedHeight, true); SetStyle(ControlStyles.FixedWidth, true); SetStyle(System.Windows.Forms.ControlStyles.AllPaintingInWmPaint, true);// True is better SetStyle(System.Windows.Forms.ControlStyles.OptimizedDoubleBuffer, true); // True is better // Disable the on built PAINT event. We dont need it with a renderloop. // The form will no longer refresh itself // we will raise the paint event ourselves from our renderloop. SetStyle(System.Windows.Forms.ControlStyles.UserPaint, false); // False is better } #region GDI+ RENDERING public Timer t = new Timer(); //This is your BackBuffer, a Bitmap: Bitmap B_BUFFER = null; //This is the surface that allows you to draw on your backbuffer bitmap. Graphics G_BUFFER = null; //This is the surface you will use to draw your backbuffer to your display. Graphics G_TARGET = null; Size DisplaySize = new Size(1120, 630); bool Antialiasing = false; const int MS_REDRAW = 32; public void GDIInit() { B_BUFFER = new Bitmap(DisplaySize.Width, DisplaySize.Height); G_BUFFER = Graphics.FromImage(B_BUFFER); //drawing surface G_TARGET = CreateGraphics(); // Configure the display (target) graphics for the fastest rendering. G_TARGET.CompositingMode = CompositingMode.SourceCopy; G_TARGET.CompositingQuality = CompositingQuality.AssumeLinear; G_TARGET.SmoothingMode = SmoothingMode.None; G_TARGET.InterpolationMode = InterpolationMode.NearestNeighbor; G_TARGET.TextRenderingHint = TextRenderingHint.SystemDefault; G_TARGET.PixelOffsetMode = PixelOffsetMode.HighSpeed; // Configure the backbuffer's drawing surface for optimal rendering with optional // antialiasing for Text and Polygon Shapes //Antialiasing is a boolean that tells us weather to enable antialiasing. //It is declared somewhere else if (Antialiasing) { G_BUFFER.SmoothingMode = SmoothingMode.AntiAlias; G_BUFFER.TextRenderingHint = TextRenderingHint.AntiAlias; } else { // No Text or Polygon smoothing is applied by default G_BUFFER.CompositingMode = CompositingMode.SourceOver; G_BUFFER.CompositingQuality = CompositingQuality.HighSpeed; G_BUFFER.InterpolationMode = InterpolationMode.Low; G_BUFFER.PixelOffsetMode = PixelOffsetMode.Half; } t.Tick += RenderingLoop; t.Interval = MS_REDRAW; t.Start(); } void RenderingLoop(object sender, EventArgs e) { try { G_BUFFER.Clear(Color.DarkSlateGray); UIPaint(G_BUFFER); G_TARGET.DrawImageUnscaled(B_BUFFER, 0, 0); } catch (Exception ex) { Console.WriteLine(ex); } } #endregion Then my elements get the event fired and try to draw what I would like:
public override void UIPaint(Graphics g) { Pen p = new Pen(Color.Blue,4); p.Alignment = System.Drawing.Drawing2D.PenAlignment.Inset; g.DrawLines(p, new Point[] { new Point(Location.X, Location.Y), new Point(Location.X + Width, Location.Y), new Point(Location.X + Width, Location.Y + Height), new Point(Location.X, Location.Y + Height), new Point(Location.X, Location.Y - 2) }); g.DrawImageUnscaled(GDATA.GetWindowImage(), Location); } here is what happening on my DrawingBoard :
As I can't post image ... here is the link : http://s8.postimage.org/iqpxtaoht/Winform.jpg
So from there I've tried everything I could to disable WinForm to make some magic drawing in background. Tried to override and empty everything that got paint/update/refresh/invalidate/validate on Form/DrawingBoard/Elements but nothing allowed me to get my texture or drawing to not get cropped by the control background : (
I also tried to set the background of the Element as transparent and also to set Form.TransparencyKey = blabla with each element BackColor = blabla. But failed each time.
I'm certainly missing something : / But I don't know what.
-646910 0 A site where users could make suggestion for my code?Hi do you guys know a site where other programmers could make suggestions about the code that I make? I always think that the code I make could be better and I also wish someone could like mentor me or point out some bad habits that I make. I code in Java.
-6238630 0The Wrap Layout might be a solution for you. It automatically moves components to the next line when a line is full.
-35447296 1 Trying to filter by an intermediate tableI'm trying to do this query
subsidiaries = self.con.query(Subsidiary)\ .options(joinedload(Subsidiary.commerce)\ .joinedload(Commerce.commerce_tags))\ .filter(CommerceTag.tag_id == id) But it doesn't work, so to explain:
The relationship between tables are:
I just want to obtain all the subsidiaries of all the commerces that has an specific tag, i want to do it with Subsidiary has the base class (i know that if i use Commerce it will be more easier), the reason is 'cause i convert it to a json value with the next format:
"subsidiaries": [ { "id": 1, "name": "some_name", "commerce": { "id": 1, "name": "Commerce Name" } } ] Well, i can do the query with Commerce has base class, but i think that maybe iterating the commerces to obtain the subsidiaries is more expensive that doing it in the query.
I don't want to load CommerceTag but i had it in joinedload 'cause it doesn't work with Join method.
I need some help to do this :(
-31899013 0I think it wp bug. Add that to functions.php
add_filter('redirect_canonical', 'disable_custom_redirect'); function disable_custom_redirect ($redirect_url) { global $post; $ptype = get_post_type($post); if ($ptype == 'catalog') $redirect_url = false; return $redirect_url; }
-28491762 0 I have read the documentation and it seems like if this flag is set when calling an Activity, if the user presses the back button or that Activity is finished(), it still remains on the stack.
No, the Activity will not remain on the stack, but its entry will be shown in the recent task list, you can click on that entry to re-launch this Activity just as you re-launch your application.
-35207148 0For MVC6, You need to decorate the controllers with Area attribute. if you do not prefer to add this to individual controllers, you may simply create a base call which has Area decoration and inherit your other controllers from that.
[Area("Admin")] public class AdminArea : Controller { } public class OrdersController : AdminArea { public IActionResult Index() { return View(); } } public class ProductsController : AdminArea { public IActionResult Index() { return View(); } } MVC 5 and below
You do not need to put that attribute on your controller name, You can simply specify the area name in the area route registration.
public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "Admin_default", "Admin/{controller}/{action}/{id}", new { action = "Index", controller= "YourDefaultCtrl", id = UrlParameter.Optional } ); }
-27493867 0 At first I thought you needed to include ob_end_clean like:
ob_start(); call_user_func( 'test', $args ); $ret_func = ob_get_clean(); $data = preg_replace( $re, $ret_func, $data); ob_end_clean(); But then I ran a basic test myself doing this:
<?php $i = 0; for($i=0; $i<10; $i++) { ob_start(); test(); $ret_func = ob_get_clean(); echo '<p>' . $ret_func . '</p>'; ob_end_clean(); //tried with this commented out as well echo '<p>' . $ret_func . '</p>'; } function test() { echo rand(0,100); } ?> And it made no difference if I included ob_end_clean or not. So your problem is probably actually how you are rebuilding the args array in each iteration of the loop.
Why not just grab all the right information in one query from the start along the lines of something like this:
select a.exID, examples.someField, examples.someOtherField from examples join ( SELECT exID FROM examples WHERE concept='$concept' ORDER BY RAND() limit 5 ) a on a.exID=examples.exID Then you just just pop them into an array (or better yet object) that has all the pertinent information in one row each time.
-25896993 0If you update your google play services you need to update your res/values tag too.
-35608521 0 Using CBC DES encryption in java cardI am trying to encrypt data using Cipher class . I want to specify the initial vector so I use the following functions :
try { cipherCBC = Cipher.getInstance(Cipher.ALG_DES_CBC_NOPAD, false); cipherCBC.init(k, Cipher.MODE_ENCRYPT,INITVECTOR,(short)0,(short)8); cipherCBC.doFinal(data, (short) 0, (short) data.length, result, (short) 0); } catch (Exception e) { ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED); } with the byte array INITVECTOR initialised by a 8-byte array.
The problem is that I get always an exception caught when I use the init function.
EXTRA INFO:
The key is build here :
octetsLus = (byte) (apdu.setIncomingAndReceive()); if (octetsLus != 16) { ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); } // build host crypto Util.arrayCopy(buffer, (short)(ISO7816.OFFSET_CDATA+4), message, (short) 0,(short) 4); Util.arrayCopy(buffer, (short)(ISO7816.OFFSET_CDATA+8), message, (short) 4,(short) 4); Util.arrayCopy(buffer, (short)(ISO7816.OFFSET_CDATA), message, (short) 8,(short) 4); Util.arrayCopy(buffer, (short)(ISO7816.OFFSET_CDATA+12), message, (short) 12,(short) 4); // GENERATE SESSION KEYS encrypt_DES(ENC_key, message,(byte) 0x01); Util.arrayCopy(result,(short) 0, ENC_SESS_KEY, (short) 0,(short) 16); encrypt_DES(MAC_key, message,(byte) 0x01); Util.arrayCopy(result,(short) 0, MAC_SESS_KEY, (short) 0,(short) 16); ENC_key = (DESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES3_2KEY, false); ENC_key.setKey(ENC_SESS_KEY, (short) 0); MAC_key = (DESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES3_2KEY, false); MAC_key.setKey(MAC_SESS_KEY, (short) 0); Util.arrayCopy(buffer, (short)(ISO7816.OFFSET_CDATA), message, (short) 0,(short) 8); Util.arrayCopy(buffer, (short)(ISO7816.OFFSET_CDATA+8), message, (short) 8,(short) 8); for(i=0;i<8;i++) message[(short)(16+i)]=(byte)PADDING[i]; Concerning the initial vector, even if I use the following initialization, I get the same problem :
INITVECTOR =new byte[]{(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00}; On the other hand, when I use the init function which use default initialization parameters the encrypt function works well:
cipherCBC.init(k, Cipher.MODE_ENCRYPT);
-10071288 0 when there is a relationship between two entities and you expect to use it, use JPA relationship annotations. One of the main advantages exactly is to not have to manually make extra queries when there is a relationship between entities.
-34725412 0 Unable to connect to remote Oracle database from a machine that does not have oracle clientI have a dot net executable (build in Visual Studio 2008) that attempts to connect to remote oracle database from a machine that does not have oracle client installed. The error I am getting is
"ORA-12154 TNS Could not resolve the connect identifier specified"
from what I have read so far I needed to add reference Oracle.DataAccess.dll. Oracle.DataAccess was not available for adding under my VS 2008, so I went ahead and got a copy of MSI package (ODTwithODAC1020221.exe from Oracle site) to add the suggested DLL file (I am not sure if there is compatibility issue between my version of VS/.NET 3.5 SP1 and the download). After I have successfully added the reference, i get the above error.
I can successfully do a TNSPING on a local machine that has oracle client. I have also validated database descriptions from TNSNAMES.ORA file.
Here is the code I am using to connect to oracle:
Imports System.IO Imports System.Xml Imports System.Net Imports System.Xml.Schema Imports System.Text Imports System.Data.Common.DataAdapter Imports System.Data.Common.DbDataAdapter Imports System.Net.Mail Imports System.Threading.Thread Imports System.Data.OleDb Imports System.Data.SqlClient Imports System.ServiceProcess Imports System.Management Imports System Imports Oracle.DataAccess Imports Oracle.DataAccess.Client Module Module1 Public Sub Main() Dim sql As String Dim sql2 As String Dim DATABASENAME1 As String = "Data Source=(DESCRIPTION =" _ + " (ADDRESS = (PROTOCOL = TCP)(HOST=Server.Host.com)(PORT=1540))" _ + ")" _ + "(CONNECT_DATA = " _ + "(SID=DATABASENAME1)));" _ + "User Id=user;Password=password1;" Dim conn1 As New OracleConnection() conn1.ConnectionString = DATABASENAME1 '%%%%% Connect to database Try conn1.Open() Console.WriteLine("Connection to Oracle database established!") MsgBox("Connection to Oracle database established!") Console.WriteLine(" ") Catch ex As Exception MsgBox("Not Connected" & ex.Message) Console.WriteLine(ex.Message) End End Try END SUB END MODULE
-3966904 1 How to determine when input is alphabetic? I been trying to solve this one for a while and can't seem to make it work right.. here is my current work
while True: guess = int(raw_input('What is your number?')) if 100 < guess or guess < 1: print '\ninvalid' else: .....continue on Right now I have made it so when a user input a number higher than 100 or lower than 1, it prints out "invalid". BUT what if i want to make it so when a user input a string that is not a number(alphabetic, punctuation, etc.) it also returns this "invalid" message?
I have thought about using if not ...isdigit(), but it won't work since I get the guess as an integer in order for the above range to work. Try/except is another option I thought about, but still haven't figured out how to implement it in correctly.
-20354133 0"These pattern match variables are scalars and, as such, will only hold a single value. That value is whatever the capturing parentheses matched last."
http://blogs.perl.org/users/sirhc/2012/05/repeated-capturing-and-parsing.html
In you example, $1 matches 1.2.3. As the pattern repeats, $2 would be set to .2 until the final match of .3
I use this short example snippet in my code
<BootstrapTable data={products}> <TableHeaderColumn dataField="id" isKey={true}>Product ID</TableHeaderColumn> <TableHeaderColumn dataField="name">Product Name</TableHeaderColumn> <TableHeaderColumn dataField="price">Product Price</TableHeaderColumn> </BootstrapTable> And everything's work perfect. There's table, there's data. But (!) I see next warning message in my Chrome console:
whereas if I use my own elements, there's no warnings..
What's wrong? How to fix it?
Take a look at this other answer. It uses the same approach that you do.
Creating constant string for a Postgres entire database
-34420129 0 Iphone Testing App on XcodeIs it possible to test your iPhone app on Xcode, not on the simulator, but on your actual phone before releasing it on the app store.
-33695919 0 error: expected expression before ‘if’Here is my code, I don't know where I'm wrong and what is "expression"?
#define m(smth) (if(sizeof(smth) == sizeof(int)) {printf("%d", (int) smth);} else{puts((char*)smth);}) int main(void) { m("smth"); } here is output:
/home/roroco/Dropbox/rbs/ro_sites/c/ex/ex2.c: In function ‘main’: /home/roroco/Dropbox/rbs/ro_sites/c/ex/ex2.c:18:18: error: expected expression before ‘if’ #define m(smth) (if(sizeof(smth) == sizeof(int)) {printf("%d", (int) smth);} else{puts((char*)smth);}) ^ /home/roroco/Dropbox/rbs/ro_sites/c/ex/ex2.c:21:5: note: in expansion of macro ‘m’ m("smth"); ^ make[3]: *** [ex/CMakeFiles/ex2.dir/ex2.c.o] Error 1 make[2]: *** [ex/CMakeFiles/ex2.dir/all] Error 2 make[1]: *** [ex/CMakeFiles/ex2.dir/rule] Error 2 make: *** [ex2] Error 2
-4619085 0 You can only use one character per range in a regex and most regex parsers don't understand multiple bytes using the \x notation. Use the \u notation instead.
(:|[A-Z]|_|[a-z]|[\xC0-\xD6]|[\xD8-\xF6]|[\xF8-\u02FF]|[\u0370-\u037D]|[\u037F-\u1FFF]|[\u200C-\u200D]|[\u2070-\u218F]|[\u2C00-\u2FEF]|[\u3001-\uD7FF]|[\uF900-\uFDCF]|[\uFDF0-\uFFFD]|[\u10000-\uEFFFF]) The .NET regex documentation states
\x20Matches an ASCII character using 2-digit hexadecimal. In this case,\x2-represents a space.
And for unicode:
\u0020Matches a Unicode character using exactly four hexadecimal digits. In this case\u0020is a space.
So I've used both above, \x for the 2-char hex values and \u for the larger ones.
I have a small issue with my dropdown menu when switching to another page. When I press my menu label button, the navigation bar slides down and when I then proceed to another page the dropdown menu acts if it was open but it is not so when I press the menu label button again the navigation bar slides up instead of down and after that it works normally.
What do I do to make the slide bar return to normal state when I switch pages? I hope you understand what I mean, otherwise I will try to clarify
HTML
<nav id="navBar"> <ul id="mainNav"> <li class="hem"><a href="index.html">Hem</a></li> <li><a href="kontakt.html">Kontakt</a></li> <li><a href="om.html">Om</a></li> </ul> </nav> CSS
#navBar { display:none; position:relative; } #navBar.active{ display:block; height:auto; } #mainNav { background:#202020; } #mainNav li { padding:6px 0; } #mainNav a { color:white; font-weight:bold; } #mainNav li:hover { background-color:#f3ba32; } JQUERY
$("#menulabel").click(function() { $("#navBar").toggleClass("active").slideToggle(300); });
-23153353 0 Ok after some trial and error I appear to have solved this issue now.
I have changed the drawMatches method to swap the "roiImg" and key points with "compare" and key points.
drawMatches(compare, keypoints_scene, roiImg, keypoints_object, good_NNmatches, img_matches, Scalar::all(-1), Scalar::all(-1), vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS ); This stopped the assertion error. But due to swapping the values around when it came to retrieving the key points I also had to make some changes. trainIdx and queryIdx have also been swapped to account for the previous changes made.
obj.push_back( keypoints_object[ good_NNmatches[i].trainIdx ].pt ); scene.push_back( keypoints_scene[ good_NNmatches[i].queryIdx ].pt );
-29993697 0 Leaflet map in ionic/angular map displays grey tiles I'm working on a mapping app using ionic and leaflet. Note that I am not using the leaflet angular directive, I am using straight JS for the leaflet map (I know, I know...).
The initial state in my app loads the leaflet map just fine. If I switch to another state and back to the map everything is also fine. However, if I launch the app, switch to a different state and open a modal window in that state, then return to the original state, the map is broken and displays a number of grey tiles. The map will not update until the browser window resizes or the orientation of the mobile device is changed.
Here's a demo on Plunker: http://plnkr.co/edit/w67K2b?p=preview. To reproduce:
I've seen other people report issues with grey tiles, which typically can be resolved with a call to:
map.invalidateSize() Unfortunately this does not resolve my issue. I'm pretty much a newb, but I think the problem is that when the modal opens, the invalidateSize() method in the leaflet source code is run, since the map div is not visible, the 'size' gets set to x:0, y:0 which ends up breaking the map when I transition back to the original state.
I'm not really sure where to go from here. Perhaps I can use JS to dynamically resize the div and trick leaflet into thinking a resize event has occurred? How would I do this? Any other thoughts?
Thanks!
-3678424 0This is really poorly explained in the documentation, but actually gyp is already present if you've done an ordinary checkout of breakpad. Open a command prompt and place yourself in the root ( google-breakpad-read-only if you're going by the instructions ). Then just do:
src\tools\gyp\gyp.bat src\client\windows\breakpad_client.gyp
This will generate visual studio sln files for you.
-27474172 0 Using Socket.io, AngularJS and Express, client listening on different port than which the server is running atI was trying to implement a chat application with authentication. I followed this tutorial to make the chat application which uses Socket.io.
When I used this tutorial the server is listening at port 8000 whereas the client is running at port 8100. The Socket URL is at 8000 and the chat application is working perfectly. However when I try to use methods of Express such as app.get(), I cant seem to make it work. I think the cause is that the port of the local host is 8100 and I am listening on 8000. I am using app.get() and AngualrJS to authenticate using PassportJS. Please can someone help me out as I have been stuck on this for a while. Thanks and I would really appreciate any help. Maybe I am thinking about this the wrong way.
I have a simple unit test project on Visual Studio 2012 Professional. I want to open this unit test using Microsoft Test Manager and run it. Is this possible? How do I do this? Thank you.
-31672428 0You can put the key between brackets ([]) to form it from a string:
cookieJSON.Cases['mdata' + i]
Consider a few points:
Keep your blacklist (business logic) checking in your application, and perform the comparison in your application. That's where it most belongs, and you'll likely have richer programming languages to implement that logic.
Load your half million records into your application, and store it in a cache of some kind. On each signup, perform your check against the cache. This will avoid hitting your table on each signup. It'll be all in-memory in your application, and will be much more performant.
Ensure myEnteredUserName doesn't have a blacklisted word at the beginning, end, and anywhere in between. Your question specifically had a begins-with check, but ensure that you don't miss out on 123_BadWord999.
Caching bring its own set of new challenges; consider reloading from the database everyday n minutes, or at a certain time or event. This will allow new blacklisted words to be loaded, and old ones to be thrown out.
I'm not sure if that's what you're looking for, but just as a quick example without having looked at the actual code but using the CSS from the Stackoverflow tag elements - you can just retrieve the value of the input on change(), create an element, append the value of input and an additional element to remove the created and appended element on click(). As the new tag is appended and not already in the DOM when the page is loaded, you can use on() to delegate this click() event from a parent element. Instead of document any parent element can be used to delegate the event.
For reference: http://api.jquery.com/on/
$(".taginput").on("change", function () { var tagval = $(this).val(); var tagelement = $("<a>"); var remove = $("<span class='remove'>x</span>") $(tagelement).append(tagval).append(remove).addClass("tag"); $("body").append(tagelement); $(".taginput").remove(); }); $(document).on("click", ".remove", function () { $(this).parent().remove(); }); .tag { background: none repeat scroll 0 0 #e4edf4; border: 1px solid #e4edf4; border-radius: 0; color: #3e6d8e; display: inline-block; font-size: 12px; line-height: 1; margin: 2px 2px 2px 0; padding: 0.4em 0.5em; text-align: center; text-decoration: none; white-space: nowrap; } .remove { padding-left:10px; position:relative; top:-2px; } .remove:hover { cursor:pointer; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input class="taginput" type="text"/> Payload for iOS is bit different. The structure should be following format
{ "content_available":true, "to":"gcm_token_of_the_device", "priority":"high", "notification": { "body":"anything", "title":"any title" } } Note: Content_available should be true and priority should be high then only u recevied the notification. when your app is in closed state
-34000747 0There is a String constructor for this problem:
var s = String(count: 10, repeatedValue: Character(" "))
-25075295 0 You need to keep the selected item index inside pager adapter instead. And on click of any item inside a fragment change that value.
interface ItemSelectionInterface{ void onItemSelectionChanged(int fragmentPosition,int itemIndex); int getSelectedItemOnFragment(int fragmentPosition); } implement above interface in PagerAdapter:
class YourPagerAdapter....... implements ItemSelectionInterface{ int selectedFragment,selectedItem; @Override public Fragment getItem(int position) { return GridFragment.getInstance(position-(Integer.MAX_VALUE / 2),this); } @Override public int getCount() { return Integer.MAX_VALUE; } void onItemSelectionChanged(int fragmentPosition,int itemIndex){ selectedFragment=fragmentPosition;selectedItem=itemIndex; } int getSelectedItemOnFragment(int fragmentPosition){ if(fragmentPosition!=selectedFragment) return -1; return selectedItem; } } Change your GridFragment to:
class GridFragment ....{ ItemSelectionInterface selectionInterface; @Override public void setMenuVisibility(final boolean visible) { super.setMenuVisibility(visible); if (visible) { mAdapter.notifyDataSetChanged(); } } public static GridFragment getInstance(int position, ItemSelectionInterface selectionInterface){ ........... ........... this.selectionInterface=selectionInterface; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_calednar, container, false); mAdapter = new CalendarGridViewAdapter(getActivity(), getDateTime(position), MONDAY); mAdapter.setSelectionInterface(selectionInterface); mGridView = (GridView) rootView.findViewById(R.id.gridView); mGridView.setAdapter(mAdapter); // TODO handle on item click listener mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { selectionInterface.onItemSelectionChanged(position,i); mAdapter.notifyDataSetChanged(); } }); } return rootView; } And finally in adapter:
ItemSelectionInterface selectionInterface; //Create a setter for int position;//create a setter @Override public View getView(int i, View convertView, ViewGroup viewGroup) { // if (convertView == null) { LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.grid_item_day, null); //} TextView txt = (TextView) convertView.findViewById(R.id.dayText); txt.setText(""+datetimeList.get(i).getDay()); View actSelection = convertView.findViewById(R.id.actSelection); actSelection.setVisibility(View.INVISIBLE); if(selectionInterface.getSelectedItemOnFragment(position)== i){ actSelection.setVisibility(View.VISIBLE); } .... return convertView; }
-19534477 0 Animate image icon from touch place to right-top corner? I am working on Android onlineShopping application.I have to apply some animation.
Please help me out.
Thanks in advance.
Update :
I Tried this to move image from one place to another.
TranslateAnimation anim = new TranslateAnimation(0,0,200,200); anim.setDuration(3000); img.startAnimation(anim); This image I want to animate from touch position to right-top corner. 
What type of cache do you use?
This sequence works fine for me:
child.setParent(parent); parent.getChildren().add(child); session.saveOrUpdate(child); session.flush(); Also, make sure that you REALLY need that cache. In my experience, 2-nd level cache rarely accelerates real applications and yet creates a lot of problems.
-11595147 0You probably want to just use Attributes to specify your validation rules. This is the namespace where all the basic validations exist: ComonpentModel.DataAnnotations. If you want to get fancier, this NuGet package gives you lots of extra attributes: Data Annotation Extensions. Both of these support client side validation with ASP.NET's MVC unobtrusive validation.
-26509285 0 Multiple modules with same build typeI have a gradle android project with two modules:
In my gradle configuration I have different build types. The defaults (debug and release, each with custom settings), and dev and beta build type (also with custom signing, custom proguard and custom applicationIdSuffix.
What I now want to do is to build the app package with for example the buildType beta (gradle clean assembleBeta). That starts building the app in beta, sees that it has a dependency to wear, and starts building wear. BUT here's the problem. The wear module is being built with the release build type instead of the same beta-build-type I used to initiate the build.
The custom build type configuration is exactly the same on the two modules, and thus manually building the wear module with beta build type does work. But having a wear module built with beta and packaged inside the app module also built with beta does not work.
Any ideas how I can achieve that?
-7438712 0The idea behind this assert is to check if first row after added ones was correctly moved. If there are some rows after inserted ones, then their data are compared. If there aren't any, your model should both in the line
c.next = model->data ( model->index ( start, 0, parent ) ); and in
Q_ASSERT ( c.next == model->data ( model->index ( end + 1, 0, c.parent ) ) ); should return invalid (empty) QVariant. If both return empty QVariant (as they should) assertion succedes, thus providing some level of error-checking even in case of no rows after currently inserted.
-33845898 0According to the stacktrace, angular didn't found the module ngAnimate. You probably forgot to link angular-animate script from your index.html page.
index.html
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-animate.js"></script> <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.14.3.js"></script>
-8177540 0 Precede your list name by a star:
def foo(a, b, c): print(a, b, c) a = [1,2,3] foo(*a) # 1 2 3 The star unpacks the list, which gives 3 separate values.
-34829171 0 How to resize canvas and its background image while somehow maintaining the co-ordinate scale?I want my canvas and background image to scale to any browser size which I have learnt is possible through this.
<canvas id="canvas" style="width:100%; height:100%; background-size:100% 100%; left:0px; top: 0px;"> Setting the width and height using percentages causes whatever I draw on top to come out blurred. The reason for this I read is that it comes out blurry because the width and height of canvas set using css is different.
It is absolutely imperative that I keep track of the co-ordinates since I have written a collision detection logic using the original size of the image.
Is it possible to dynamically change the canvas size to fill the screen, redraw it and ensure that the collision logic works perfectly without blurry drawing on top?
Lets take an example here. The image floor.jpg that I want as the background of the canvas is 1200X700. I want the canvas to be 100% of the page width and height. My animated player that moves on top of it requires collision detection with walls which I have coded keeping in mind the 1200x700 image.
I have gone through the various similar question on this site, but can't seem to figure it out.
-18860799 0 Modify File Contents based on starting element/stringI have a HL7 File like:
MSH|^~\&|ABC|000|ABC|ABC|0000||ABC|000|A|00 PID|1|000|||ABC||000|A|||||||||| OBR|1|||00||00|00|||||||||||ABC|00|0|0||||A|||||00||ABC|7ABC||ABC OBX|1|ABC|ABC|1|SGVsbG8= OBX|2|ABC|ABC|1|XYTA OBX|3|ABC|ABC|1|UYYA I have to read only OBX segments and get the text after 5th pipe (|).
Currently I am doing this with:
StreamReader reader = new StreamReader(@"C:\Users\vemarajs\Desktop\HL7\Ministry\HSHS.txt"); string strTest = reader.ReadToEnd(); string OBX1 = strTest.Split('\n')[3]; File.AppendAllText(@"C:\Users\vemarajs\Desktop\Test\OBX.txt", OBX1 + Environment.NewLine); List<string> list = new List<string>(); using (reader) { string line; while ((line = reader.ReadLine()) != null) { list.Add(line); if (line.StartsWith("OBX|") == true) { string txt = line.Split('|')[5]; File.AppendAllText(@"C:\Users\vemarajs\Desktop\Test\test.txt", txt+Environment.NewLine); } else { //string x = line + Environment.NewLine + OBX1.Distinct(); File.AppendAllText(@"C:\Users\vemarajs\Desktop\Test\newtest.txt", line + Environment.NewLine); } File.AppendAllText(@"C:\Users\vemarajs\Desktop\Test\newtest.txt", OBX1.Distinct().ToList() + Environment.NewLine);
This extracts the contents of each OBX segment at element 5 (after 5 pipes) and writes out a file called test.text, in my else statement I am trying to modify the original HL7 file by deleting OBX|2 and OBX|3 to have only One OBX|1 as we expect the number of OBX segments inside the HL7 file to reach 40 or more and we don't wan't to keep those many while returning the message to its messagebox.
How do I get the first occurrence of OBX|1 without saying the line number is 4, this might change.
This is the working code:
StreamReader reader = new StreamReader(@"C:\Users\vemarajs\Desktop\HL7\Ministry\HSHS.txt"); string strTest = reader.ReadToEnd(); reader.DiscardBufferedData(); reader.BaseStream.Seek(0, SeekOrigin.Begin); reader.BaseStream.Position = 0; string OBXstr = string.Empty; string x = null; string fileName = Guid.NewGuid().ToString() + ".txt"; StringBuilder sb = new StringBuilder(); List<string> list = new List<string>(); using (reader) { string line; while ((line = reader.ReadLine()) != null) { list.Add(line); if (line.StartsWith("OBX|") == true) { string txt = line.Split('|')[5]; File.AppendAllText(@"C:\Users\vemarajs\Desktop\Test\"+fileName, txt + Environment.NewLine); } else { sb.AppendLine(line); } } int obx1Index = 0; int obx2Index = 0; var obx1IDR = "\r" + "OBX" + "|" + "1"; var obx1IDN = "\n" + "OBX" + "|" + "1"; var obx2IDR = "\r" + "OBX" + "|" + "2"; var obx2IDN = "\n" + "OBX" + "|" + "2"; obx1Index = strTest.IndexOf(obx1IDN); if (obx1Index < 1) obx1Index = strTest.IndexOf(obx1IDR); obx2Index = strTest.IndexOf(obx2IDN); if (obx2Index < 1) obx2Index = strTest.IndexOf(obx2IDR); if (obx1Index > 0) { OBXstr = strTest.Substring(obx1Index, obx2Index - obx1Index - 1); OBXstr = OBXstr.Replace(strTest.Substring(obx1Index, obx2Index - obx1Index - 1).Split('|')[5], fileName); } } sb.Append(OBXstr); x = sb.ToString(); File.WriteAllText(@"C:\Users\vemarajs\Desktop\Test\newtest.txt", x); reader.Close();
-21802196 0 If you want to treat this as a 1d array, you must declare it as so:
void data(int i,int arr[],int size) { Or:
void data(int i,int *arr,int size) { The reason is that otherwise, arr[i] is interpreted as an array of 2 integers, which decays into a pointer to the first element (and that's the address that is printed).
Declaring it as a 1-dimensional array will make sure that arr[i] is seen as an int.
Note that whoever calls this function cannot pass a 2D array anymore, or, put another way, cannot make that obvious to the compiler. Instead, you have to pass it a pointer to the first element, as in:
data(0, &arr[0][0], 4); Or, equivalently:
data(0, arr[0], 4); This just affects the first call, the recursive call is correct, of course.
In other words, the code should work, you just need to change the declaration of the parameter arr
An ASP.NET web project loads with up the solution, but I get this error
The Web Application Project Module Example is configured to use IIS. The Web Server 'http://dnndev.me/desktopmodules/Module_Example' could not be found.
-19186457 0I agree this is a bad idea, but here is another possible solution;
data big; cust_id = 1; retain var1-var20000 0; run; data temp/view=temp; set big(keep=cust_id var1-var10000); run; proc export data=temp outfile='c:\temp\file1.csv' dbms=csv replace; run; data temp/view=temp; set big(keep=cust_id var10001-var20000); run; proc export data=temp outfile='c:\temp\file2.csv' dbms=csv replace; run; To control the variables written, just change the view definition however you need. You originally asked about creating five CSVs, this creates two.
You have to use a view because PROC EXPORT does not respect KEEP or DROP data set options. I don't think using a macro to do something like this is a good idea unless you are very sure you know what you are doing AND you need to run it multiple times with different scenarios.
Here is a simple example of how to copy values from an input to another html tag:
<input id="myInput" type="text" value="waffles" /> <button type="button" onclick="$('#copiedValue').html($('#myInput').val())">Copy value</button> <span id="copiedValue"></span> The jQuery is all in onclick which pulls the value from the input using $('#myInput').val() and supplies that value as an argument to replace the html contents of the span $('#copiedValue').html(...).
Here is a jsfiddle with the working code: https://jsfiddle.net/njacwybg/
-2692829 0 HTTP Response 412 - can you include content?I am building a RESTful data store and leveraging Conditional GET and PUT. During a conditional PUT the client can include the Etag from a previous GET on the resource and if the current representation doesn't match the server will return the HTTP status code of 412 (Precondition Failed). Note this is an Atom based server/protocol.
My question is, when I return the 412 status can I also include the new representation of the resource or must the user issue a new GET? The HTTP spec doesn't seem to say yes or no and neither does the Atom spec (although their example shows an empty entity body on the response). It seems pretty wasteful not to return the new representation and make the client specifically GET it. Thoughts?
-35047148 0 When runtime modifications are written to Edits log file in Name Node, is the Edits Log file getting updated on RAM or Local DiskWhen run-time modifications are written to Edits log file in Name Node, is the Edits Log file getting updated on RAM or Local Disk
-38266581 0 Jasper studio multi column pageI have mad a report in jaspersoft studio and I sat the Page Format to 2 columns, Portrait. It shows me what I need to see but starts from the second column at the first page. The first column remains empty! I could not find any configuration regarding this issue. How can I fix this problem. The output looks like this picture:
The source code is:
<?xml version="1.0" encoding="UTF-8"?> <!-- Created with Jaspersoft Studio version 6.3.0.final using JasperReports Library version 6.3.0 --> <!-- 2016-07-08T15:55:48 --> <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="ergebnisse" columnCount="2" pageWidth="595" pageHeight="842" columnWidth="272" columnSpacing="10" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" isSummaryNewPage="true" uuid="cc068ab5-928c-4253-8ba7-acdd311310fc"> <property name="com.jaspersoft.studio.data.sql.tables" value=""/> <property name="com.jaspersoft.studio.unit." value="pixel"/> <property name="net.sf.jasperreports.print.create.bookmarks" value="true"/> <property name="com.jaspersoft.studio.unit.pageHeight" value="pixel"/> <property name="com.jaspersoft.studio.unit.pageWidth" value="pixel"/> <property name="com.jaspersoft.studio.unit.topMargin" value="pixel"/> <property name="com.jaspersoft.studio.unit.bottomMargin" value="pixel"/> <property name="com.jaspersoft.studio.unit.leftMargin" value="pixel"/> <property name="com.jaspersoft.studio.unit.rightMargin" value="pixel"/> <property name="com.jaspersoft.studio.unit.columnWidth" value="pixel"/> <property name="com.jaspersoft.studio.unit.columnSpacing" value="pixel"/> <property name="com.jaspersoft.studio.data.defaultdataadapter" value="QIDBReport"/> <template><![CDATA["qiDB.jrtx"]]></template> <style name="Table_CH" mode="Opaque" backcolor="#BFE1FF"> <box> <pen lineWidth="0.5" lineColor="#000000"/> <topPen lineWidth="0.5" lineColor="#000000"/> <leftPen lineWidth="0.5" lineColor="#000000"/> <bottomPen lineWidth="0.5" lineColor="#000000"/> <rightPen lineWidth="0.5" lineColor="#000000"/> </box> </style> <style name="Table 1_TH" mode="Opaque" backcolor="#F0F8FF"> <box> <pen lineWidth="0.5" lineColor="#000000"/> <topPen lineWidth="0.5" lineColor="#000000"/> <leftPen lineWidth="0.5" lineColor="#000000"/> <bottomPen lineWidth="0.5" lineColor="#000000"/> <rightPen lineWidth="0.5" lineColor="#000000"/> </box> </style> <style name="condition"> <conditionalStyle> <conditionExpression><![CDATA[$F{KN_Id}.intValue() ==811809 ]]></conditionExpression> <style forecolor="#F0120E"/> </conditionalStyle> </style> <subDataset name="Dataset1" uuid="a8e62151-8fe6-42ec-b6ca-7f971a479ee6"> <property name="com.jaspersoft.studio.data.sql.tables" value=""/> <property name="com.jaspersoft.studio.data.defaultdataadapter" value="QIDBReport"/> <queryString> <![CDATA[select ZI_Infotext, Image, IMG_ID from"ZusatzInfo", Images where ZI_ID = 1269 and IMG_Id = 1]]> </queryString> <field name="ZI_Infotext" class="java.lang.String"/> <field name="Image" class="java.awt.Image"/> <field name="IMG_ID" class="java.lang.Integer"/> </subDataset> <scriptlet name="WrapImage" class="testProjektIman.toc.WrapImage"> <scriptletDescription><![CDATA[Fließtext ums Bild]]></scriptletDescription> </scriptlet> <parameter name="KN_OffeziellGruppe" class="java.lang.Integer"> <defaultValueExpression><![CDATA[3]]></defaultValueExpression> </parameter> <parameter name="LB_ID" class="java.lang.Integer"> <defaultValueExpression><![CDATA[62]]></defaultValueExpression> </parameter> <queryString> <![CDATA[select * from "KennzahlReferenz2015_QIBericht", "Images" where LB_ID = $P{LB_ID} and KN_OffiziellGruppe = $P{KN_OffeziellGruppe} and KN_OffiziellGruppe =$P{KN_OffeziellGruppe} and IMG_ID = 1]]> </queryString> <field name="QI_Praefix" class="java.lang.String"/> <field name="KN_Id" class="java.lang.Integer"/> <field name="bewertungsArtTypNameKurz" class="java.lang.String"/> <field name="refbereich" class="java.lang.String"/> <field name="refbereichVorjahres" class="java.lang.String"/> <field name="KN_ZAlleinstehend" class="java.lang.String"/> <field name="KN_GGAlleinstehend" class="java.lang.String"/> <field name="erlaueterungDerRechregeln" class="java.lang.String"/> <field name="teildatensatzbezug" class="java.lang.String"/> <field name="mindesanzahlZaeler" class="java.lang.Integer"/> <field name="mindesanzahlNenner" class="java.lang.Integer"/> <field name="KN_FormelZ" class="java.lang.String"/> <field name="KN_FormelGG" class="java.lang.String"/> <field name="verwendeteFunktionen" class="java.lang.String"/> <field name="KN_Vergleichbarkeit_Vorjahr" class="java.lang.String"/> <field name="bewertungsArtTypNameLang" class="java.lang.String"/> <field name="bewertungsArtVorjahrTypNameLang" class="java.lang.String"/> <field name="KN_OffiziellGruppeBezeichnung" class="java.lang.String"/> <field name="idLb" class="java.lang.String"/> <field name="LB_LangBezeichnung" class="java.lang.String"/> <field name="LB_ID" class="java.lang.Integer"/> <field name="nameAlleinstehend" class="java.lang.String"/> <field name="KN_BezeichnungAlleinstehendKurz" class="java.lang.String"/> <field name="refBereichArt" class="java.lang.Integer"/> <field name="refBereichEinheitErgebnis" class="java.lang.String"/> <field name="refBereichInfo" class="java.lang.String"/> <field name="KN_OffiziellGruppe" class="java.lang.Integer"/> <field name="KN_Zusatzinfo_Erlaeuterung_Rechenregel" class="java.lang.String"/> <field name="KN_Zusatzinfo_Erlaeuterung_Refbereich" class="java.lang.String"/> <field name="KN_Zusatzinfo_Methode_Risikoadjustierung" class="java.lang.String"/> <field name="KN_Zusatzinfo_Erlaeuterung_Risikoadjustierung" class="java.lang.String"/> <field name="KN_Zusatzinfo_Erlaeuterung_zum_SD" class="java.lang.String"/> <field name="KN_Zusatzinfo_DV_Indikatorbezug" class="java.lang.String"/> <field name="KN_Zusatzinfo_DV_Mindestanzahl_Z" class="java.lang.String"/> <field name="KN_Zusatzinfo_DV_Mindestanzahl_N" class="java.lang.String"/> <field name="KN_Zusatzinfo_DV_Relevanz" class="java.lang.String"/> <field name="KN_Zusatzinfo_DV_Hypothese" class="java.lang.String"/> <field name="KN_Zusatzinfo_DV_Jahr_der_Erstanwendung" class="java.lang.String"/> <field name="KN_Zusatzinfo_DV_Kommentar" class="java.lang.String"/> <field name="KN_Zusatzinfo_DV_Einleitungstext" class="java.lang.String"/> <field name="refBereichInfoArt" class="java.lang.String"/> <field name="refBereichOperator1" class="java.lang.String"/> <field name="refBereichStringAusgabe" class="java.lang.String"/> <field name="refBereichVorjahrInfoArt" class="java.lang.String"/> <field name="refBereichVorjahrOperator1" class="java.lang.String"/> <field name="refBereichVorjahrStringAusgabe" class="java.lang.String"/> <field name="refBereichWert1" class="java.math.BigDecimal"/> <field name="sortierung" class="java.lang.Integer"/> <field name="veroeffentlichungsPflicht" class="java.lang.Integer"/> <field name="QI_ID" class="java.lang.Integer"/> <field name="IMG_ID" class="java.lang.Integer"/> <field name="Name" class="java.lang.String"/> <field name="Image" class="java.awt.Image"/> <variable name="breakPos" class="java.lang.Integer" calculation="System"> <initialValueExpression><![CDATA[$P{WrapImage_SCRIPTLET}.getBreakPosition($F{KN_Zusatzinfo_DV_Einleitungstext},250,60)]]></initialValueExpression> </variable> <group name="LB" isReprintHeaderOnEachPage="true" keepTogether="true"> <groupExpression><![CDATA[$F{LB_ID}]]></groupExpression> <groupHeader> <band height="34"/> </groupHeader> <groupFooter> <band height="50"/> </groupFooter> </group> <group name="KN_ID" isReprintHeaderOnEachPage="true" keepTogether="true"> <groupExpression><![CDATA[$F{KN_Id}]]></groupExpression> <groupHeader> <band height="40"/> </groupHeader> <groupFooter> <band height="50"/> </groupFooter> </group> <background> <band splitType="Stretch"/> </background> <title> <band height="53" splitType="Stretch"> <staticText> <reportElement x="-10" y="10" width="60" height="20" forecolor="#BABABA" uuid="293b49d1-7b6f-46b8-bf8d-eecf08e4d76c"/> <textElement> <font fontName="SansSerif"/> </textElement> <text><![CDATA[Ergebnisse]]></text> </staticText> <textField isStretchWithOverflow="true"> <reportElement x="350" y="5" width="201" height="21" forecolor="#6B66FA" uuid="920ddc7a-36c4-4064-bacb-0d06eee25674"/> <textElement textAlignment="Right"/> <textFieldExpression><![CDATA[$F{idLb} +" - "+ $F{LB_LangBezeichnung}]]></textFieldExpression> </textField> <staticText> <reportElement x="360" y="30" width="191" height="20" uuid="bc3f12b2-89f2-4da8-af9f-97f4f7e6f6ef"/> <textElement textAlignment="Right"/> <text><![CDATA[Dr XYZ]]></text> </staticText> </band> </title> <pageHeader> <band height="59" splitType="Stretch"> <property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.FreeLayout"/> <printWhenExpression><![CDATA[new Boolean($V{PAGE_NUMBER} != 1)]]></printWhenExpression> <textField> <reportElement x="350" y="34" width="201" height="21" forecolor="#6B66FA" uuid="e6b696bf-6a6f-4c47-b92f-b4c4df3f56d6"/> <textElement textAlignment="Right"/> <textFieldExpression><![CDATA[$F{idLb} +" - "+ $F{LB_LangBezeichnung}]]></textFieldExpression> </textField> <staticText> <reportElement x="-10" y="7" width="60" height="20" forecolor="#BABABA" uuid="4d7cc8c1-51e1-475c-94b9-9cdb4b912a6d"/> <textElement> <font fontName="SansSerif"/> </textElement> <text><![CDATA[Ergebnisse]]></text> </staticText> </band> </pageHeader> <columnHeader> <band height="61" splitType="Stretch"/> </columnHeader> <detail> <band height="401" splitType="Stretch"> <image scaleImage="RetainShape"> <reportElement x="0" y="10" width="80" height="80" uuid="f9fa3516-451b-46e0-8e60-380798ae46e2"> <property name="com.jaspersoft.studio.unit.width" value="pixel"/> <property name="com.jaspersoft.studio.unit.height" value="pixel"/> </reportElement> <imageExpression><![CDATA[$F{Image}]]></imageExpression> </image> <textField isStretchWithOverflow="true"> <reportElement x="85" y="10" width="185" height="30" uuid="cf3b40af-aaa2-48a9-9742-b6a1de5224fd"> <property name="com.jaspersoft.studio.unit.y" value="pixel"/> </reportElement> <textElement textAlignment="Justified"/> <textFieldExpression><![CDATA[$F{KN_Zusatzinfo_DV_Einleitungstext}.substring(0,$V{breakPos}.intValue() )]]></textFieldExpression> </textField> <textField isStretchWithOverflow="true"> <reportElement x="4" y="101" width="260" height="30" uuid="35f16f07-67b7-4f1d-99e3-0c37f37764dd"/> <textElement textAlignment="Justified"/> <textFieldExpression><![CDATA[$F{KN_Zusatzinfo_DV_Einleitungstext}.substring($V{breakPos}.intValue())]]></textFieldExpression> </textField> <staticText> <reportElement style="StyleHeader" positionType="Float" x="10" y="140" width="170" height="30" forecolor="#000000" uuid="c9456766-8f28-4b5b-813c-00a1e1eac882"/> <textElement markup="styled"/> <text><![CDATA[Documentationspflichtige Leistung]]></text> </staticText> <textField isStretchWithOverflow="true"> <reportElement style="condition" positionType="Float" x="10" y="180" width="100" height="30" uuid="e1ae18a6-1d88-4d4b-b4aa-ecc86ea9f990"/> <textElement markup="styled"/> <textFieldExpression><![CDATA[0]]></textFieldExpression> </textField> </band> </detail> <columnFooter> <band height="45" splitType="Stretch"/> </columnFooter> <pageFooter> <band height="54" splitType="Stretch"/> </pageFooter> <summary> <band height="42" splitType="Stretch"/> </summary> </jasperReport> String urldisplay="http://www.google.com/";//sample url Log.d("url_dispaly",urldisplay); try{ InputStream in = new java.net.URL(urldisplay).openStream(); Bitmap mIcon11 = BitmapFactory.decodeStream(new SanInputStream(in)); } catch(Exception e){} Create class name SanInputStream
public class SanInputStream extends FilterInputStream { public SanInputStream(InputStream in) { super(in); } public long skip(long n) throws IOException { long m = 0L; while (m < n) { long _m = in.skip(n-m); if (_m == 0L) break; m += _m; } return m; } }
-40526461 0 Type error on using Apache Kakfa's KafkaConsumer api Im writing a simple Kafka Consumer class as follows
public class MySimpleKafkaConsumer { public static void main(String[] args) { Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); props.put("group.id", "mygroup"); props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props); consumer.subscribe(Arrays.asList("storm-test-topic")); . .
Although I get an error at the below line stating
The method subscribe(String...) in the type KafkaConsumer is not applicable for the arguments (List)
consumer.subscribe(Arrays.asList("storm-test-topic")); This seems correct as per the api docs. Here is the dependency version
<groupId>org.apache.kafka</groupId> <artifactId>kafka-clients</artifactId> <version>0.9.0.1</version> Am I missing something? Thanks
-5431059 0You must know the source encoding.
string someText = "The quick brown fox jumps over the lazy dog."; byte[] bytes = Encoding.Unicode.GetBytes(someText); char[] chars = Encoding.Unicode.GetChars(bytes);
-26620087 0 'pathos' provides a fork of python's 'multiprocessing', where 'pathos.multiprocessing' can send a much broader range of the built-in python types across a parallel 'map' and 'pipe' (similar to python's 'map' and 'apply'). 'pathos' also provides a unified interface for parallelism across processors, threads, sockets (using a fork of 'parallelpython'), and across 'ssh'.
-21841153 0 from itertools import chain def shuffle(list1, list2): if len(list1)==len(list2): return list(chain(*zip(list1,list2))) # if the lists are of equal length, chaining the zip will be faster else: a = [] while any([list1,list2]): for lst in (list1,list2): try: a.append(lst.pop(0)) except IndexError: pass return a # otherwise, so long as there's items in both list1 and list2, pop the # first index of each (ignoring IndexError since one might be empty) # in turn and append that to a, returning the value when both lists are # empty. This is not the recursive solution you were looking for, but an explicit one is generally faster and easier to read and debug anyway. @DSM pointed out that this is likely a homework question, so I apologize for misreading. I'll go ahead and leave this up in case it's enlightening to anyone.
-9309076 0It seems that ie and table widths don't play nicely together.
What you can do to enforce a minimum width for your table is to add an extra row to your table which spans all columns which has a width of the minimum size that you desire. This will then enforce your td percentages when the broswer is resized or your iframe is small.
Like so:
<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title></title> <style> .min500 { width: 500px; height: 1px; } </style> </head> <body> <form id="form1" runat="server"> <table align="center" border="1" cellpadding="0" cellspacing="0" class="loginBg"> <asp:Panel runat="server" ID="pnlLoginIn" style="width:100%;"> <tr> <td colspan="2"> <div class="min500"></div> </td> </tr> <tr> <td style="padding-left:0px;font-family:Verdana;font-size:70%;width:30%;"> Username </td> <td style="padding-right:0px;width:70%;" align="left"> <asp:TextBox id="txtUsername" runat="server" Width="90px" /></td> <asp:RequiredFieldValidator ID="rfvUserName" runat="server" ErrorMessage="*" ControlToValidate="txtUsername" ValidationGroup="credentials" Display="Dynamic" /> </tr> </asp:Panel> </table> </form> -40575329 0
What your IDE means is likely:
(p) -> new ReadOnlyStringWrapper(p.getValue()); No return needed.
I am very new at all this c# Windows Phone programming, so this is most probably a dumb question, but I need to know anywho...
IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings; if (!appSettings.Contains("isFirstRun")) { firstrunCheckBox.Opacity = 0.5; MessageBox.Show("isFirstRun not found - creating as true"); appSettings.Add("isFirstRun", "true"); appSettings.Save(); firstrunCheckBox.Opacity = 1; firstrunCheckBox.IsChecked = true; } else { if (appSettings["isFirstRun"] == "true") { firstrunCheckBox.Opacity = 1; firstrunCheckBox.IsChecked = true; } else if (appSettings["isFirstRun"] == "false") { firstrunCheckBox.Opacity = 1; firstrunCheckBox.IsChecked = false; } else { firstrunCheckBox.Opacity = 0.5; } } I am trying to firstly check if there is a specific key in my Application Settings Isolated Storage, and then wish to make a CheckBox appear checked or unchecked depending on if the value for that key is "true" or "false". Also I am defaulting the opacity of the checkbox to 0.5 opacity when no action is taken upon it.
With the code I have, I get the warnings
Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string'
Can someone tell me what I am doing wrong. I have explored storing data in an Isolated Storage txt file, and that worked, I am now trying Application Settings, and will finally try to download and store an xml file, as well as create and store user settings into an xml file. I want to try understand all the options open to me, and use which ever runs better and quicker
-34817389 0mysqli_query() can only execute 1 query, if you want to execute multiple queries, you need:
if (mysqli_multi_query($conn, $sql)) {
-18359122 0 postgres, contains-operator for multidimensional arrays performs flatten before comparing? The following query:
SELECT ARRAY[[1,2,3], [4,5,6], [7,8,9]] @> ARRAY[2, 3, 5]; gets responded with true and not false as expected, since the array[2, 3, 5] doesn't exist in the source array. Any ideas how can it happen? Maybe flatten is applied to multidimensional arrays?
Since this specific issue seems to be resolved but it hasn't been addressed in an answer, I'll make the general remark that when trying to debug an error that pops up in the jQuery/jQuery UI/etc files, it's usually not actually an error IN THAT FILE, it's an error in your usage of it that isn't actually breaking until it gets down into jQuery. So you really want to just figure out "what Javascript that I wrote was being run right before that broke?", and start there.
-35961223 0Use the file() function in PHP to split each line of the file into an array then set each element of the array equal to it's respective variable. For example:
$lines = file('user1.txt'); $firstname = $lines[0]; $lname = $lines[1]; $age = $lines[2]; $gender = $lines[3];
-26600737 0 Once buyer login to their paypal account during checkout, the buyer will be able to see their email and shipping address as shown in the image for PayPal Payment Standard buttons such as buynow, addto cart.
If you are using Express checkout Integration, you can use GetExpressCheckoutDetails API to retrieve the buyer information and display in the order summary page on your website(not in paypal checkout page). 
In Rails, you can organize controllers into folders and keep your structure nice with namespacing. I'm looking for a similar organizational structure in Symfony 1.4.
I was thinking of organizing multiple actions.class.php files in an actions folder, but all I came across was using independent action files, one for each action... like this:
# fooAction.class.php class fooAction extends sfActions { public function executeFoo() { echo 'foo!'; } } But I'd have to develop a whole new routing system in order to fit multiple actions into that file, which is... silly.
Really I'm just looking to make Symfony into Rails, (again, silly, but I'm stuck with Symfony for this project) so I'm wondering if there's a better way....?
Thanks.
-13002233 0You were close.
a.menuLink:link { color: green; } Was what you intended to achieve. But try this:
a.menuLink { color: green; } Would mean a a with a classname of menuLink, the :link is redundant.
.menuLink a:link Would mean a inside of an element with a classname of menuLink.
I'm working with this on JavaScript:
<script type="text/javascript"> var sURL = "http://itunes.apple.com/us/app/accenture-application-for/id415321306?uo=2&mt=8&uo=2"; splitURL = sURL.split('/'); var appID = splitURL[splitURL.length - 1].match(/[0-9]*[0-9]/)[0]; document.write('<br /><strong>Link Lookup:</strong> <a href="http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/wa/wsLookup?id=' + appID + '&country=es" >Lookup</a><br />'); </script> This script takes the numeric ID and gives me 415321306.
So my question is how can I do the same thing but using PHP.
Best regards.
-24214469 0What's happening is the Dependency Property is getting Registered multiple times under the same name and owner. Dependency Properties are intended to have a single owner, and should be statically instanced. If you don't statically instance them, an attempt will be made to register them for each instance of the control.
Make your DependencyProperty declaration static. Change it from:
public DependencyProperty SomeStringValueProperty = DependencyProperty.Register("SomeStringValue", typeof(string), typeof(ExampleUserControl)); To:
public static DependencyProperty SomeStringValueProperty = DependencyProperty.Register("SomeStringValue", typeof(string), typeof(ExampleUserControl));
-33612022 0 Although it requires a 3rd party tool, these days I use curl. The -X option allows me to specify the HTTP verb. Windows has a few bash clients that allow you to run curl including Cygwin.
$ curl -H "Content-Type: application/json" -X POST -d '{value: "600"}' http://localhost:8888/my/endpoint
Check your main method:
public static void main(String[] args) throws Exception { new Test().searchBetweenDates(startDate, endDate); searchBetweenDates(startDate, endDate); the parenthesis is missing. It should be:
public static void main(String[] args) throws Exception { new Test().searchBetweenDates(startDate, endDate); searchBetweenDates(startDate, endDate); }
-9838299 0 How to debug a Rails application:
You're sending something called "books.xls", and correctly signalling that it's an Excel spreadsheet... but it isn't. You've completely missed the step of actually creating an Excel spreadsheet containing your data (which is probably 80% of the work here).
Try searching the web for how to create an excel spreadsheet in Python.
-20976898 0Firstly, the k-means clustering algorithm doesn't necessarily produce an optimal result, thus that's already a fairly significant indicator that it might have different results from different starting points.
It really comes down to the fact that each cluster uses the points in its own cluster to determine where it should move to - if all the clusters find their way to the centre of their respective points, the algorithm will terminate, and there can be multiple ways this can happen.
Consider this example: (4 points indicated by . and 2 clusters indicated by x)
. . . x . x x versus . . . x . Both the left and the right side have converged, but they're clearly different (the one on the right is clearly worse).
To find the best one you can pick the result that minimizes the sum of square distances from the centres to each of the points classified under it (this is, after all, the goal of k-means clustering).
-2118469 0Use ViewState between postbacks otherwise value of property will be lost.
public string UrlForRedirecting { get { object urlForRedirecting = ViewState["UrlForRedirecting"]; if (urlForRedirecting != null) { return urlForRedirecting as string; } return string.Empty; } set { ViewState["UrlForRedirecting"] = value; } }
-29405880 0 mySQL group by 3 columns I have a query here that group by 3 columns and count the total rows
SELECT count(*) FROM ( SELECT date,bankName FROM table GROUP BY date,bankName,referenceNo ) a; Basically, this query is used for pagination. I have two queries before this one.
I have 166,000 rows of data now and this query taking 1.23 seconds to return the result which is not nice to use when the data grows. What should I do?
-29769393 0 Bash rename files with underscoreI have files that are named CULT_2009_BARRIERS_EXP_Linear.dbf
and would like to rename them to CULT_BARRIERS_EXP_Linear.dbf . The files have a date prefixed with them which is always different showing when it was captured. I have tried to replace them with regular expressions. i want to test the string if it contains numbers and then rename. I have used
if [[ $file =~ [0-9] ]]; then rename -v "s/[0-9]//g" * && rename -v s/[_]_/_/ *; which partially works. But I would ideally like to have one rename command as it is good practice
-2041870 0Probably the easiest is getting a heap dump by VisualVM. JDK also includes related tools, as the jmap tool.
-37210218 0I prefer to have NO extra LIBRARY PATHS in Tools Options, in every Delphi version, and to have each project have its own search path.
I prefer to have my settings exist and be the same for all build configurations. To do this, I make sure that I use the root nodes. This is unfortunately not as straightforward in Delphi 2007 since you have a Build = Debug setting and Build = Release setting, and if I remember correctly, there is no ROOT node in Delphi 2007.
For you, in Delphi 2007, you may have to pay special attention to keeping the values in the debug and the release branch the SAME manually as I believe you can't do this automatically in Delphi 2007.
To answer your question there is no need for a full path and generally no need to use $(PROJECTDIR). There is also no need for a full path. You need to use relative paths, like this: ..\Lib\Dir1;..\Lib\Dir2;..\Lib\Dir3 and so on. My goal for using relative paths is to satisfy the desire to check out code and build it anywhere. Code which can only be built when checked out to a certain directory (C:\YOURAPP) is sloppy, dare I say downright lazy, as well as impractical, and also so sadly common that you might think it was a best practice. Such sloppy no-effort codebases prevent proper continuous integration practices, prevents having multiple working copies that are at different branches or major versions, and so on, and is often worked around by keeping all the code barely building in some kind of virtual machine. Nobody even knows how to set their code up, so they shove it in a VM and let the mess moulder.
When you absolutely CAN NOT use relative paths such as when you don't know where the other stuff is, you should set your OWN in house root folder variable, if your company was called ACME, I would call it ACMEROOT, and I would set it up myself. At my current company we have such a root variable we call it PS because our product's initial capitals are P and S. Then we use $(PS) similar to the way you see $(BDS) used in the library path.
Sometimes I find it useful to have an external tool that I have written that will set up the environment variables for me, directly writing to the IDE the environment variables that I want, and I have a practice of checking out code from version control and running this tool to set up my environment. It so happens I can now check the code onto a fresh computer and run it without any manual effort to set up packages, install components, configure library paths, or projects, and everything just builds. Unfortunately the IDE does not provide everything you need for such a practice, but there are a variety of third party tools that can provide you with a portable clean easy to build codebase.
So I found the answer to my own question :
I use this :
data: 'start='+ start+$('#EventAdd').serialize(), instead of this
data: $('#EventAdd').serialize(),start: start,
-16875368 0 This is a good use case for promises.
They work like this (example using jQuery promises, but there are other APIs for promises if you don't want to use jQuery):
function doCallToGoogle() { var defer = $.Deferred(); callToGoogleServicesThatTakesLong({callback: function(data) { defer.resolve(data); }}); return defer.promise(); } /* ... */ var responsePromise = doCallToGoogle(); /* later in your code, when you need to wait for the result */ responsePromise.done(function (data) { /* do something with the response */ }); The good thing is that you can chain promises:
var newPathPromise = previousPathPromise.then( function (previousPath) { /* build new path */ }); Take a look to:
To summarize promises are an object abstraction over the use of callbacks, that are very useful for control flow (chaining, waiting for all the callbacks, avoid lots of callback nesting).
-18041981 0Well the error is quite logical
if command == "iam": self.name = content msg = self.name + "has joined" elif command == "msg": msg = self.name + ": " + content print msg In the first if clause you assign a value to self.name which may either rely on assumption that self.name exists somewhere, or on assumption that it is new and needs to be declared, but in elif you seem to assume with certainty that self.name already exists, it turns out it doesn't so you get an error.
I guess your safest option consists of simply adding self.name at the beginning of dataReceived method:
def dataReceived(self, data): self.name = "" this will get rid of the error. As an alternative you could also add self.name to init method of IphoneChat.If you need self.name in other functions not only in dataReceived then adding init with self.name is the way to go, but from your code it seems you only need it in datareceived so just add it there. Adding self.name in init would look like this:
class IphoneChat(Protocol): def __init__(self): self.name = "" or you can also simply do
class IphoneChat(Protocol): name = "" and then go on with name instead of self.name.
-29016131 0 SVG: Why element is not displaying in I'm attempting to put a After scratching my head for a bit I started looking at the properties in the two tabs (both in Chrome) and the only 2 things at this point that jump out me are that when I hover over the As an experiment, I attempted to set the height and width explicitly in the CSS for 'p' but chrome just shows this as an 'invalid property'. Assuming this is the problem, I'm a little lost as to how to control a property that I'm not allowed to specify. Can someone help with some advice on how to debug this further? There's clearly something about what I am doing that is causing this but I'm not sure where to look next. EDIT: I don't know why I didn't notice this before but I see a difference that may help explain this. The fiddle shows the properties for the The application shows these properties: I assume this has something to do with how d3 is adding the I am newbie in using of await/async and windows phone 8.1 programming. I need to run async method simulateously in more than one thread. May be four, because my phone has four cores. But i cannot figure it out :-( This is example of my async method. Four threads can be ensured by using of a semaphore object, but how i can run it in simulatously running threads? EDIT: This is my code which explores folder structure and log metadata about files into database. I want to speed up execution of this code by calling method "async LogFilesFromFolderToDB(StorageFolder folder)" simulateously in separate thread for each folder. Method: async LogFilesFromFolderToDB(StorageFolder folder) looks like: You'll need to subclass Consider this example Seems like it would make more sense to compute the parameters within if/else or switch logic, store them in variables, and then call the function afterwords with whatever parameters you computed. I have many elscreen tabs(frames?) that are horizontally and vertically split. I'd like to be able to save the current buffers, windows layout in each frame, and the frames themselves. In short, I'd like to be able to close emacs and re-open with relatively the same state as when I closed it. (I think I got the terminology right) The issue was the Class assignment that was with the Search Icon. After removing the line To go from an DateTime in the "Excel Format" to a C# Date Time you can use the DateTime.FromOADate function. In your example above: To write it out for display in the desired format, use: If you are wondering where the discrepancies in Excel's date handling come from, it's supposed to be on purpose: When Lotus 1-2-3 was first released, the program assumed that the year 1900 was a leap year even though it actually was not a leap year. This made it easier for the program to handle leap years and caused no harm to almost all date calculations in Lotus 1-2-3. When Microsoft Multiplan and Microsoft Excel were released, they also assumed that 1900 was a leap year. This allowed Microsoft Multiplan and Microsoft Excel to use the same serial date system used by Lotus 1-2-3 and provide greater compatibility with Lotus 1-2-3. Treating 1900 as a leap year also made it easier for users to move worksheets from one program to the other. Although it is technically possible to correct this behavior so that current versions of Microsoft Excel do not assume that 1900 is a leap year, the disadvantages of doing so outweigh the advantages. Source: http://www.ozgrid.com/Excel/ExcelDateandTimes.htm I try to catch resize events with jquery and the Everything works fine, except when I use the maximize Button in Firefox, the event is not thrown. Is there something wrong here? I have a php code running on my server that i call my web service.It processes the data in send integer value.How can i get that?Here is my request url : Update Comment : I have a php file on my server.It takes 3 arguments and register my users and returns value like 1(for success,2 for duplicate).I need to send request to my server as : How can i send this request to server and get the return value from server? I have some signup form that had email and login text fields as table cells and signup button as button in footer view. That all functioned superb, here is the code My question is how to add another button next to this one. By using [self.tableView.tableFooterView addSubview:...] buttons are not shown and if I use some other UIView, place buttons there and then say that the footerView is that UIView, I see the buttons, but am unable to press them. I hope that this isn't too confusing and that you understand my problem. I have a multi array and I am using the max function to return the highest value, however I'd like it to return the name? How can I do that? Thanks!! I'm trying to add line numbers using NoodleLineNumberView. The issue I'm having is that the line numbers dont line up properly with thier line number.I have to type 16 lines, then line 1 gets marked as line 16. If I scroll down past the top of the text I can see the other line numbers there, its just like all over the are shifted up. I subclassed a You can use If you want to generate random locations, you can use This will randomly generate a number from I'm trying to create an ICAL file based on a single entry inside an Expression Engine channel but my methods of accomplishing this are failing. I've tried the following: Creating a session variable with the entry ID but there seems to be no way of adding this variable to the {exp} query: I haven't tried just making a flat file each time the single entry page is accessed with Is there a way with PHP to make the file when I click a button? Maybe firing off a function written in the page so I don't need to pass or detect the This is likely a config issue, but I'm new to Webpack and haven't been able to figure it out after a few days. I'd appreciate some help! Packages webpack.config.js With a completely empty entry file, I get the following error when trying to run webpack. If I actually require a jade file within entry.js, I get a different error: However, if I comment out the jade loader line in Any idea what's up? Why not try something like this: To get the directories and files to an unlimited depth, combine that with a recursion method based on I will explain how solved this problem. First of all the refresh token process is critical process. In my application and most of applications doing this : If refresh token fails logout current user and warn user to login .(Maybe you can retry refresh token process by 2-3-4 times by depending you) I recreated my refresh token using So this is my new refresh token process : My refresh method: In authenticate method : Maybe this - JOIN instead of subselect: I see Is there a PHP function for this (can't find it, only modified versions of EDIT: Found the answer: use mcrypt ciphers When we are using ViewState or cookies or cashing or sessions where are we storing the information? I know when we use sessions we can store data in sql server or web server. is there any other way we store data when we are using sessions. One more questions when i get the data from sql server and bind it to the dataset or datatable where that data is going to store(the dataset records)? I want to play animation on a key on custom keyboard. I've created the custom keyboard and everything is working fine, except the animation which is kind of popping up of key. I'm accomplishing it through AnimationDrawable. When Now I want to know how can I get the exact view handle of any key or why this animation is not working. Thanks in advance. You can do something like: just make sure the file is maked as "Resource" in visual studio. Alternatively you can mark it as "Content" and use it like this: I don't know if you need to assign the background programatically (because you can do it in markup), but if you do here is what you need to say: [FURTHER] in order set margin programmatically: First, your code does not have any effect. Hash table "breaks" the order. The order of elements in hash table depends on the particular hash implementation. There are 2 types of Maps in JDK: HashMap and SortedMap (typically we use its implementation TreeMap). BTW do not use Hashtable: this is old, synchronized and almost obsolete implementation). When you are using HashMap (and Hashtable) the order of keys is unpredictable: it depends on implementation of If you wish your keys to be extracted in the same order you put them use I am using You almost get the answer from Matthew, all you need to do is to add cast : HSQL also provides support for interpreting csv files as http://swift-lang.org/tryswift/ doesn't look like it's anything to do with Apple Swift. The "try Swift" page you're using is for Swift, not Swift. Note that Apple's has the stylised swift in its logo heading downwards; the parallel scripting language Swift is heading upwards :) To try Apple's Swift in a similar way, you'll need the Xcode 6 beta and a "playground" file. I recommend this. If you have a emulator preview connected first go inside Android Wear app to the emulator and choose FORGET. Later use the commands all are using That work for me. I'm trying to view our peak bytes received/sec count for an eventhub in order to scale it properly. However, the portal is showing vastly different results from the "daily" view to the "hourly" view. This is the graph using the "hourly" view: From here, it looks like I'm peaking at around 2.5 MB/s. However, if I switch to the "daily" view, the numbers are vastly different: So I can't make sense of this. It's the exact same counter, showing vastly different results. Anyone know if the Azure portal performs any "adding" or similar? Edit: Notice that the counter is "bytes received per second". It shouldn't matter if I look at the hourly or daily view, the number of items per second shouldn't be affected by that (tho it clearly is). Most or all of Endeca's objects have internal constructors. I'm working on a good project that lacks great test coverage around the Endeca API, are there any good strategies to unit testing the interactions with Endeca? So far the best we have is kind of a poor man's adapter pattern: We can then mock our own type, DimValue. Is this the best way to keep their API as testable as can be? Or is there another method that is preferred to this? The h values need to be adjusted for the three cases prior to calculating the cos values dependent on them. i.e.: You will also need to make sure that none of the rr,gg,bb values end up outside the 0..255 interval: ... etc you need both In your case, we decided to expose our web app functionality as web services, because of: The kind of web services you use depends on your requirements: people normally expose their API as a REST api, which is more or less an http CRUD wrapper over your application entities. You can use standard SOAP web services, which is more of a procedural point of view. Up to you to decide, I hope this was useful I don't like Whenever I have to do significant processing, I cheat and use a local This way, the exception will be throw only on first use, and yet the object will be This is quite a powerful idiom to delay execution. It had a little overhead (basically the compiler checks a flag each time it enters the method), but better worry about correctness first ;) If this is called from multiple threads: Guideline: only use Unfortunately, it is illegal to reference a variable/param in a match pattern in XSLT 1.0. However, you can reference your This won't process any undesired elements and no other templates need to specify the language to match. ColumnAttribute with IsPrimaryKey=true missing in EmployeePhoneNumber Ari, A good reference to how to accomplish "invisible" instance variable declarations can be found here with credit respectfully given to Matt Gallagher. Hope it helps, Frank try this Refer this More about json Is there a way to do an accent insensitive search using grep, preferably keeping the --color option ? By this I mean I know I can use I have a controller in which there is a "viewless" action. That controller is used to set a variable called This is my story board. I want to set the ttitle for this I have also tried: But it doesn't set any title. Why is that? Pleasehelp me. Thanks With a layout as shown in the example and the range in Sheet1 named I have a broadcast receiver that works fine but now I want to send send notifications to status bar. Since BroadcastReceiver cannot do it directly it looks like I need to create a service to do that for me correct? So I created a service using the examples provided at http://developer.android.com/reference/android/app/Service.html Other than a few small tweaks it's that code. I start the service from the broadcast receiver with context.startService(new Intent(context, AlertUser.class)); What happened is it did put out the msg in the status bar. then when I did a clear and had it generate a new msg the service code did not execute. Do I interact with he service differently once started? From what I read no if part of same process. Also how would I share information like a string from the the BroadcastReceiver to the service to that it is info to display in the notification? Thanks, Frank Your problem is thinking of the state as being all the permutations of what people can see. In general you should just be thinking of the state as the facts of the situation, and calculate individual views of those facts as they are needed. If one player (eg, A) cannot see another player (eg. B), then you just don't send player B's information to player A until the situation changes. The answer suggested; [theTableView reload] definitely works fine. If you update the table every view seconds, however, your users will going to hate you and down-vote your app. No question. Try to capture the reloading data in a notification handler. In that handler, check if the updated data belongs somewhere between the currently visible cells, if so, update the currently visible view. If not, ignore the updated data (but do add it to your underlying model). If the user scrolls further, after your update, cellForIndexPath: is called and the updated data will be drawn automatically. reload is quite heavy to do every view seconds, certainly with a lot of data. drawing might get screwed up or worse.. This answer may shed some light. How do you sort a dictionary by value? They sort by value but could the linq statement be altered to sort by key? If you need to do AJAX request, turn-off the VerifyCsrfToken middleware on your Kernel.php file. You can also edit your VerifyCsrfToken.php middleware file to exclude certain URLs like this way: Is it possible to implement message segmentation using JMS as it is in using Native IBM API as shown here. One posible solution I have read is message grouping for JMS. is anyone using this an alternative solution to Segmentation, using JMS? I have rails helpers ( ...which produces handlebars templates: How can I render I think I should remove It is hard to help unless you post a bit more detail and some code. Without that here are some suggestions that might help. You will need a submit button or some JavaScript to post the form inside the partial. If you have another form on the page which you are submitting, it will not include data from other forms and inputs on the page. Also to form has to post back to a controller action, a partial just a helper to render a view inside another view. The answer is correct in a certain context, for simple select statements over a DB link, you'll get this error: ORA-22992: cannot use LOB locators selected from remote tables. From the errors manual: Cause: A remote LOB column cannot be referenced. I also had trouble finding definitive documentation on this...but we just ran into the same issue in our data warehouse. However, there are several work-arounds available, pulling the data over or creating a view for example. New with Matlab. When I try to load my own date using the NN pattern recognition app window, I can load the source data, but not the target (it is never on the drop down list). Both source and target are in the same directory. Source is 5000 observations with 400 vars per observation and target can take on 10 different values (recognizing digits). Any Ideas? I have developed an online exam using the Moodle software which is written in PHP. Now I want to restrict the person who is taking the test without being able to navigate to other tabs or other windows by generating a mouserover pop-up. Following is the I have a code for the alert pop-up when the user leaves the window:<p> element inside a <foreignobject> inside an <svg> node in chrome but I am not seeing the text. I have inspected the element and the DOM model shows the structure I expect. I created this jsfiddle by copying from the DOM model and lo and behold it works exactly as I desire in the fiddle.<foreignobject> or <p> element in the fiddle, it shows a grey box the area where it's displayed. When I do this in the real application, it does the same for the <foreignobject> but I see nothing for the <p> element. The second difference is that in the fiddle, the <p> element shows a height and a width of 54px and 100px (respectively) but in the actual application they both are reported to be 'auto'.<p> element as:
<p> element. I will try to create a fiddle that creates the elements with d3.public async Task GetFilesAsyncExample(StorageFolder root) { IReadOnlyList<StorageFolder> folders = await root.GetFoldersAsync(); //DO SOME WORK WITH FOLDERS// } Stack<StorageFolder> foldersStack = new Stack<StorageFolder>(); foldersStack.Push(root); while (foldersStack.Count > 0) { StorageFolder currentFolder = foldersStack.Pop(); await LogFilesFromFolderToDB(null, currentFolder);// Every call of this method can be done in a separate thread. IReadOnlyList<StorageFolder> folders = await currentFolder.GetFoldersAsync(); for (int i = 0; i < folders.Count; i++) foldersStack.Push(folders[i]); }
-7100174 0 async Task LogFilesFromFolderToDB(StorageFolder folder) { IReadOnlyList<StorageFile> files = await folder.GetFilesAsync(); //SOME ANOTHER CODE// } UITableViewCell and override -layoutSubviews. When the cell's editing bit is set to YES, -layoutSubviews will automatically be invoked. Any changes made within -layoutSubviews are automatically animated.
-1794705 0 - (void)layoutSubviews { [super layoutSubviews]; CGFloat xPosition = 20.0f; // Default text position if (self.editing) xPosition = 40.0f; CGRect textLabelFrame = self.textLabel.frame; textLabelFrame.origin.x = xPosition; self.textLabel.frame = textLabelFrame; } class: col-mw-3 it ran fine, and in all of the browsers. Also make sure nothing is covering the <a> Tag as well! DateTime myDate = DateTime.FromOADate(41172); myDate.ToString("dd/MM/yyyy");
$(window).resize(function() { } NSString *requestURL=[NSString stringWithFormat:@"%@?u=%@& p=%@&platform=ios",url,txtUserName.text,txtPassword.text]; url="http://smwebtech.com/Pandit/web_service/signup.php?u=Test&p=password&platform=ios" frame = CGRectMake(boundsX+85, 100, 150, 60); UIButton *signInButton = [[UIButton alloc] initWithFrame:frame]; [signInButton setImage:[UIImage imageNamed:@"button_signin.png"] forState:UIControlStateNormal]; [signInButton addTarget:self action:@selector(LoginAction) forControlEvents:UIControlEventTouchUpInside]; self.navigationItem.hidesBackButton = TRUE; self.tableView.tableFooterView.userInteractionEnabled = YES; self.tableView.tableFooterView = signInButton; self.view.backgroundColor = [UIColor blackColor]; $total = array($total_one => 'Total One', $total_two => 'Total Two'); echo max(array_keys($total)); NSScrollView and added this bit of code. Thats all that should be needed. Is anyone else having this issue, or solved it?- (void)awakeFromNib { self.gutter = [[NoodleLineNumberView alloc] initWithScrollView:self]; [self setVerticalRulerView:self.gutter]; [self setHasHorizontalRuler:NO]; [self setHasVerticalRuler:YES]; [self setRulersVisible:YES]; } 
input to accept a string from the user. As you'll have two co-ordinates to punch in, perhaps call this twice. Once you get the strings, cast the locations to integer via int().random.randrange(). The syntax for random.randrange() is like so:num = random.randrange(start, stop) #OR num = random.randrange(start, stop, step) start to stop excluding stop itself. This is pretty much the same as with range(). The first method assumes a step size of 1, while the second method you can specify an optional third parameter which specifies the step size of your random integer generation. For example, if start = 2, stop = 12 and step = 2, this would randomly generate a integer from the set of [2, 4, 6, 8, 10].
$_GET function seems to be frowned upon in EE{exp:channel:entries channel="gallery" entry_id="MY_PHP_VARIABLE" limit="1" show_future_entries="yes"}fwrite() and linking directly to it, but that seems like a costly move.entry_id?
var webpack = require('webpack'); var path = require('path'); module.exports = { // ... resolve: { extensions: ["", ".webpack.js", ".web.js", ".json", ".js", ".jade" ], root: [ path.join(__dirname, 'src/js'), path.join(__dirname, 'node_modules') ], modulesDirectories: ['node_modules'], }, module: { loaders: [ { test: /\.json$/, loader: "json-loader" }, { test: /modernizr/, loader: "imports?this=>window!exports?window.Modernizr" }, { text: /\.jade$/, loader: "jade-loader" } ] } // ... }; ERROR in ./~/jade/lib/runtime.js Module build failed: Error: unexpected token "indent" at MyParser.Parser.parseExpr (/Users/name/project/code/assets/node_modules/jade/lib/parser.js:252:15) at MyParser.Parser.parse (/Users/name/project/code/assets/node_modules/jade/lib/parser.js:122:25) at parse (/Users/name/project/code/assets/node_modules/jade/lib/index.js:104:21) at Object.exports.compileClientWithDependenciesTracked (/Users/name/project/code/assets/node_modules/jade/lib/index.js:256:16) at Object.exports.compileClient (/Users/name/project/code/assets/node_modules/jade/lib/index.js:289:18) at run (/Users/name/project/code/assets/node_modules/jade-loader/index.js:170:24) at Object.module.exports (/Users/name/project/code/assets/node_modules/jade-loader/index.js:167:2) @ ./entry.js 1:11-85 ERROR in ./entry.js Module build failed: Error: unexpected text ; var at Object.Lexer.fail (/Users/name/project/code/assets/node_modules/jade/lib/lexer.js:871:11) at Object.Lexer.next (/Users/name/project/code/assets/node_modules/jade/lib/lexer.js:930:15) at Object.Lexer.lookahead (/Users/name/project/code/assets/node_modules/jade/lib/lexer.js:113:46) at MyParser.Parser.lookahead (/Users/name/project/code/assets/node_modules/jade/lib/parser.js:102:23) at MyParser.Parser.peek (/Users/name/project/code/assets/node_modules/jade/lib/parser.js:79:17) at MyParser.Parser.tag (/Users/name/project/code/assets/node_modules/jade/lib/parser.js:752:22) at MyParser.Parser.parseTag (/Users/name/project/code/assets/node_modules/jade/lib/parser.js:738:17) at MyParser.Parser.parseExpr (/Users/name/project/code/assets/node_modules/jade/lib/parser.js:211:21) at MyParser.Parser.parse (/Users/name/project/code/assets/node_modules/jade/lib/parser.js:122:25) at parse (/Users/name/project/code/assets/node_modules/jade/lib/index.js:104:21) webpack.config.js and require the jade file with the inline syntax require('jade!template.jade') -- everything works okay.foreach (var file in System.IO.Directory.GetFiles(k)) { zip.AddFile(file); } System.IO.Directory.GetDirectories("path") - should be pretty straightforward methinks.HttpUrlConnection which simplest connection method. No cache , no retries , only try connection and get answer .public boolean refreshToken(String url,String refresh,String cid,String csecret) throws IOException { URL refreshUrl=new URL(url+"token"); HttpURLConnection urlConnection = (HttpURLConnection) refreshUrl.openConnection(); urlConnection.setDoInput(true); urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlConnection.setUseCaches(false); String urlParameters = "grant_type=refresh_token&client_id="+cid+"&client_secret="+csecret+"&refresh_token="+refresh; // Send post request urlConnection.setDoOutput(true); DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = urlConnection.getResponseCode(); Log.v("refresh http url","Post parameters : " + urlParameters); Log.v("refresh http url","Response Code : " + responseCode); BufferedReader in = new BufferedReader( new InputStreamReader(urlConnection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // handle response like retrofit, put response to POJO class by using Gson // you can find RefreshTokenResult class in my question Gson gson = new Gson(); RefreshTokenResult refreshTokenResult=gson.fromJson(response.toString(),RefreshTokenResult.class); if(responseCode==200) { //handle new token ... return true; } //cannot refresh Log.v("refreshtoken", "cannot refresh , response code : "+responseCode); return false; }
-38564716 0 @Override public Request authenticate(Route route, Response response) throws IOException { String userRefreshToken="your refresh token"; String cid="your client id"; String csecret="your client secret"; String baseUrl="your base url" refreshResult=refreshToken(baseUrl,userRefreshToken,cid,csecret); if (refreshResult) { //refresh is successful String newaccess="your new access"; return response.request().newBuilder() .header("Authorization", newaccess) .build(); } else { //refresh failed , maybe you can logout user return null; } }
-3115524 0 How do I encode something in PHP with a key? SELECT t1.week_val, CASE t1.week_val WHEN 1 THEN t2.hour_val ELSE t1.hour_val END AS hour_val FROM table_name t1 LEFT JOIN table_name t2 ON t2.week_val = t1.week_val + 1 base64_encode can encode values, but without a key. I need a function that takes a salt and data, encodes it, and can be decoded with the same salt (but if you try to decode it without the salt, it gives you gibberish).base64_encode).animation.start() is called, only the first frame of animation is shown and it stucks there. Below is my simple code for animation. enterKey.icon = ContextCompat.getDrawable(getActivity(), R.drawable.enter_button_animation); AnimationDrawable drawable = (AnimationDrawable) enterKey.icon; drawable.start(); mKeyboardView.invalidateAllKeys(); KeyboardView.Key.icon is just a drawable. Given is my enter_button_animation.xml: <?xml version="1.0" encoding="utf-8"?> <animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/selected" android:oneshot="false" > <item android:drawable="@drawable/enter_key_1" android:duration="50" /> <item android:drawable="@drawable/enter_key_2" android:duration="50" /> <item android:drawable="@drawable/enter_key_3" android:duration="50" /> <item android:drawable="@drawable/enter_key_4" android:duration="50" /> </animation-list>
-6786715 0 $("#grid").kendoGrid({ dataSource: { type: "json", pageSize: 10, serverPaging: true, transport: { read: "http://whatever" } }, selectable: "cell", pageable: true, columns: ["ProductID", "ProductName"], change: function() { var dataItem = this.dataSource.view()[this.select().closest("tr").index()]; alert(dataItem.UnitPrice); } } <Button> <Button.Background> <ImageBrush Source="/AlarmClock;component/Images/page_preview.png" /> </Button.Background> </Button> <ImageBrush Source="/Images/page_preview.png" /> viewButton.Background = new ImageBrush { Source = new BitmapImage(new Uri("", UriKind.Relative)) }
-7784436 0 viewButton.Margin = new Thickness(left, top, right, bottom); hashCode() method of class you are using as keys of your map. If you are using TreeMap you can use Comparator to change this logic. LinkedHashMap.BackgroundWorker a lot and can tell that RunWorkerCompleted event is definitely ran in UI thread. Also, you can pass the DoWork result to according eventArgs field and then, in RunWorkerCompleted take it from eventArgs to perform some UI-dependent operations with it, as mentioned here
-2601346 0 Select CAST(SUM(timediff(timeOut, timeIn)) as time) as totalhours FROM volHours WHERE username = 'skolcz' ResultSets.adb forward tcp:4444 localabstract:/adb-hub adb connect localhost:4444 

public class DimValue : IDimValue { public DimValue(Dimension dim, DimVal dimValue) { Dimension = dim; Value = dimValue; } public virtual bool IsNavigable() { return Value.IsNavigable(); } public virtual long Id() { return Value.Id; } // and so on... } if(h<(2.0f*pi/3.0f)){ y = in*( 1.0f + (s*cos(h) / cos(pi/3.0f-h)) ); b = x; r = y; g = z; }else if(h<(4.0f*pi/3.0f)){//&&2pi/3<=h h -= 2*pi/3; y = in*( 1.0f + (s*cos(h) / cos(pi/3.0f-h)) ); r = x; g = y; b = z; }else{ //less than 2pi && 4pi/3<=h h -= 4*pi/3; y = in*( 1.0f + (s*cos(h) / cos(pi/3.0f-h)) ); g = x; b = y; r = z; } if (rr < 0) rr = 0; if (rr > 255) rr = 255; hidden.bs.collapse and shown.bs.collapse
-21991956 0 $(document).ready(function() { function toggleChevron(e) { $(e.target) .prev('.panel-heading') .find("i") .toggleClass('fa-question fa-angle-up'); } $('#accordion').on('hidden.bs.collapse shown.bs.collapse', toggleChevron); });
static data members much, the problem of initialization being foremost.static instead:class MyClass { public: static const SomeOtherClass& myVariable(); }; const SomeOtherClass& MyClass::myVariable() { static const SomeOtherClass MyVariable(someOtherFunction()); return MyVariable; } const.
boost::once in the Boost.Threads libraryconst, you may not care if it's initialized multiple times, unless someOtherFunction does not support parallel execution (beware of resources)static or global variables instantiation for simple objects (that cannot throw), otherwise use local static variables to delay execution until you can catch the resulting exceptions.$lang parameter any time you apply templates. So, for example, in the root template (i.e. a template that matches / or some other sufficiently top-level node), you could specify that you only want to apply templates to elements that have an xml:lang attribute equal to the value of your param (or no xml:lang at all):<xsl:apply-templates select="*[not(@xml:lang) or @xml:lang=$lang]" /> for (NSDictionary *status in statuses) { NSString *Tstatus = [status objectForKey:@"TStatus"] if([Tstatus isEqualToString:@"100001"){ //Do your code here } } grep --secret-accent-insensitive-option aei would match àei but also äēì and possibly æi.iconv -t ASCII//TRANSLIT to remove accents from a text, but I don't see how I can use it to match since the text is transformed (it would work for grep -c or -l) @@ComputedData={}. But the data is computed based on a csv file a user of the application uploaded. Now are users going to see their specific data or will the @@ComputeData be the same for all users? Could someone explain me this concept? I'm really shaky on it. Thank you in advance and sorry for the noob question. FrontViewController So I did this in my FrontViewControlleroverride func viewDidAppear(animated: Bool) { super.viewDidAppear(true) self.navigationController!.navigationBar.topItem!.title = "Home"; } self.title="Home" self.navigationItem.title = "Home" array =VLOOKUP(A2,array,2,FALSE) should show in ColumnC the value from the Sheet1 cell immediately to the right of the value as specified in A2 (of Sheet2). The same formula in D2 with ,2, replaced ,3, should give the corresponding unit price, so appending *B2 should give the Cost. Both formulae may be copied down to suit:
// pseudocode - make it properly object oriented for best results struct player { int teamNumber; bool hidden; }; bool is_friend(player other_guy) { return me.teamNumber == other_guy.teamNumber; } bool can_see(player other_guy) { return (is_friend(other_guy) || !other_guy.hidden); } /** * The URIs that should be excluded from CSRF verification. * * @var array */ protected $except = [ 'ajax/*', 'api/*', ];hs_if, hs_else):= hs_if :current_user do Hello, {{ current_user/name }}! = hs_else do = link_to 'Sign In', sign_in_path {{#if current_user}} Hello, {{ current_user/name }}! {{else}} <a href="/signin">Sign In</a> {{/if}} {{#if current_user}} ... {{else}} ... {{/if}} without nesting hs_else in hs_if?{{/if}} from output, but I can't find way to do it in helper.
-3594733 0 Banner.frame = CGRect(x:0.0, y:self.view.frame.size.height - Banner.frame.size.height, width:Banner.frame.size.width, height:Banner.frame.size.height)
Action: Remove references to LOBs in remote tables.<html> <head> <script type="text/javascript"> function addEvent(obj, evt, fn) { if (obj.addEventListener) { obj.addEventListener(evt, fn, false); } else if (obj.attachEvent) { obj.attachEvent("on" + evt, fn); } } addEvent(window,"load",function (e) { addEvent(document, "mouseout", function (e) { e = e ? e : window.event; var from = e.relatedTarget || e.toElement; if (!from || from.nodeName == "HTML") { // stop your drag event here // for now we can just use an alert alert("Your Test will close in 10 secs unless you return to the page "); } }); }); </script> </head> <body></body> </html>
Is there a possibility to restrict the user with this code and in that case where to append this code to the moodle's actual source code??
Thanks.
-35637885 0Hyperlink tag doesn't have a close tag </a>, if you want to close it make it like this:
<a target="_blank" href="http://url.com" style="text-decoration: underline; color: #000001;"> Call To Action <img src="image/path/triangle.png" border="0" /> </a> Reference:
Also, I recommend you separate design from content.
-35579637 0 Gap in auto-increment IDs on Heroku PostgresI've got a Ruby web app running on Heroku with a Postgres database. I've noticed the auto-incremented IDs have a gap in them around the time that the Postgres database was under "maintenance" by Heroku.
The gap is a one-time thing, and then the IDs increment by 1 again. Like so:
ID | Created at | 2959 | 2016-02-14 21:07:05.149797 | 2960 | 2016-02-14 21:15:05.03284 | 2961 | 2016-02-14 22:59:19.634962 | 2994 | 2016-02-15 09:25:30.969881 | 2995 | 2016-02-15 09:44:38.49678 | 2996 | 2016-02-15 09:51:00.282624 | The maintenance by Heroku happened in between the two records (2961 and 2994) being created, at 2016-02-15 04:00:00.
I've seen an explanation that a failed transaction will result in an ID being skipped over on the next successful commit, but I can't see anything in the application logs to indicate that any records were being created around the time.
-18156020 0I'm not sure I understand fully what is happening in this scenario but here is a solution to your problem:
... casper.then(function() { casper.page.close(); casper.page = require('webpage').create(); }); casper.thenOpen('http://www.yahoo.com/', function(response) { this.wait(1000, function() { this.echo(this.getTitle()); }); }); ... close() - "Close the page and releases the memory heap associated with it. Do not use the page instance after calling this." <- This is from the phantomjs documentation. You need to create a new page instance if you want to continue opening sites. Hope this helps!
-30687242 0 Linear algebra libraries and dynamic parallelism in CUDAWith the advent of dynamic parallelism in 3.5 and above CUDA architectures, is it possible to call linear algebra libraries from within __device__ functions?
Can the CUSOLVER library in CUDA 7 be called from a kernel (__global__) function?
I have tidied up your query a little (although this won't make a massive amount of difference to performance, and there may be typos as I don't have VS to hand). From your edit it seems you are a little confused by deferred execution in LINQ. callDetailsForNodes does not represent your results - it is a query that will provide your results once it is executed.
If you have to do all this querying in process I suggest you add a ToList after the first select and run that in isolation. Then add ToList to the Where clause. Calling ToList will force your query to execute and you will see where the delays are.
One final note - you should pass your records directly to ObservableCollection constructor rather than calling Add for each item. Calling Add will (I think) cause the collection to raise a changed notification which is not a big deal for small lists but will slow things down for larger lists.
var callDetailsForNodes = dtRowForNode.AsEnumerable() .Select(dr => new { caller1 = StringComparer.CurrentCultureIgnoreCase.Compare(dr["F1"], dr["F2"]) < 0 ? dr["F1"] : dr["F2"], caller2 = StringComparer.CurrentCultureIgnoreCase.Compare(dr["F1"], dr["F2"]) < 0 ? dr["F2"] : dr["F1"], time = Convert.ToDateTime(dr["F3"]), filters = dr.Field<string>("F9")}) .Where(dr => (dtMin <= dr.time) && (dtMax >= dr.time) && (lstCallType.Contains(dr.filters)) && (dtMinTime <= dr.time.TimeOfDay) && (dtMaxTime >= dr.time.TimeOfDay) && caller1 == VerSelected || caller2 == VerSelected)) .GroupBy(drg => new { drg.caller1, drg.caller2 }) .Select(drg => new { drg.Key.caller1, drg.Key.caller2, count = drg.Count());
-37296847 0 Type definitions for JavaScript libraries I tried to convert a simple React project from JavaScript to TypeScript, but somehow this doesn't seem to work.
First VSCode shows me sometimes that react isn't a module, even if I installed it with typings and added the typings/index.d.ts to the tsconfig.json files list. When I restart VSCode it works after opening a few files, but it never seems to work right away.
Then I use history and typings also found a history type definition and installed it, but when I try to import history/lib/createBrowserHistory TypeScript doesn't know anything about it and talks about missing modules again.
Here is the code which I am using for deploying a service in Azure,
internal async static Task DeployCloudService(this SubscriptionCloudCredentials credentials) { try { using (var _computeManagementClient = new ComputeManagementClient(credentials)) { Console.WriteLine("Deploying a service..."); var storageConnectionString = await GetStorageAccountConnectionString(credentials); var account = CloudStorageAccount.Parse(storageConnectionString); var blobs = account.CreateCloudBlobClient(); var container = blobs.GetContainerReference(ConfigurationManager.AppSettings["containerName"]); if (!container.Exists()) { Console.WriteLine("Container not found"); }; await container.SetPermissionsAsync( new BlobContainerPermissions() { PublicAccess = BlobContainerPublicAccessType.Container }); var blob = container.GetBlockBlobReference( Path.GetFileName(ConfigurationManager.AppSettings["packageFilePath"])); var blob1 = container.GetBlockBlobReference( Path.GetFileName(ConfigurationManager.AppSettings["configFilePath"])); await _computeManagementClient.Deployments.CreateAsync(ConfigurationManager.AppSettings["serviceName"], DeploymentSlot.Production, new DeploymentCreateParameters { Label = ConfigurationManager.AppSettings["label"], Name = ConfigurationManager.AppSettings["serviceName"], PackageUri = blob.Uri, Configuration = File.ReadAllText((blob1.Uri).ToString()), StartDeployment = true }); Console.WriteLine("Deployment Done!!!"); } } catch (Exception e) { throw; } } The Idea is that package and config file is already there in blobs within some container and I can deploy my service when I am using Configuration = File.ReadAllText(ConfigurationManager.AppSettings["configFilePath"])(which takes the file from the local path and working fine as expected), but since I don't wanna do that I am trying to use the config file from Azure blobs, but File.ReadAllTextis not taking the Uri of my file which I checked is fine and giving System.SystemException {System.NotSupportedException} withbase {"The given path's format is not supported."}.(as its looking for string parameter)
-12864532 0My Question is that how can we use the config file (.cscfg) from the server
Email address is accessible for the authenticated user as long as you request "r_emailaddress" permissions upon authorization.
Take a look at the Oauth Login Dialog that's presented to the user to authorize the application. Notice how "email address" isn't presented as one of the profile fields that the application wants to access. You'll need to modify this line in your code:
var request = new RestRequest { Path = "requestToken?scope=r_basicprofile+r_emailaddress", }; To this:
var request = new RestRequest { Path = "requestToken?scope=r_basicprofile%20r_emailaddress", }; The space should be URL encoded in your request token path.
Thanks, Kamyar Mohager
-40648993 0 "grunt tests” task throws error as Fatal error: spawn EACCEScommand 'grunt tests'
throws following errors:
Running "tests" task (node:956) DeprecationWarning: process.EventEmitter is deprecated. Use require('events') instead.
Running "karma:unit" (karma) task INFO [karma]: Karma v0.12.37 server started at http://localhost:9876/ INFO [launcher]: Starting browser Firefox Fatal error: spawn EACCES
i have following setup: FIREFOX_BIN=/usr/bin -- where firefox exists
and have following grunt tools installed on Centos 6. grunt-cli v1.2.0 grunt v0.4.5
-10277663 0 How to handle exception in wicketmy code:
try { LinkedDataForm form = webService.process(searchForm, path); add(new ExternalLink("url", form.getUrl(), form.getUrl())); } catch (Exception e) { add(new Label("error", e.getMessage())); } where:
@SpringBean(name = "webService") WebService webService; and my html page looks like:
<a wicket:id="url">url</a> <p wicket:id="error"/> the problem is in html page that I have url or error and then wicket return exception: Unable to find component with id 'error' in ... how I can solve this problem
Here's a working example made from following Facebooks developer guidelines for the Like button. Place this right after the opening body tag:
<div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <div class="fb-like" data-href="https://www.facebook.com/MagnoliaRV" data-layout="standard" data-action="like"></div>
-2129546 0 best practices in naming session variables I was used to naming my session variables the "normal" way, kinda like when I want to keep track of user details, I name them:
$_SESSION['username']$_SESSION['email'] $_SESSION['id']I am worried that they may be in conflict with other session data when I am browsing sites in the same browser, or will there not be any conflict at all(once I tried to simultaneously run two of my projects with the same session variables, residing in the same server, and obviously, things got real messy).
-37072932 0Calculating out of basic logic, theoretically 1 GHz can do 1 billion calculations/second.
Time for 10 quadrillion calculations would mean, 10 quadrillion/1 billion
So calculate it through and you will find that it will take approximetly 115 days to complete
10,000,000,000,000,000 / 1,000,000,000 = 10,000,000 seconds 10,000,000 seconds = 166,667 minutes 166,667 minutes = 2778 hours 2778 hours = 115 days But this is all theoretical
-22673429 0The LayoutAnchorablePaneControl (or any TabControl for that matter) has a property TabStripPlacement which you can set to Top. See the VS2010 Theme.xaml
am working on a c program that should log data from a norma 5000, but it seams like the normas tcpconnection randomly closes after an arbitary time (0.2-6h) but i need to log longer than that.
when it Closes the Connection i can just restart program and it will continue to log. so i got the idea of just restarting my socket when the tcpconnection breaks. but my restart dosent work every time.. the function i Think you want to look at is shutdownCon, init and main.
my question is: what am i doing wrong?
winsock errors i get when the tcp Connection stops working 10053 (WSAECONNABORTED) or 10054 (WSAECONNRESET).
https://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx
#pragma comment(lib, "Ws2_32.lib") #define WIN 1 #define debug 1 #include <winsock2.h> #include <windows.h> #include <stdio.h> #include <sys/timeb.h> #include <time.h> #define HOST "192.168.0.101" #define PORT 23 #define SOCKET_HANDLE_FMT_PFX "" #define SOCKET_HANDLE_FMT "u" /* "%u" - 'typedef u_int SOCKET' */ typedef SOCKET socket_handle_t; typedef struct { socket_handle_t h; } *socket_t; /**************************************************************************** **/ static void Delay(double seconds) { Sleep((DWORD)(seconds * 1000)); } /**************************************************************************** **/ void wsa_error(char *func,int error) { fprintf(stderr,"%s() failed, error %d\n", func,error == -1 ? WSAGetLastError() : error); int c; /* must be int to hold EOF */ while((c = getchar()) != '\n' && c != EOF); } /**************************************************************************** **/ int socket_setup(void) { #if WIN WSADATA wsaData; int wsaerrno; /* * Initialize Windows Socket DLL */ if ( (wsaerrno = WSAStartup( MAKEWORD(1,1), /* at least version 1.1 */ &wsaData)) != 0 ) { wsa_error("WSAStartup",wsaerrno); return -1; } #endif /* WIN */ return 0; /* OK */ } /**************************************************************************** **/ int socket_cleanup(void) { #if WIN if ( WSACleanup() == SOCKET_ERROR ) wsa_error("WSACleanup",-1); #endif return 0; /* OK */ } /**************************************************************************** **/ socket_t socket_create(void) { socket_handle_t sh; socket_t s; sh = socket(AF_INET,SOCK_STREAM,0); #if WIN if ( sh == INVALID_SOCKET ) { wsa_error("socket",-1); return NULL; } #endif s = calloc(1,sizeof(*s)); if ( !s ) return NULL; s->h = sh; return s; /* OK */ } /**************************************************************************** **/ int socket_connect(socket_t s,struct sockaddr *addr,int addrlen) { int ret = 0; /* OK */ #if WIN if ( connect(s->h,addr,addrlen) == SOCKET_ERROR ) { wsa_error("connect",-1); return -1; } #endif return 0; /* OK */ } /**************************************************************************** **/ int socket_recv(socket_t s,void *buf,int len,int flags) { register int l; #if WIN l = recv(s->h,buf,len,flags); if ( l == SOCKET_ERROR ) { wsa_error("recv",-1); return -1; } #endif return l; } /**************************************************************************** **/ int socket_send(socket_t s,void *buf,int len,int flags) { register int slen; /* sent length */ #if WIN slen = send(s->h,buf,len,flags); if ( slen == SOCKET_ERROR ) { wsa_error("send",-1); return -1; } #endif return slen; } /**************************************************************************** **/ int socket_puts(socket_t s,char *str) { char buf[1024]; strcpy(buf,str); strcat(buf,"\n"); if ( socket_send(s,buf,strlen(buf),0) < 0 ) return -1; return 0; } /**************************************************************************** **/ int socket_gets(socket_t s,char *str) { char buf[1024]; char *p; if ( socket_recv(s,buf,sizeof(buf),0) < 0 ) return -1; if ( (p = memchr(buf,'\n',sizeof(buf))) != NULL ) { if ( p > buf && p[-1] == '\r' ) p--; *p = '\0'; } else buf[sizeof(buf)-1] = '\0'; strcpy(str,buf); return strlen(str); } /**************************************************************************** **/ /*is some thing wrong here?*/ int shutdownCon(socket_t s){ char buff[1024]; if (shutdown(s->h,2)== SOCKET_ERROR) { wsa_error("shutdownCon",-1); return -1; } while(socket_gets(s,buff)> 1); if(closesocket(s->h) == SOCKET_ERROR) { wsa_error("shutdownCon",-1); return -1; } socket_cleanup(); return 0; } /*is some thing wrong here?*/ int init(socket_t *s){ struct sockaddr_in saddr; struct sockaddr_in *addr_in = (struct sockaddr_in *)&saddr; /* socket (TCP/IP) API initialization: */ if ( socket_setup() < 0 ) return -1; /* * Connect to the instrument: */ /* set destination IP address and TCP port: */ memset(addr_in,0,sizeof(struct sockaddr_in)); addr_in->sin_family = AF_INET; addr_in->sin_port = htons(PORT); addr_in->sin_addr.s_addr = inet_addr(HOST); /* create socket: */ *s = socket_create(); if ( !*s ) return -1; #if debug fprintf(stderr,"socket_connect() ...\n"); #endif if ( socket_connect(*s,(struct sockaddr *)&saddr,sizeof(saddr)) < 0 ) return 1; #if debug fprintf(stderr,"socket_connect(): done\n"); #endif return 1; } int recon(socket_t *s){ shutdownCon(*s); init(s); return 0; } void printTime(){ struct _timeb timebuffer; char *timeline; _ftime( &timebuffer ); timeline = ctime( & ( timebuffer.time ) ); printf( "The time is %.19s.%hu %s", timeline, timebuffer.millitm, &timeline[20] ); } int main(int argc,char *argv[]) { socket_t s; char buffer[1024]; char oper[1024]; init(&s); #if debug fprintf(stderr,"trying to get id from norma \n"); if ( socket_puts(s,"*IDN?") < 0 ) return 1; if ( socket_gets(s,buffer) < 0 ) return 1; puts(buffer); #endif //##################CONF FROM FLUKE##################### /* Bring the instrument into a default state: */ //socket_puts(s,"*RST"); /* Select three wattmeter configuration: */ //socket_puts(s,"ROUT:SYST \"3W\""); /* SYNC source = voltage phase 1: */ //socket_puts(s,"SYNC:SOUR VOLT1"); /* Set voltage range on voltage channel 1 to 300 V: */ //socket_puts(s,"VOLT1:RANG 300.0"); /* Set current channel 1 to autorange: */ //socket_puts(s,"CURR1:RANG:AUTO ON"); /* Set averaging time to 1 second: */ //socket_puts(s,"APER 1.0"); /* Select U, I, P measurement: */ //socket_puts(s,"FUNC \"VOLT1\",\"CURR1\",\"POW1:ACT\""); /* Run continuous measurements: */ //socket_puts(s,"INIT:CONT ON"); //###################################################### socket_puts(s,"SYST:KLOC REM"); socket_puts(s,"*RST"); socket_puts(s,"ROUT:SYST \"3w\""); socket_puts(s,"APER 0.025"); socket_puts(s,"INP1:COUP DC"); socket_puts(s,"FUNC \"VOLT1\",\"CURR1\",\"POW1\",\"POW1:APP\",\"POW1:ACT\",\"PHASE1\""); socket_puts(s,"INIT:CONT ON"); Delay(5.0); /* Wait 2 seconds */ int opstat = -1; while(1){ //if(opstat != -1) // recon(&s); opstat = 0; while((opstat & 0x400) == 0){ if(socket_puts(s,"STAT:OPER:EVEN?")==-1){ recon(&s); continue; } memset(oper,0,sizeof(oper)); if(socket_gets(s,oper) == -1){ recon(&s); continue; } opstat = atoi(oper); } if(socket_puts(s,"DATA?") == -1){/* Query the measurement */ recon(&s); continue; } memset(buffer,0,sizeof(buffer)); /* Clear buffer */ if(socket_gets(s,buffer) == -1){/* read values */ recon(&s); continue; } puts(buffer); /* Print the value on the screen */ //Delay(1.0); /* Wait 2 seconds */ printTime(); } return 0; } /**************************************************************************** **/ best regards baot
-33109710 0There are several ways to achieve what you want as the other answers point out. If you want a bit of safety checking then I'd use TryParse:
using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { var test = "1 2 3 x"; var values = test.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries); var results = new List<int>(); foreach(var value in values) { int x; if(Int32.TryParse(value, out x)) { results.Add(x); } else { Console.WriteLine("{0} is not an integer", value); } } } }
-20934928 0 changing storyboard after UIAlert button pressed I want to change to the main menu after clicking main menu at the game over UIAlert
trying this:
-(void)gameOver { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Time's up!" message:[NSString stringWithFormat:@"You've scored: %i points!", scoreCounter] delegate:self cancelButtonTitle:nil otherButtonTitles:@"Submit to Leaderboards",@"Play Again",@"Main Menu", nil]; [alert show]; } -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { if (buttonIndex == 1) { [self toMain]; } if (buttonIndex == 2) { [self toMain]; } if (buttonIndex == 3) { [self toMain]; } } -(void)toMain { mainMenu *main = [[mainMenu alloc] initWithNibName:nil bundle:nil]; [self presentViewController:main animated:YES completion:NULL]; } does nothing at all...
EDIT
fixed the button index, now facing a black screen after [self toMain]
-35478154 0The problem was that the below variables initialization code was never getting executed:
env.shell = '/bin/ksh' env.user = config.user_app2 env.password = config.password_app2 Creating an init function that had the above lines and running that function before any others like execute() worked.
-38727168 0Try this
If Right(Field2, 3) = "A-1" Or _ Right(Field2, 3) = "A-2" Or _ Right(Field2, 3) = "B-1" Or _ Right(Field2, 3) = "B-2" Or _ Right(Field2, 3) = "C-1" Or _ Right(Field2, 3) = "C-2" Or _ Right(Field2, 3) = "D-1" Or _ Right(Field2, 3) = "D-2" Or _ Right(Field2, 3) = "D-3" Then Cells(i, 50).Value = "OtherPrtnrs /Dcrs & Dept heads" End If Or better still... this
Select Case Right(Field2, 3) Case "A-1","A-2","B-1","B-2","C-1","C-2","D-1","D-2","D-3" Cells(i, 50).Value = "OtherPrtnrs /Dcrs & Dept heads" End Select Note: I am assuming that i is a valid row number
Explanation:
When comparing using an If statement, you cannot say If A = B or C. You are supposed to compare is separately. If A = B or A = C Then. Here each OR is its own Boolean statement i.e it will be evaluated separately.
When you have multiple such comparisons, it is better to use a Select Statement as shown in the example above.
-6514515 0This may not work in your scenario, but you can invoke a method from a binding using an ObjectDataProvider. Here's a quick example:
<Window.Resources> <local:StringToDoubleConverter x:Key="stringToDouble" /> <local:MyObject x:Key="objInstance" /> <ObjectDataProvider x:Key="odp" ObjectInstance="{StaticResource objInstance}" ObjectMethod="MyMethod" > <ObjectDataProvider.MethodParameters> <sys:Double>0</sys:Double> </ObjectDataProvider.MethodParameters> </ObjectDataProvider> </Window.Resources> Now, an element in your view, say a TextBox can bind to the method parameter:
<TextBox Text={Binding Source={StaticResource odp}, Path=MethodParameters[0], UpdateSourceTrigger=PropertyChanged, Converter={StaticResource stringToDouble}} /> The method return value can then be used in a binding elsewhere:
<Label Content="{Binding Source={StaticResource odp}}" ContentStringFormat="Method returned: {0}" /> Again, this may not work in your scenario, but it does illustrate a way to pass a parameter to a method and use the return value entirely in XAML. Here's a resource for more information: http://bea.stollnitz.com/blog/?p=22
-27995808 0Yes, it is possible to do so.
CAUTION: Proceed at your own risk. Writing block placement strategy is extremely complicated and risky. It's seems a code smell that your apps need to determine how replicas are placed. Think about if you really really need to write block placement strategies. Having warned you, proceed if you want to know how to accomplish this. Typically this feature is used to control how well balanced a cluster is. E.g. one of the strategies that was built by one of the Hadoop vendors is to place blocks on the disk with the lowest percentage disk used.
Here's a bunch of resources for you to check out:
I suggest you to create json object from your vars and pass it as argument, something like:
<button id="modalBtn" type="button" onclick="ShowProduct(<?php echo json_encode(array($title, $description, $img))?>);"> View Details </button> Or (for more readable keys)
<button id="modalBtn" type="button" onclick="ShowProduct(<?php echo json_encode(array('title' => $title, 'descr' => $description, 'img' => $img))?>);"> View Details </button> And your ShowProduct function you can define like:
function ShowProduct(params) { console.log( params ); // do other stuff } Update:
if your vars are already in array you can:
// pass this array: ShowProduct(<?php echo json_encode($your_array)?>) // fill new array with required keys only ShowProduct(<?php echo json_encode(array($your_array['title'], $your_array['description'], $your_array['img']))?>)
-11540937 0 ActionScript 3 MouseEvent run once What I want to do is to run once my over listener function. The problem is that once I do a mouse over into my movie clip "button", it enters a new loop again and again. How can I make it run only once, when the tween event is completed ?
import fl.transitions.Tween; import fl.transitions.easing.*; import fl.transitions.TweenEvent; function Over (e:MouseEvent):void { trace('Over'); var myTweenUp:Tween = new Tween(button, "y", Back.easeOut, 200, 180, 2, true); } function Out (e:MouseEvent):void { trace('Out'); var myTweenDown:Tween = new Tween(button, "y", Back.easeOut, 180, 200, 2, true); } button.addEventListener(MouseEvent.MOUSE_OVER, Over); button.addEventListener(MouseEvent.MOUSE_OUT, Out);
-4604771 0 SQL Server Stored Procedure Compile-time Validation Does anyone know how to get compile time validation of parameters being passed to a stored procedure. Example If Proc1 calls Proc2 but specifies an invalid parameter name for Proc2. Currently I find out at run-time. Is there a way to find out when I'm creating Proc1?
Thanks much, Tom
-36577116 0I don't suggest using numerical indexes if you don't have to, as in this case, they can be unpredictable. Instead, use the column names from your database, like this...
$videoFile = $row['videoFile']; $views = $row['views']; Also, you say you want the ONE entry with MOST views, so I believe you want...
$q="select videoFile, views from videos ORDER BY views DESC LIMIT 1";
-7021593 0 Memory leak when using SWFLoader in Adobe AIR I'm trying to load windowed sub-application in another windowed application, The requirement is to replace one loaded application with another on user action.
I tried the documented method of unloadAndStop() on the swfLoader in the main windowed application, but somehow during memory profiling I could see the instances of those applications were maintained in the memory even after explicitly running garbage collection.
Where as If I make those windowed application as modules, and then try to load them using the Moduleloader things work smoothly and unloaded modules are removed from memory.
Any one faced the same issue before ?
-9310680 0You don't have UINavigationController into your pop-up, so it works normal. Change it to support navigation like this:
//build our custom popover view BookSelectionview* popoverContent = [[BookSelectionview alloc] init]; UINavigationController *navigationController = [[[UINavigationController alloc] initWithRootViewController:popoverContent] autorelease]; //resize the popover view shown //in the current view to the view's size popoverContent.contentSizeForViewInPopover = CGSizeMake(500, 600); //create a popover controller self.popoverController = [[UIPopoverController alloc] initWithContentViewController:navigationController];
-15913062 0 The following code snippet illustrate an example of usage and creation of an OWL expression using the OWL API (taken and adapted from there):
//OWL Expression we would like to create: //in OWL Functional syntax: ObjectIntersectionOf(A ObjectSomeValuesFrom(R B)) //in Manchester syntax: A and R some B PrefixManager pm = new DefaultPrefixManager("http://example.org/"); OWLClass A = factory.getOWLClass(":A", pm); OWLObjectProperty R = factory.getOWLObjectProperty(":R", pm); OWLClass B = factory.getOWLClass(":B", pm); //The expression OWLClassExpression expression = factory.getOWLObjectIntersectionOf(A, factory.getOWLObjectSomeValuesFrom(R, B)); //Create a class in order to use the expression OWLClass C = factory.getOWLClass(":C", pm); // Declare an equivalentClass axiom //Just there to show how an example on how to use the expression OWLAxiom definition = factory.getOWLEquivalentClassesAxiom(C, expression); manager.addAxiom(ontology, definition);
-37798972 0 VBA merge and unmerge according to if statement I am having an issue with merging data in excel using VBA.
Basically, I would like every cell row to be the same size and when a cell matches with a specific name, I want certain cells (specific 2 sets of rows preceding the name) to merge and center while others just merge across but that way some cells in the column have one number while others have a percentage and fraction as seen in this picture example above.
I'm wondering if offset could be useful here as well?
Here is some pseudo ish code to give you an idea: basically, if a cell in the A range matches a color (or whatever I put), then we want to merge and center two rows of cells and the 3 columns. Else if the cell in the A range matches a name (or whatever I put), then leave the cells separate but merge across maybe.
sub example1() if (cell in A range) = "red", "orange", "yellow", "green", "blue", then offset ( , 1) and merge¢er else if (cell in A range) = "sarah", "mark", "bob", "steve", "Brittany", then offset (, 1) and leavealone or merge just across end if end sub
-87310 0 The lovely built in regular expression evaluator.
-4604794 0 Creating a simple li slider (infinate or with 'rewind'/stop)So far I've got scrolling list items on click using the code below:
$('li#news-back').click(function(){ $('li.news-item').animate({ left : '-=960px' }); //$('li.news-item:first').insertAfter('li.news-item:last'); }); $('li#news-forward').click(function(){ $('li.news-item').animate({ left : '+=960px' }); //$('li.news-item:last').inserBefore('li.news-item:first'); }); Each list item is 960px wide , items are floated left and only one item is shown in the container at any given time. Clicking back for forward will animate the li by their width making the next or previous visible..
The problem is that for now there are 4 items. So I either need to add the first item to the end or the list or the last to the beginning of the list when clicked as the code I've commented out.
Watching this in firebug it seems to be rearranging the content as I hoped but it's not working so within the browser (getting some very odd results - jumping to the 3rd when the second should be visible etc).
The other solution perhaps would be to use an if statement to say (was we're manipulating the left property) - when back is click if left = 0 do nothing or alert there are no more in the list - then if forward is click to say if left = 2880 do nothing as you'll be at the end of the list..
Any pointers greatly appreciated.
-5248321 0 Have TouchJSON return mutable objects?I am receiving some json from a web service. I parse this using the TouchJSON library. I keep the data around for the user to change certain values and then I want to return it to the web service.
The JSON object I get contains NSDictionary Objects within the object, like this:
[ { "id": null, "created_at": 12332343, "object": { "name": "Some name", "age" : 30 }, "scope": "it stuff", "kind_id": 1, "valid": true, "refering_statement": { "id": 95 }, "user": { "id": 1 } } ] If I want to change values in this dictionary, I can't because the returned objects from TouchJSON are not mutable.
Is there a way to have have TouchJSON return mutable objects?
or is there a way to have Objective C make an NSDictionary and all its children mutable?
or do I have to just go through every NSDictionary in NSDictionary and copy all data into a mutable copy and then reinsert everything?
Hope someone can help me out on this one:) thanks in advance.
-7798341 0The decision of whether to override the method or use the event handler often times comes down to how much control you need to have over what happens during the execution of that method. Overriding the method gives you full control of the method, whereas the event handler only runs after the method has executed.
If you need a high level of control over what happens during that method, I would advise overriding the method. If you simply need to run some code after execution of the method, I would use the event handler.
protected override void OnDeactivated(EventArgs e) { //run some code before execution (anything that could effect execution) //call the base method and fire the event base.OnDeactivated(e); //run some code after execution }
-39192896 0 Finally to solve I REDIRECTED with flash msg..
$em = $this->getDoctrine()->getManager(); $user = $this->get('security.token_storage')->getToken()->getUser(); $entity = $em->getRepository('ApplicationSonataUserBundle:User')->find($user->getId()); if (!$entity) { throw $this->createNotFoundException('Unable to find User entity.'); } $form = $this->createForm(ProfileType::class, $entity); if ($request->getMethod() === 'POST') { $form->handleRequest($request); if ($form->isValid()) { $em->flush(); return $this->redirectToRoute('fz_user'); } $em->refresh($user); $this->flashMSG(1, '' . $form->getErrors(true, false)); return $this->redirectToRoute('fz_user_profile_edit'); }
-1324197 0 Along with boosting during search, you can also boost fields differently during indexing. This means that a general search for a term that could show up in either field would still give a better score for those that match your preferred field without overtly stating where you're looking for the term.
-8947114 0That's pretty vague, but this is the concept if the child is nested:
$('.menu').find('.class')
It seems like your question boils down to "how can I dynamically add a method to an object", the the short answer is don't do it (1). Objects can have attributes which can be functions, and that's fine, but these functions do not become methods and don't behave like methods. For example if foo.attr is sum then foo.attr(x) is the same as sum(x) not sum(foo, x).
Your question has a certain functional "aroma" to it, if you wanted to drop the class/object stuff and go the fully functional route you could do something like this:
def identity(x): return x def f(n): return [i for i in range(1, 10) if (n % i == 0)] def s(factors): return (len(factors) == 2) def foo(func, helper=identity): def innerfunc(n): return func(helper(n)) return innerfunc a = foo(f) print a(6) # [1, 2, 3, 6] b = foo(s, a) print b(5) # True If that doesn't appeal to you, I would suggest thinking of the func and parent attributes on your Foo class as data attached to your objects, not as methods, and work out the problem from there. The logic associated with your class should live inside proper methods. These methods can refer to the data as needed. Here's my very simple example:
class Foo(object): def __init__(self, func, parent=None): self.func = func self.parent = parent def run(self, n): if self.parent is None: return self.func(n) else: return self.func(self.parent.run(n)) a = Foo(f) print a.run(6) # [1, 2, 3, 6] b = Foo(s, a) print b.run(5) # True (1) Methods belong to a class not an object, so the question should really be how can I attach something to my object that behaves like a method.
-12566831 0 Display all records with an id smaller than 100 fails due to 'comparison of Symbol with 100 failed'I have a user model and I need to display all users that have an id of smaller than 100. My code is
User.where(:id < 100) The error message is "comparison of Symbol with 100 failed". How can I just get all users with ids smaller than 100? How will it be if I need ids between 100 and 200?
-33919058 0 Prevent iOS URL scheme hijackI have an app that gets opened from another app via a URL scheme. The URL contains signup tokens. As any app can register the same URL scheme as my app, I am concerned a "fake" app can do a man-in-the-middle attack and capture the signup tokens.
My idea is to check that the URL scheme does not open another app when my app is first opened.
From a security perspective, if the URL scheme opens my app the first time, will it always open my app in the future?
-338630 0We run Apache listening on port 443 (https) for Trac and Svn (WebDAV), and IIS listening on port 80 (http) for public web pages. Setting up Apache for Trac and Svn was very easy and well documented.
-36742550 0I found the error >> all what i forgot to do is to return data from http get in factory services.js >>
.factory('stations',['$http',function($http){ var stations = []; return $http.get(base_url+'api/stations/uid/'+uu_id).success(function(response){ stations = response; return stations; }); }])
-21560232 0 OnCreate() of first tab gets called even when second tab is defined as CurrentTab I have an activity on which I have a TabHost and a TabWidget like this:
<TabHost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/tabhost" android:layout_gravity="bottom" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="5dp"> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="0dip" android:padding="5dp" android:layout_weight="1" /> <TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout> </TabHost> I use the following code to add three tabs and their respective activities to the TabHost:
private void CreateTabs() { TabHost.TabSpec spec; // Resusable TabSpec for each tab Intent intent; // Reusable Intent for each tab String strJson = Intent.GetStringExtra (Constants.JSON_RESPONSE); // Create an Intent to launch an Activity for the tab (to be reused) intent = new Intent (this, typeof (FirstActivity)); if (strJson != null) { intent.PutExtra (Constants.JSON_RESPONSE, strJson); } intent.AddFlags (ActivityFlags.NewTask); // Initialize a TabSpec for each tab and add it to the TabHost spec = TabHost.NewTabSpec ("first"); spec.SetIndicator ("First", Resources.GetDrawable (Resource.Drawable.FirstIcon)); spec.SetContent (intent); TabHost.AddTab (spec); // Do the same for second tab intent = new Intent (this, typeof (SecondActivity)); if (strJson != null) { intent.PutExtra (Constants.JSON_RESPONSE, strJson); } intent.AddFlags (ActivityFlags.NewTask); spec = TabHost.NewTabSpec ("second"); spec.SetIndicator ("Second", Resources.GetDrawable (Resource.Drawable.SecondIcon)); spec.SetContent (intent); TabHost.AddTab (spec); // Do the same for third tab intent = new Intent (this, typeof (ThirdActivity)); if (strJson != null) { intent.PutExtra (Constants.JSON_RESPONSE, strJson); } intent.AddFlags (ActivityFlags.NewTask); spec = TabHost.NewTabSpec ("third"); spec.SetIndicator ("Third", Resources.GetDrawable (Resource.Drawable.third_icon)); spec.SetContent (intent); TabHost.AddTab (spec); //Set the tab you want to show TabHost.CurrentTab = 1; } As you can see that at the last line I am making the second tab to be shown when I open this tabbed activity and that is what it does but actually it first calls the OnCreate of FirstActivity and then calls OnCreate of SecondActivity before showing the SecondActivity. (The OnCreate of ThirdActivity is only called when I tap on the third tab to actually see that activity, which is absolutely fine).
I want that the OnCreate of FirstActivity to be only called when I tap on the first tab because:
FirstActivity gets the user's current location and if I get it before the user actually navigates to the required screen then it may not be correct if the user has already changed his location.Please let me know how to achieve that?
-3221921 0 Change all with command lineI'm wondering if there is a way to change a specific word in all of the files within the /www/ directory using command line. Just looking for a faster way to change out a specific word so I don't need to open all the files manually! Thanks!
-6144517 0 php command line print in object not returningI am trying to run some php from the command line but the php in my class is not being hit.
<?php print "1"; try { print ",2"; $a = new myClass(""); } catch (Exception $e) { print $e->getMessage(); } print ",3"; myClass
<?php class myClass{ function __construct($var) { print "My Class"; } } The output I am getting is:
1,2 Process finished with exit code 255 Why is the print in the constructor not outputting to the command line?
-23287646 0If you have that textfile, you might just put a rename at the beginning of each line and save it as .bat.
(E. g. with Notepad++, Search Mode = Extended, replace \n with \nrename, maybe check first and last lines)
Is it possible for a Makefile to determine what binary format the compiler is targeting (i.e. PE, ELF, Mach-O, etc.)? Maybe by running the compiler or assembler with certain options?
Or can I accurately determine this from the OS (by running uname -s or something of the sort)?
From the Python FAQ:
Lists and tuples, while similar in many respects, are generally used in fundamentally different ways. Tuples can be thought of as being similar to Pascal records or C structs; they're small collections of related data which may be of different types which are operated on as a group. For example, a Cartesian coordinate is appropriately represented as a tuple of two or three numbers.
Lists, on the other hand, are more like arrays in other languages. They tend to hold a varying number of objects all of which have the same type and which are operated on one-by-one.
Generally by convention you wouldn't choose a list or a tuple just based on its (im)mutability. You would choose a tuple for small collections of completely different pieces of data in which a full-blown class would be too heavyweight, and a list for collections of any reasonable size where you have a homogeneous set of data.
-912429 0I agree with most of the others here. I think you should really try to uncomplicate things by using another already build free option like itunes, Winamp or WMP. If you really want to learn something new, do this just for fun after when you won't be under so much pressure to make it work.
If, however you REALLY want to go through with this I think http://code.google.com/p/ffmpeg-sharp/ should do what you want.
-14925551 0 What does class << self mean?Regarding:
class Test class << self def hi puts "Hi there" end end I came up with following image in my head:
Since everything is an object in Ruby, classes themselves are objects of class Class. By calling class << self you open up Class definition from the inside of Test and inject few instance methods. Since Test is an instance of Class, you can call those methods same way you call instance methods on your objects: Test.hi.
Following is the pseudo code which helps to visualise my previous sentence:
class Class def hi puts “Hi there” end end Test = Class.new(class Test end) Test.hi Am I getting this right?
-15929012 0 Is it possible to use a parent table Id instead of child table Id, when child table should put it's Id into another tableI have this Generalization relation ship between some classes in my class diagram. FirstClass as a base class that has Name attribute, SecondClass as a derived class that the FirstClass is it's base class and has some other attributes and finally ThirdClass that is a derived class from SecondClass and it has some other attributes too. ThirdClass as an association relation ship with Widget class, 1.*.

I used Joined strategy when I wanted to implement a Data Model from the class diagram. so the FirstTable has their Pk in the SecondTable and the SecondTable has its PK in the ThirdTable. As you see Third table should has it's PK in Widget class. And there are some costs whenever I want to Join widget table with third table because I need to fetch Name from First Table.
Is it appropriate that I read Id from FirtTable (Actually it's base class) and put it into Widget table?
Use the .figure() function to create a new window, the following code makes two windows:
import matplotlib.pyplot as plt plt.plot(range(10)) # Creates the plot. No need to save the current figure. plt.draw() # Draws, but does not block plt.figure() # New window, if needed. No need to save it, as pyplot uses the concept of current figure plt.plot(range(10, 20)) plt.draw() You can repeat this as many times as you want
-11755163 0Check the Permissions section at https://developer.spotify.com/technologies/apps/guidelines/
You will need to add the URLs google web fonts are loaded from to the RequiredPermissions element.
-38892754 0 How to call SOAP API from the browserI have a localhost SOAP API that I can call using Chrome's extension Boomerang - SOAP & REST Client it works and I get results with this request:
<x:Envelope xmlns:x="http://schemas.xmlsoap.org/soap/envelope/" xmlns:eko="http://localhost:8080/api/myapi.wsdl"> <x:Header/> <x:Body> <eko:getReview> <eko:auth>123abfdbgfdg</eko:auth> <eko:changed_since>2016-06-07</eko:changed_since> <eko:rating_id>?</eko:rating_id> <eko:product_id>?</eko:product_id> </eko:getReview> </x:Body> </x:Envelope> Now I need to call this API method; getReview, using the browser. So I tried to pass those parameters like this:
http://localhost/api/api.php/getReview/123abfdbgfdg/2016-06-07 But seems not working: I just get back the WSDL service help, but not the actual call results.
Is it even possible to call SOAP from browser?
-4744507 0 XML, DTD: how to make the order not importantI started off using an XML file and a parser as a convenient way to store my data
I want to use DTD to check the structure of the xml files when they arrive.
Here is my DTD file
< ?xml version="1.0" encoding="UTF-8"?> < !ELEMENT document (level*)> < !ELEMENT level (file,filelName?,fileNumber?)> < !ELEMENT file (#PCDATA)> < !ELEMENT filelName (#PCDATA)> < !ELEMENT fileNumber (#PCDATA)> (note that fileName and fileNumber are actually purely optional)
and
<document> <level> <file>group1file01</file> </level> <level> <file>group1file02</file> <fileName>file 2</fileName> <fileNumber>0</fileNumber> </level> ... as such all this works fine. (I use eclipse "validate" option to test it for now)
however while testing I got what I think is a wierd error
if I do
<level> <levelName>Level 2</levelName> <levelNumber>0</levelNumber> <file>group1level02</file> </level> changing the order of the lines, Eclipse refuses to validate it ...
I was wondering if this was a problem with Eclipse or if the order is actually important.
If the order is important how can I change the DTD to make it work no matter the ordering of he elements?
I can't really change the XML because I already have all the XML files and the parser written (I know I did it the wrong way round lol).
-17190654 0 How to create text file in given directory in iphone and androidcan you please tell me hoe to create text file in given given directory .I need write on that text file .and read the text from that text file. I am able to create folder using this code .But i need to add text file inside the folder(newDir).
<!DOCTYPE html> <html> <head> <title>Local File System Example</title> <script type="text/javascript" charset="utf-8" src="cordova-x.x.x.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for Cordova to load document.addEventListener("deviceready", onDeviceReady, false); // Cordova is ready function onDeviceReady() { window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, onFileSystemFail); } function onFileSystemSuccess(fileSystem) { console.log(fileSystem.name); var directoryEntry = fileSystem.root; directoryEntry.getDirectory("newDir", {create: true, exclusive: false}, onDirectorySuccess, onDirectoryFail) } function onDirectorySuccess(parent) { console.log(parent); } function onDirectoryFail(error) { alert("Unable to create new directory: " + error.code); } function onFileSystemFail(evt) { console.log(evt.target.error.code); } </script> </head> <body> <h1>Example</h1> <p>Local File System</p> </body> </html>
-7957062 0 using SQL to directly delete CoreData data from my DB There are times when i will need to delete say 10,000 rows from my CoreData data store and looping through those records individually each time takes way too long.
Is there a way to use SQL to directly delete from my data store quickly?
-30401906 0 PyQt4: Where can you make menus?I'm using Python 3 and PyQt4
I'm trying to make a simple main window with a menubar. It doesn't work if I try to set up the menubar in the MainWindow initialization but does work if I set it up in some external function. That is, the following does NOT work:
import sys from PyQt4 import QtGui class MyMainWindow(QtGui.QMainWindow): def __init__(self, parent=None): super().__init__(parent) centralWidget = QtGui.QWidget() menubar = QtGui.QMenuBar() menu = QtGui.QMenu("File") menu.addAction("New") menubar.addMenu(menu) self.setMenuBar(menubar) self.setCentralWidget(centralWidget) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) mainWindow = MyMainWindow() mainWindow.show() sys.exit(app.exec_()) While if I simply move the menu setup down to the main routine:
class MyMainWindow(QtGui.QMainWindow): def __init__(self, parent=None): super().__init__(parent) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) mainWindow = MyMainWindow() centralWidget = QtGui.QWidget() menubar = QtGui.QMenuBar() menu = QtGui.QMenu("File") menu.addAction("New") menubar.addMenu(menu) mainWindow.setMenuBar(menubar) mainWindow.setCentralWidget(centralWidget) mainWindow.show() sys.exit(app.exec_()) Then the menu is created (I know I don't have any actions hooked up, this is stripped down to show the oddity). I thought it might have to do with being in init but moving it to another class routine, e.g. setup(self), and then calling that after creating the mainWindow doesn't solve the problem.
I seem to be continually baffled by what works and what doesn't in PyQt4. If anyone could point me at some good resources I'd also appreciate it (I've read Rapid GUI Programming but find I'm still lost).
Thanks in advance for your help
-25358040 0 AngularJS with ui-router: Changing value of a parent dependency of from child's controllerEnvironment: AngularJS application (using UI Router) that has nested states.
Short version: How do I change the value of a parent-state's dependency from inside a child's controller, such that siblings of the child state, who are also using the dependency will get the new value.
Long version: Take the following configuration:
shopApp.config(function($stateProvider) { $stateProvider.state('shop', { url : '/shop', templateUrl : 'shop.html', resolve : { user : function($q) { // callback that ends up returning null // because the user is not logged in } }, controller: function($scope, user) { // user is null at this point $scope.user = user; } }).state('shop.login', { url : '/login', templateUrl : 'login.html', controller : function($scope) { // onLoggedIn is called from some form-processing // logic once the user has successfully logged in $scope.onLoggedIn = function(userObject) { // I want the shop.userDetails state's controller // to get the new $scope.user value $scope.user = userObject; $state.go('^.userDetails'); }; } }).state('shop.userDetails', { url : '/userDetails', templateUrl : 'userDetails.html', controller : function($scope, user) { // Unfortunately user is null here $scope.user = user; } }); }); The shop.login state's controller has a function called onLoggedIn that's called once the user has logged in successfully. An object containing user-information is passed to this function. From this point on I want all resolutions of the user dependency to use this value (i.e userObj). Unfortunately, instead of using the value that I've just assigned to $scope.user, it seems that the value that gets passed to the controller of shop.userDetails is the one that was originally resolved when the shop state's controller was created.
Does anyone know how to do this? If I'm doing this all wrong please tell me.
-35362525 0 Pipe git diff to git checkoutIf I delete a file, I can revert it in git with:
git checkout filename If I want to revert all deleted files, I can list them with:
git diff --diff-filter=D --name-only What I then want to do is restore them, but
git diff --diff-filter=D --name-only | git checkout Doesn't work, it only repeats the list to stdout, and git checkout seems to receive no input. Ditto for | git checkout HEAD -- and so on.
I've tried this in Windows Command Prompt, in Powershell, and in Git Bash, with the same result each time.
How do I correctly pipe input to git checkout?
-1827221 0Wireshark won't help you if you have to debug HTTPS requests (unless you can get the encryption keys for both endpoints - see the Wireshark site for details). Firebug and Tamper Data are getting close, but for thorough analysis, I sometimes like to save a recorded session. I'd recommend giving the OWASP Zed Attack Proxy (the successor of Parosproxy, which is no longer actively developed) a try. It is a Java application serving as a http(s) proxy; it provides quite a lot of features and proved to be very helpful to me in the past.
ZAP offers an easy autoconfiguration of Firefox. Bear in mind to do that on a separate (meaning: not for other browsing activities) Firefox profile: In order to intercept https, ZAP will install a new SSL certificate.
-5630312 0 Simple MySQL/AJAX Search Box questionI am making a simple search box on my web site. I followed a tutorial here
I just need to query id numbers from a certain table in the database and display the EXACT results right beneath the searchbox
you can see it here:
http://4evergreengroup.com/temp/
click on "instant verification" and I want the search box that pops up to display its results right beneath and still remain in the fancybox
-28342923 0 How to access nodejs config parameter in angular side?i have nodejs config file(backend) in which some configuration data is defined:
module.exports = { product: { name: 'Event' }, server: { host: '0.0.0.0', port: 8000 }, database: { host: '127.0.0.1', port: 27017, db: 'EventExchange', username: '', password: '' }, key:{ privateKey: 'dufediioeduedhn', tokenExpiry: 1*30*1000*60 //1 hour }, admin:{ "username" : "admssin", "password" : "adminss123", "scope" : "adamssin" } }; i have to access port and host parameter in angular(client side). how is it posssible ? Thanks!
I am working with android SIP for VoIP. The application is receiving calls successfully. However, initiation a call is having some bugs.
there is no error in the logs but info which says
" I/art: Thread[1,tid=23775,WaitingForJniOnLoad,Thread*=0xb4f07800,peer=0x759512e0,"main"] recursive attempt to load library "/system/lib/librtp_jni.so" "
Can anyone explain what is the problem and how could we possible solve it?
-29470389 0 How can I pass variable when render view to script tag in Node.jsI'm using hbs as a template engine along with html. This is my setting.
app.set('view engine', 'html'); app.engine('html', hbs.__express); In my route.js
router.get('/home', isAuthenticated, function(req, res){ res.render('home', { user: data something }); }); In my home.html I want to use user variable not as a template but to do something
<script> var user = {{user}}; // It don't recognize user variable /* do something about user variable */ </script>
-35741298 0 Yes, you may use inner_product (dot product) to take the result in very simple way.
Make vectors
V2 = P - P2 V3 = P - P3 V = P3 - P2 Find signs of dot products D2 = Dot(V2,V) and D3 = Dot(V3,V)
Projection of Point P lies at S(P2, P3), if
D2 >=0 and D3 <=0 Note - there is no need in normalizations, square roots etc. Just some subtractions, multiplications and additions.
(Explanation - angles P-P2-P3 and P-P3-P2 should be acute or right)
In your edit you specify that your helper class is in a seperate assembly. If you want to avoid references and you have control over your app.config files you could put an
<add key="typeOfSystem" value="Forms|Web"/> in your projects and access it with
ConfigurationManager.AppSettings["typeOfSystem"] using ConfigurationManager along with its property AppSettings. Don't forget to add a reference to System.Configuration in your project. Note that you get the AppSettings of the hosting application. By doing this you need to add a key in your parent application's app.config, or output some error or warning if it's not specified perhaps.
I've tried to attach my own class to a numeric, to alter the output format. This works fine, but after I do a group by the class reverts back to numeric.
Example: Define a new format function for my class:
format.myclass <- function(x, ...){ paste("!!", x, "!!", sep = "") } Then make a small data.table and change one of the columns to myclass:
> DT <- data.table(L = rep(letters[1:3],3), N = 1:9) > setattr(DT$N, "class", "myclass") > DT L N 1: a !!1!! 2: b !!2!! 3: c !!3!! 4: a !!4!! 5: b !!5!! 6: c !!6!! 7: a !!7!! 8: b !!8!! 9: c !!9!! Now perform a group by and the N column reverts to integer:
> DT[, .SD, by = L] L N 1: a 1 2: a 4 3: a 7 4: b 2 5: b 5 6: b 8 7: c 3 8: c 6 9: c 9 > DT[, sapply(.SD, class), by = L] L V1 1: a integer 2: b integer 3: c integer Any idea why?
-34450319 0something like this?
$(document).ready(function() { $('ul').each(function(){ var $thisUl = $(this); $thisUl.find('input').change(function(){ var total = 0; $thisUl.find('input:checked').each(function() { total += parseInt($(this).val()); }); $thisUl.find('li:last span').html(total + ' €') }); }); $('input').change(function(){ var overAllPrice = 0; $('input:checked').each(function(){ overAllPrice += parseInt($(this).val()); }) $('.overallprice').html(overAllPrice); }) });
-29915283 0 Twilio developer evangelist here.
I'm afraid the Calls endpoint only takes one "From" number as a filter, you can't pass a list of numbers to it. You might want to return all calls and then filter manually yourself or alternatively loop through the numbers you want to return calls from and make list calls for each of them.
-12949716 0For Microsoft SQL, I'd recommend the books by Kalen Delaney (et al) called "Inside SQL Server". They offer a good insight into the internals of SQL Server, thus allowing readers to educate themselves on why particular statements might be faster than others.
Inside SQL Server 7.0
Inside SQL Server 2000
Inside Microsoft SQL Server 2005
Microsoft SQL Server 2008 Internals
There's also a book dedicated to performance tuning of SQL Server 2008 queries: SQL Server Performance Tuning Distilled
I also like the blogs by Paul Randal and Kimberly Tripp on SQLSkills.com. They are full of solid SQL advice:
-11364484 0I see the join is taking a while can you confirm you have the foreign key in place. Also if you show me the SQL I might be able to help.
-22724556 0Sure it's possible. You'd need to explode the captured pages on the slash / and go from there though.
Route::any('{any}', function($pages) { $pages = explode('/', $pages); // Do whatever... })->where('any', '.*'); A few things to be aware of:
Route::any in the above to capture any request (POST, GET, etc), you might want to limit this to a subset of those or only GET, that's up to you.URL::route helper but you can still make use of the URL::to helper. This shouldn't be a problem as it's more than likely you're storing these dynamic pages in a database and as such the URI should be stored within the database as well.What I would like is for the Parent component to intercept the props.parentClassName set in GrandParent and change it, or create it if it doesn't exist.
A component cannot intercept props from its parent because it has no access to its parent, only to its children!
I'm still don't clearly understand what you want to achieve... Does the following code do what you want?
import _ from 'underscore'; import React from 'react'; class Grandparent extends React.Component { render() { return ( <div {... this.props}> <Parent> <span>hello</span> <span>welcome</span> <span className="red">red</span> </Parent> </div> ); } } // Parent component will add ``className="border"`` to each its // child without ``className`` property. class Parent extends React.Component { render() { return ( <div {... this.props}> {_.map(this.props.children, (v, k) => React.cloneElement(v, {className: v.props.className || 'border', key: k}))} </div> ); } }
-23072707 0 Are Aggregate Roots just Entities with invariants over their contents? A Network is composed of Nodes that are connected with Fibers. The Network is responsible for making sure that:
Node; Node;Both the Network, the Node and the Fiber are information-rich (they have a name, a date when they were deployed, etc), and it looks to me as if Network is an Aggregate Root (as its the container of both Nodes and Fibers and forces invariants between them).
I'm at this point also sure that Node and Fiber are entities, and that they are also probably Aggregate Roots.
One possible implementation of the Network class might be as follows:
class Network { private final NetworkId id; private String name; private Location location; ... private final Map<FiberId, Fiber> fibers = new HashMap<FiberId, Fiber>(); private final Map<NodeId, Fiber> nodes = new HashMap<NodeId, Node>(); } which poses a big problem if my use case is just to edit the location or the name of the Network. In that case I just don't care about fibers and nodes and realistically, it is expected them to be quite possible for their numbers to be on the order of 10k-100k nodes/fibers! How should I approach this issue? Should I separate the definition of a Network (containing fibers and nodes and their invariants) from the rest of the fields?
I've always thought of Aggregate Roots as Entities that have a set of invariants to hold over its attributes, in contrast with Entities that just don't care abouts the state of their attributes (for instance, a Person defined with a name and age wouldn't probably need to have any kind of checking for invalid combinations of name and age).
Following this philosophy, I generally tend to decide whether some domain concept is either a Value, Entity, Value or Event and then if it's an Entity, if it's an Aggregate Root. Is my assumption flawed?
Thanks
-24943335 0 PureScript does not compose `trace` and `show`So the following works
main = do trace $ show $ 5 but this does not
main = do (trace . show) 5 in psci the type of trace is
forall r. Prim.String -> Control.Monad.Eff.Eff (trace :: Debug.Trace.Trace | r) Prelude.Unit and the type of show is
forall a. (Prelude.Show a) => a -> Prim.String since the return value of show is Prim.String and the first input into trace is Prim.String they should be composable. This is further evidenced by that trace $ show passes the type checking. But instead I get this error:
Error at line 1, column 10: Error in declaration it Cannot unify Prim.Object with Prim.Function Prim.String. What am I missing here? Right now my mental model is that trace is very like putStrLn in Haskell, and that one can definitely be composed with show. (putStrLn . show) 5 works.
Expected type of composed result of trace and show:
forall a r. (Prelude.Show a) => a -> Control.Monad.Eff.Eff (trace :: Debug.Trace.Trace | r) Prelude.Unit
-4447932 1 AttributeError: 'str' object has no attribute 'attack' "'Help!" I have q quick question regarding an Attribute Error regarding a basic Arena battler I am writing for my Intro to Programming Class. Here is the chunk of code that I am having trouble with upon running the program,
class Enemy: def __init__(self,player,weapons,armor): self.name = "Bad Guy" self.health = 100 self.attackPower = (player.attack + randint(-5,5)) self.defensePower = (player.defense + randint(-5,5)) self.weapon = player.weapon self.armor = player.armor def name_generator(self): import random element = ["Thunder","Lightning","Wind","Fire", "Stone"] tool = ["Hammer","Drill","Cutter","Knife", "Saw"] randomNumber1 = random.randrange(0,len(element)) randomNumber2 = random.randrange(0,len(tool)) self.randomname = element[randomNumber1] + " " + tool[randomNumber2] return self.randomname Lol, ignore the Name Generator for now, thats an idea Ill try to work out later. The Current problem I am having now is that when I run the program through IDLE i get the following error;
File "C:\Users\Caleb Walter\Downloads\Arena_Battler.py", line 150, in __init__ self.attackPower = int(player.attack + randint(-5,5)) AttributeError: 'str' object has no attribute 'attack' Any Help would be appreciated on the program error, as I have done research and tried to find the answer but all of the other casses of 'str' error involved lists. Thank You in Advance!
-36797358 0This is some code I knocked up in LinqPad, which does what you want:
void Main() { c(); } void a() { using(var id = new IndentedDebug()) { id.Trace("I'm in A"); } } void b() { using(var id = new IndentedDebug()) { id.Trace("I'm in B"); a(); } } void e() { a(); } void d() { e(); } void c() { using(var id = new IndentedDebug()) { id.Trace("I'm in C"); a(); b(); { using(var id2 = new IndentedDebug()) { id2.Trace("I'm still in C"); d(); } } } } class IndentedDebug : IDisposable { const int indentSize = 2; const char indentChar = ' '; static int indentLevel = 0; private string _indentSpaces; public IndentedDebug() { _indentSpaces = new string(indentChar, indentSize * indentLevel); ++indentLevel; } public void Trace(string message) { Console.WriteLine("{0}{1}", _indentSpaces, message); } public void Dispose() { --indentLevel; } } So your code doesn't quite look the same, but on the other hand, it's not doing any "magic" either - the code itself shows you when the indented debug ends.
-27117083 0 asp.net c# create a new page and refresh routing mapI am using the routemagic library and it works great. Except when I create a new page it doesn't refresh the route map.
this is my save action:
protected void lbSave_Click(object sender, EventArgs e) { //save data to database; //recompile the route.cs var assembly = BuildManager.GetCompiledAssembly("~/Config/Routes.cs"); var registrar = assembly.CreateInstance("Routes") as IRouteRegistrar; } in the Config/Route.cs class I have a foreach loop that ties the slug to the ID:
routes.MapPageRoute(events.Slug, events.Slug, "~/index.aspx?id=" + events.ID, true, new System.Web.Routing.RouteValueDictionary { { "id", events.ID } }); but i still keep getting a 404 page for all new pages unless i refresh IIS..What I would need to do is add a new MapPageRoute everytime I create a new "event" to avoid the 404.
-16553371 0You're looking for .distinct()
I haven't tried it myself, but possibly an AnimationDrawable could work.
-23278172 0In Python 2, writing
class MyClass(object): would suffice. Or you switch to Python 3, where
class MyClass: would be just fine.
The inheritance list usually gives a list of base classes (see Customizing class creation for more advanced uses), so each item in the list should evaluate to a class object which allows subclassing. Classes without an inheritance list inherit, by default, from the base class object; hence
class Foo: pass is equivalent to
class Foo(object): pass See also: https://docs.python.org/3/reference/compound_stmts.html#class
Also, as @Kevin pointed out in a comment, method resolution is not trivial and might lead to unexpected behavior when using multiple inheritance: http://python-history.blogspot.com/2010/06/method-resolution-order.html
-40645269 0Add the style import above your existing style, then apply the css rule to whichever element you wish. In this case I applied it to the body. I would also recommend using here strings instead of += as they are far more readable.
$a = @" <style> @import url('https://fonts.googleapis.com/css?family=Ubuntu') </style> <style> BODY{background-color:peachpuff; font-family: 'Ubuntu', sans-serif;} TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;} TH{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:thistle} TD{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:PaleGoldenrod} strong{color: green;} </style> "@ $b = @" <H2>Service Information</H2> <p> This is the list of services that are on this system. It dispays <strong>both</strong> running and stopped services </p> "@ Get-Service | Select-Object Status, Name, DisplayName | ConvertTo-HTML -Head $a -Body $b | Out-File C:\Scripts\Test.htm Invoke-Item C:\Scripts\Test.htm
-32674704 1 list's index() method for nested structures OR how to match against particular value of composed element stored in list and get it's index It is possible to get index of particular element in list using index() method, following way (borrowed from here):
>>> ["foo", "bar", "baz"].index('bar') 1 Is it possible to apply the same principle to nested structures (if not what is the closest most pythonic way)? The result should looks like this:
In [20]: list Out[20]: [(0, 1, 2), (3, 4, 5)] In [21]: list.someMagicFunctionHere(,4,) Out[20]: 1
-7397790 0 This does not make much sense to begin with. A Derived should be able to be used anywhere a Base is expected, so you should be able to do
Base *foo = new Base(); Apple x = foo->func(); // this is fine Base *bar = new Derived(); Apple y = foo->func(); // oops... I think you need to look into a different design. It's not clear just what your goal is here, but I'm guessing you might either want Base to be a class template with Fruit as a template parameter, or maybe you need to get rid of the inheritance altogether.
You could also check the most commonly used commercial profiler/coverage tool, AQTime from http://www.automatedqa.com
Here's a video on features: http://www.automatedqa.com/products/aqtime/screencasts/coverage-profiling/
-16697004 0 jQuery - toggle() a form when a button is clicked in a listProblem: I don't want it to toggle when I am clicking on the table. Only when I click the button(div). Also, there has to be a selector so that other li's tables doesnt toggle.
jQuery
$(document).ready(function() { $('table.edititem').hide(); $('.menu-category > li ul li .button').click(function(){ $('table.edititem', this).toggle(); }); }); I know the problem is: $('table.edititem', >>>this<<<).toggle(); Because the table is not inside the ".button". We need to grab the parent, but how do we do it?
HTML
<ul> <li> Category1 <ul> <li> <div> <div class="button"></div> <table class="edititem"> </table> </div> </li> </ul> </li> </ul> I hope you understand what I mean.
-3753443 0AIR addition to the actionscript 3 language that provide ways to control features from windows, mac, and linux. eg the titlebar and saving files.
Flex is an addition to the actionscript 3 language that provides way to new interrogation features from server technologies like java, php, asp and connection between multiple flash applications and databases.
Flash (CS4) can include AIR code but doesn't include Flex code. the server technology in Flash is limited but exists. Flash includes the GUI that stream lines developing. Like vector based graphics, filters, and components. Also more documentation and examples because it's easier to rewrite classes from Flex into Flash then rewriting Flash code for classes.
Where in Flash you have a button, radio button, dropdown, or menu for every property of a movieclip, image, button. Where in Flex you can write all these properties/options by simply copying pasting, and tweaking the raw code.
-32547416 0Assuming cell A1 is the range in question, select it and for Data Validation enter this formula under Custom:
=AND(LEN(A1)=7,ISTEXT(A1),ISNUMBER(MID(A1,2,6)+0))
-39204525 0 Add this into model/User.php Hope it will work
public $hasMany = array( 'Phonenumber' => array( 'className' => 'Phonenumber', 'foreignKey' => 'user_id', 'conditions' => array('Phonenumber.user_id' => 'User.id'), 'dependent' => true )
-40729708 0 Track Dependency Property Value Changes WPF I am looking for a Way to be notified on property changed of a dependency property. Similar question was answered here
What is meant by:
"If it's a DependencyProperty of a separate class, the easiest way is to bind a value to it, and listen to changes on that value."
can someone explain with an example.
thanks!
-16054711 0 How this linq execute?Data = _db.ALLOCATION_D.OrderBy(a => a.ALLO_ID) .Skip(10) .Take(10) .ToList(); Let say I have 100000 rows in ALLOCATION_D table. I want to select first 10 row. Now I want to know how the above statement executes. I don't know but I think it executes in the following way...
Is it right? I want to know more details.
-10427349 0Your class's constructor method should be called __construct(), not __constructor():
public function __construct(EntityManager $entityManager) { $this->em = $entityManager; }
-10856504 0 If you want to compute the Euclidean distance between vectors a and b, just use Pythagoras. In Matlab:
dist = sqrt(sum((a-b).^2)); However, you might want to use pdist to compute it for all combinations of vectors in your matrix at once.
dist = squareform(pdist(myVectors, 'euclidean')); I'm interpreting columns as instances to classify and rows as potential neighbors. This is arbitrary though and you could switch them around.
If have a separate test set, you can compute the distance to the instances in the training set with pdist2:
dist = pdist2(trainingSet, testSet, 'euclidean') You can use this distance matrix to knn-classify your vectors as follows. I'll generate some random data to serve as example, which will result in low (around chance level) accuracy. But of course you should plug in your actual data and results will probably be better.
m = rand(nrOfVectors,nrOfFeatures); % random example data classes = randi(nrOfClasses, 1, nrOfVectors); % random true classes k = 3; % number of neighbors to consider, 3 is a common value d = squareform(pdist(m, 'euclidean')); % distance matrix [neighborvals, neighborindex] = sort(d,1); % get sorted distances Take a look at the neighborvals and neighborindex matrices and see if they make sense to you. The first is a sorted version of the earlier d matrix, and the latter gives the corresponding instance numbers. Note that the self-distances (on the diagonal in d) have floated to the top. We're not interested in this (always zero), so we'll skip the top row in the next step.
assignedClasses = mode(neighborclasses(2:1+k,:),1); So we assign the most common class among the k nearest neighbors!
You can compare the assigned classes with the actual classes to get an accuracy score:
accuracy = 100 * sum(classes == assignedClasses)/length(classes); fprintf('KNN Classifier Accuracy: %.2f%%\n', 100*accuracy) Or make a confusion matrix to see the distribution of classifications:
confusionmat(classes, assignedClasses)
-37507547 0 Try
INSERT INTO [dbo].[WordRelationship] SElECT a.WordId, b.WordId from [dbo].[Temp] t JOIN [dbo].{Word] a on t.HeaderWord = a.Word LEFT JOIN [dbo].{Word] b on t.OtherWord = b.Word EDIT
removed LEFT in Join over Headerword since it is a not null field in WordRelationship.
-8227531 0You are overwritting the first value in your variable "myAjax" by assigning it a second value. It would be just like doing something like
var x=5; x=7; alert(x); Here x would hold the value of 7, because that was the last value assigned to it.
This function
myAjax.onreadystatechange=function() { if (myAjax.readyState==4 && myAjax.status==200) { document.getElementById(div).innerHTML=myAjax.responseText; } } will be called when the server you are calling returns a response. When the first call returns myAjax will be holding the value of the second call already, making the first call not display anything. You need to either assign these two variables synchronously (one after the other one has completed), or assign them to different variable names.
-5213630 0 Suspend and Resume thread (Windows, C)I'm currently developing a heavily multi-threaded application, dealing with lots of small data batch to process.
The problem with it is that too many threads are being spawns, which slows down the system considerably. In order to avoid that, I've got a table of Handles which limits the number of concurrent threads. Then I "WaitForMultipleObjects", and when one slot is being freed, I create a new thread, with its own data batch to handle.
Now, I've got as many threads as I want (typically, one per core). Even then, the load incurred by multi-threading is extremely sensible. The reason for this: the data batch is small, so I'm constantly creating new threads.
The first idea I'm currently implementing is simply to regroup jobs into longer serial lists. Therefore, when I'm creating a new thread, it will have 128 or 512 data batch to handle before being terminated. It works well, but somewhat destroys granularity.
I was asked to look for another scenario: if the problem comes from "creating" threads too often, what about "pausing" them, loading data batch and "resuming" the thread?
Unfortunately, I'm not too successful. The problem is: when a thread is in "suspend" mode, "WaitForMultipleObjects" does not detect it as available. In fact, I can't efficiently distinguish between an active and suspended thread.
So I've got 2 questions:
How to detect "suspended thread", so that i can load new data into it and resume it?
Is it a good idea? After all, is "CreateThread" really a ressource hog?
Edit
After much testings, here are my findings concerning Thread Pooling and IO Completion Port, both advised in this post.
Thread Pooling is tested using the older version "QueueUserWorkItem". IO Completion Port requires using CreateIoCompletionPort, GetQueuedCompletionStatus and PostQueuedCompletionStatus;
1) First on performance : Creating many threads is very costly, and both thread pooling and io completion ports are doing a great job to avoid that cost. I am now down to 8-jobs per batch, from an earlier 512-jobs per batch, with no slowdown. This is considerable. Even when going to 1-job per batch, performance impact is less than 5%. Truly remarkable.
From a performance standpoint, QueueUserWorkItem wins, albeit by such a small margin (about 1% better) that it is almost negligible.
2) On usage simplicity : Regarding starting threads : No question, QueueUserWorkItem is by far the easiest to setup. IO Completion port is heavyweight in comparison. Regarding ending threads : Win for IO Completion Port. For some unknown reason, MS provides no function in C to know when all jobs are completed with QueueUserWorkItem. It requires some nasty tricks to successfully implement this basic but critical function. There is no excuse for such a lack of feature.
3) On resource control : Big win for IO Completion Port, which allows to finely tune the number of concurrent threads, while there is no such control with QueueUserWorkItem, which will happily spend all CPU cycles from all available cores. That, in itself, could be a deal breaker for QueueUserWorkItem. Note that newer version of Completion Port seems to allow that control, but are only available on Windows Vista and later.
4) On compatibility : small win for IO Completion Port, which is available since Windows NT4. QueueUserWorkItem only exists since Windows 2000. This is however good enough. Newer version of Completion Port is a no-go for Windows XP.
As can be guessed, I'm pretty much tied between the 2 solutions. They both answer correctly to my needs. For a general situation, I suggest I/O Completion Port, mostly for resource control. On the other hand, QueueUserWorkItem is easier to setup. Quite a pity that it loses most of this simplicity on requiring the programmer to deal alone with end-of-jobs detection.
-40042882 0There are two dependencies usually involved: jmh-core and jmh-generator-annprocess. Their versions should agree. If they don't, then generator may produce the benchmark list in a format that core cannot understand. This most probably is such case.
Try to stick with eclipse, if you're having problems there, it will be worse trying to do things on the command line. The built in tools like log cat and the debugger are of great value.
-15233168 0I think you've got things a bit mixed up here. The server's encoding does not matter to the client, and it shouldn't. That is what RFC 2109 is trying to say here.
The concept of cookies in http is similar to this in real life: Upon paying the entrance fee to a club you get an ink stamp on your wrist. This allows you to leave and reenter the club without paying again. All you have to do is show your wrist to the bouncer. In this real life example, you don't care what it looks like, it might even be invisible in normal light - all that is important is that the bouncer recognises the thing. If you were to wash it off, you'll lose the privilege of reentering the club without paying again.
In HTTP the same thing is happening. The server sets a cookie with the browser. When the browser comes back to the server (read: the next HTTP request), it shows the cookie to the server. The server recognises the cookie, and acts accordingly. Such a cookie could be something as simple as a "WasHereBefore" marker. Again, it's not important that the browser understands what it is. If you delete your cookie, the server will just act as if it has never seen you before, just like the bouncer in that club would if you washed off that ink stamp.
Today, a lot of cookies store just one important piece of information: a session identifier. Everything else is stored server-side and associated with that session identifier. The advantage of this system is that the actual data never leaves the server and as such can be trusted. Everything that is stored client-side can be tampered with and shouldn't be trusted.
Edit: After reading your comment and reading your question yet again, I think I finally understood your situation, and why you're interested in the cookie's actual encoding rather than just leaving it to your programming language: If you have two different software environments on the same server (e.g.: Perl and PHP), you may want to decode a cookie that was set by the other language. In the above example, PHP has to decode the Perl cookie or vice versa.
There is no standard in how data is stored in a cookie. The standard only says that a browser will send the cookie back exactly as it was received. The encoding scheme used is whatever your programming language sees fit.
Going back to the real life example, you now have two bouncers one speaking English, the other speaking Russian. The two will have to agree on one type of ink stamp. More likely than not this will involve at least one of them learning the other's language.
Since the browser behaviour is standardized, you can either imitate one languages encoding scheme in all other languages used on your server, or simply create your own standardized encoding scheme in all languages being used. You may have to use lower level routines, such as PHP's header() instead of higher level routines, such as start_session() to achieve this.
BTW: In the same manner, it is the server side programming language that decides how to store server side session data. You cannot access Perl's CGI::Session by using PHP's $_SESSION array.
Only if you put the "nested select" (THis is referred to as a subquery) in the From Clause:
select FN from (select First_Name as FN from PERSON) z
-25460329 0 Difference from compiler perspective between passing by const value or const ref In the context of c++.
I wonder what is the difference, between this:
T f(T const val); and this:
T f(T const & val); I do know one is a pass by value, but, from the compiler's pespective, this is a value that is not going to change, so my questions are:
Mostly likely you don't have your app selected in the package explorer tree at the left.
Just click on the top-most item in the tree (ie. "MyFirstApp") and then try running again. Chances are you had "activity_main.xml" selected as it's the default selection when you built your test app.
-15469534 0 Remove signing from an assemblyI have a project open in Visual Studio (it happens to be Enyim.Caching). This assembly wants to be delay-signed. In fact, it desires so strongly to be delay-signed, that I am unable to force Visual studio to compile it without delay signing.
I have unchecked "Delay sign only" and "Sign the assembly" on the Visual Studio project properties box, and rebuilt. The assembly is still marked for delay sign (as shown by sn.exe -v).
I have unloaded the project and verified that the signing is set to false. When reloading the project, the check boxes for "Sign" and "Delay Sign" are checked.
I have verified that no attributes are present in the AssemblyInfo (or elsewhere) that would cause this.
I have searched the Internet for a solution, but have found none.
How can I do this?
-565460 0You sound as though you are "rolling your own" authentication system.
I would look into using ASP.NET's built in Forms authentication system that is commonly used with an ASP.NET Membership Provider. Built-in providers already exist for SQL Server, and you can create your own Membership Provider by inheriting from the System.Web.Security.MembershipProvider base class.
Essentially, the ASP.NET membership providers usually work by setting a client side cookie (also known as an Authentication Ticket) in the client's browser, once the client has successfully authenticated themselves. This cookie is returned to the web server with each subsequent page request, allowing ASP.NET, and thus your code, to determine who the user is, usually with a single line of code like so:
string username = HttpContext.Current.User.Identity.Name; // The above gets the current user's name. if(HttpContext.Current.User.Identity.IsAuthenticated) // Do something when we know the user is authenticated. You then should not need to store anything in the Session state. Of course, if you want to store user-specific data in a session variable (i.e. user-data that may not be part of the authentication of a user, perhaps the user's favourite colour etc.) then by all means you can store that in a session variable (after retrieving it from the DB when the user is first authenticated). The session variable could be stored based on the user's name (assuming unique names) and retrieved using code similar to the above which gets the current user's name to access the correct session object.
Using the built-in forms authentication will also allow you to "protect" areas of your website from un-authorized users with simple declarative code that goes in your web.config, for example:
<authorization> <deny users="?"/> </authorization> Adding the above to your "main" web.config would ensure that none of your pages are accessible to un-authorized users (though you'd probably never do this in reality - it's just meant as an example). Using the ASP.NET Role Provider in conjunction with the Membership Provider will give you even greater granularity over who can or can't access various sections of your website.
-501990 0Preventing the user from using the functionality of Screen is bad form (unless you have a shared login which runs your application).
Instead, make your application deal with the use case you've shown by autologout, warning new connecting users and giving them the option to boot the other user, handling multiple users, etc.
-10414320 0No, the current beta VS11 Express edition only supports creating Metro apps. Whether the RTM edition ever will support old style apps requires a crystal ball. I doubt it.
You'll need to use the VS2010 Express edition if you want to create legacy apps.
-2301991 0 C++ Portable way of programmatically finding the executable root directoryPossible Duplicate:
how to find the location of the executable in C
Hi,
I am looking for a portable way to find the root directory of a program (in C++). For instance, under Linux, a user could copy code to /opt, add it to the PATH, then execute it:
cp -r my_special_code /opt/ export PATH=${PATH}:/opt/my_special_code/ cd /home/tony/ execution_of_my_special_code (where "execute_my_special_code" is the program in /opt/my_special_code).
Now, as a developer of "execution_of_my_special_code", is there a portable programmatical way of finding out that the executable is in /opt/my_special_code?
A second example is on MS Windows: What if my current working directory is on one hard drive (e.g. "C:\") and the executable is placed on another (e.g. "D:\")?
Ultimately, the goal is to read some predefined configuration files that are packaged with the program code without forcing the user to enter the installation directory.
Thanks a lot in advance!
-28050839 0See:
Warning If a connection opened by fsockopen() wasn't closed by the server, feof() will hang. To workaround this, see below example:
On: feof
The workaround essentially waits default_socket_timeout and then terminates the while-loop.
It looks like you're somehow sending a pushBetter method call to your view controller which it is apparently not prepared for (according to your code and the error):
-[HBFSViewController pushBetter]: unrecognized selector sent to instance 0x693ccb0' Can you to a global search for "pushBetter" and see where it is in your project??
-2963306 0You might want to take a look at what caused the problem in my case and how I solved it here.
-11149404 0 Android Scrollview not catching longclickAs said in the title, I have a scrollview that should be listening for longclicks, but isn't catching any. Nothing happens when I hold the scrollview- no logs, no haptic feedback, & no dialog.
Thanks in advance!
JAVA:
... ScrollView text_sv = (ScrollView) findViewById(R.id.text_sv); text_sv.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { MMMLogs.i("click", "long-click recognized"); AlertDialog.Builder builder = new AlertDialog.Builder(_this); builder .setTitle(name) .setMessage(DHMenuStorage.notification) .setCancelable(false) .setNegativeButton("Close", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); return true; } }); ... XML:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:padding="5dp" > <ScrollView android:id="@+id/text_sv" android:layout_width="match_parent" android:layout_height="75dp" android:hapticFeedbackEnabled="true" android:clickable="true" android:longClickable="true" > <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:id="@+id/name" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@color/Gray" android:focusable="false" android:gravity="center" android:padding="4dp" android:text="-- Dining Hall Name --" android:textColor="@color/Black" android:textSize="28dp" android:textStyle="bold" /> <TextView android:id="@+id/note" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@color/Gray" android:focusable="false" android:gravity="center" android:padding="4dp" android:text="-- Special note here --" android:textColor="@color/Black" android:textSize="14dp" android:textStyle="normal" /> </LinearLayout> </ScrollView> <TabHost android:id="@android:id/tabhost" android:layout_width="fill_parent" android:layout_height="fill_parent" > <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:padding="5dp" > <TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="5dp" /> </LinearLayout> </TabHost>
-10937998 0 I don't see any relationship between those two tables.
In your uploads table definition change this
`member_school_id` int(11) NOT NULL DEFAULT 1 Remove quote from member_school_id since it's a INT field.
SELECT uploads.*, audienceuploadassociation.* FROM uploads JOIN audienceuploadassociation ON uploads.upload_id = audienceuploadassociation.upload_id WHERE uploads.member_id = '1' AND uploads.member_school_id=1 AND uploads.subject = 'ESL' AND uploads.topic = 'Poetry' LIMIT 20
-37846521 0 How to track the lifetime of a Drag/Drop operation? I have an application which let's me drag&drop items from a modified QListWidget on to a modified QLabel using startDrag(), dragEnterEvent(), dropEvent(), etc.
I now want to not only get notified, when the dragging starts but also when it get's interrupted (by pressing ESC or dropping somewhere in the void). (My goal is to uncover a hidden widget I can drop items on which hides again as soon as the drag operation gets interrupted.)
I crawled the docs but find anything promising - has someone accomplished this already?
There is a quite similar question already but it didn't get useful answers and it's two years old - so maybe there are some new trickies introduced by Qt5?
-26846968 0If you think about the overall operation that you are trying to perform, it is really just a Wipe-and-Replace based on what you are passing in. According to your stated rules:
Hence, you shouldn't be using MERGE for this. Instead, just do:
DELETE fc FROM Fruits_Crates fc WHERE fc.CrateID IN (SELECT DISTINCT tmp.CrateID FROM #FruitCrates tmp); INSERT INTO Fruits_Crates (FruitID, CrateID) SELECT tmp.FruitID, tmp.CrateID FROM FruitCrates tmp; Or, if most of the time the number of items that match exceeds the number of items that will be removed and added, you can take a more targeted approach:
CREATE TABLE #FruitCrates (FruitID INT, CrateID INT); CREATE TABLE #Fruits_Crates (FruitID INT, CrateID INT); --DELETE FROM #FruitCrates INSERT INTO #FruitCrates (CrateID, FruitID) VALUES (2, 4); INSERT INTO #FruitCrates (CrateID, FruitID) VALUES (2, 6); INSERT INTO #FruitCrates (CrateID, FruitID) VALUES (3, 26); --DELETE FROM #Fruits_Crates; INSERT INTO #Fruits_Crates (CrateID, FruitID) VALUES (1, 4); INSERT INTO #Fruits_Crates (CrateID, FruitID) VALUES (2, 4); INSERT INTO #Fruits_Crates (CrateID, FruitID) VALUES (2, 8); DELETE fc --SELECT fc.*, '--' AS [--], tmp.* FROM #Fruits_Crates fc LEFT JOIN #FruitCrates tmp ON tmp.CrateID = fc.CrateID AND tmp.FruitID = fc.FruitID WHERE tmp.CrateID IS NULL AND fc.CrateID IN (SELECT DISTINCT tmp2.CrateID FROM #FruitCrates tmp2); INSERT INTO #Fruits_Crates (FruitID, CrateID) SELECT tmp.FruitID, tmp.CrateID FROM #FruitCrates tmp LEFT JOIN #Fruits_Crates fc ON fc.CrateID = tmp.CrateID AND fc.FruitID = tmp.FruitID WHERE fc.CrateID IS NULL; SELECT CrateID, FruitID FROM #Fruits_Crates; Output:
CrateID FruitID 1 4 2 4 2 6 3 26 Result:
This will replace all occurrence of "str" with "rep" in "src"...
void strreplace(char *src, char *str, char *rep) { char *p = strstr(src, str); do { if(p) { char buf[1024]; memset(buf,'\0',strlen(buf)); if(src == p) { strcpy(buf,rep); strcat(buf,p+strlen(str)); } else { strncpy(buf,src,strlen(src) - strlen(p)); strcat(buf,rep); strcat(buf,p+strlen(str)); } memset(src,'\0',strlen(src)); strcpy(src,buf); } }while(p && (p = strstr(src, str))); }
-22087308 0 Error in Insert a Products wth CSV in magento I have a a csv files for insert a products in magento. but there are problem with inserting a products description. In description cell when the code started it stop the insertion of data. Please give me a solution to solve this problem.
-7719501 0 DynamicJasper (DJ) is an open source free library that hides the complexity of Jasper Reports. -13595126 0 Php, traffic catcherI'm starting up an image hosting website which also offers pay per view, for example upload an image and it get 1000 views you get $2.00 something along those lines. The only issue I have is that I want to be able to view the traffic per image and what I.P address were used to view the image.
So someone accesses my site they upload an image using a file form input field it then returns a link e.g - domain.com/image.png what could I add to my code so that some sort of tracking is added to each new image thats uploaded.
I will be greatful for any ideas I get!
THANKS
-32794254 0 App Crashes On Calling Webview Loadurl method inside switchmy app contains a fragment with a webview and a edit text.i have a navigation drawer with 3 choices and use a switch condition to handle selection,on 3 selections i update the same webview with different html files using the foolowing code ..but my app crashes..
@Override public void onNavigationDrawerItemSelected(int position) { // update the main content by replacing fragments Fragment fragment; switch (position) { case 0: WebView wv = (WebView) findViewById(R.id.webView); wv.loadUrl("file:///android_asset/src/web.html"); //app crashes fragment = getFragmentManager().findFragmentByTag(WebFragment.TAG); if (fragment == null) { fragment = new WebFragment(); } getFragmentManager().beginTransaction().replace(R.id.container, fragment, WebFragment.TAG).commit(); break; case 1: fragment = getFragmentManager().findFragmentByTag(WebFragment.TAG); if (fragment == null) { fragment = new WebFragment(); } getFragmentManager().beginTransaction().replace(R.id.container, fragment, WebFragment.TAG).commit(); break; case 2: fragment = getFragmentManager().findFragmentByTag(WebFragment.TAG); if (fragment == null) { fragment = new WebFragment(); } getFragmentManager().beginTransaction().replace(R.id.container, fragment, WebFragment.TAG).commit(); break; } } my logcat logs http://pastebin.com/snbzASTq
please provide a workaround for this
-14118997 0 How to Upload With ASP.NETI know I might get a lot of downvotes for this, but I cannot find the information anywhere. I am trying to upload my compiled web application to the internet. I was told that all I need is the dll file which is supposed to go into the bin folder? Is this true or do I need to upload both the dll file and the bin folder?
Also, is there a better way to build so that I dont have to intermix my image, css, and so on into my project folder? Maybe a way to copy the dll file to a bin folder and all my aspx pages?
I got it to work but it seems like I keep duplicating a bunch of files and I know eventually some problem will arise.
Thanks and happy new year to everyone.
-39679706 0Well I believe the default user acls are still working and they are not overrided. The way loopback decides which ACL entry is effective for the request, is by selecting most specific one that appears later. So loopback has defined this entry:
{ "principalType": "ROLE", "principalId": "$everyone", "permission": "ALLOW", "property": "login" } Since it's as specific as it gets, to beat that you have to add this in your model:
{ "principalType": "ROLE", "principalId": "$everyone", "permission": "DENY", "property": "login" } There's also another way to remove the default user acls via code but it's not documented.
-17306361 0The CPAN module YAPE::Regex::Explain can be used to parse and explain Perl regexes that you don't understand. Here is the output for your first regex:
(?-imsx:^(\d+)_[^,]+,"",(.+)"NR"(.+)"0","","") matches as follows: NODE EXPLANATION ---------------------------------------------------------------------- (?-imsx: group, but do not capture (case-sensitive) (with ^ and $ matching normally) (with . not matching \n) (matching whitespace and # normally): ---------------------------------------------------------------------- ^ the beginning of the string ---------------------------------------------------------------------- ( group and capture to \1: ---------------------------------------------------------------------- \d+ digits (0-9) (1 or more times (matching the most amount possible)) ---------------------------------------------------------------------- ) end of \1 ---------------------------------------------------------------------- _ '_' ---------------------------------------------------------------------- [^,]+ any character except: ',' (1 or more times (matching the most amount possible)) ---------------------------------------------------------------------- ,"", ',"",' ---------------------------------------------------------------------- ( group and capture to \2: ---------------------------------------------------------------------- .+ any character except \n (1 or more times (matching the most amount possible)) ---------------------------------------------------------------------- ) end of \2 ---------------------------------------------------------------------- "NR" '"NR"' ---------------------------------------------------------------------- ( group and capture to \3: ---------------------------------------------------------------------- .+ any character except \n (1 or more times (matching the most amount possible)) ---------------------------------------------------------------------- ) end of \3 ---------------------------------------------------------------------- "0","","" '"0","",""' ---------------------------------------------------------------------- ) end of grouping ---------------------------------------------------------------------- You can use the module to parse your second regex as well (I won't dump it here since the explanation will be very long and very redundant.) But if you want to give it a shot, try this:
use strict; use warnings; use YAPE::Regex::Explain; my $re = qr/^[^_]+_[^,]+,"([\d\/]+)","[^"]+","[^"]+","[^"]+","[^"]+","[^"]+", "[^"]+","[^"]+","[^"]+","[^"]+","[^"]+","[^"]+","[^"]+",.+/x; print YAPE::Regex::Explain->new( $re )->explain;
-25282869 0 First check all outlet connection are correct or not.
Now change if condition to isFirstResponder()
func textFieldShouldReturn(textField: UITextField!) -> Bool { if (userNameSignUpTextField.isFirstResponder()){ userNameSignUpTextField.resignFirstResponder() passwordSignUpTextField.becomeFirstResponder() } else if(passwordSignUpTextField.isFirstResponder()) { passwordSignUpTextField.resignFirstResponder() emailSignUpTextField.becomeFirstResponder() } return true } Hope it will help you
-26842480 0You can use this awk using same regex as provided by OP:
awk -v re='[tsh]*est' '{ i=0; s=$0; while (p=match(s, re)) { p+=RLENGTH; i+=p-1; s=substr(s, p) } print i; }' file 14 15 35
-12209065 0 Allow users to create a new table but one table for each topic only I am trying to create something where the user can create a table for a topic, but only one topic table and in that topic table other users will be able to add to that topic table.
I need the topic table to be only created once. So for ex:
User A creates a a new topic which is a new table about oranges.
Then other users will be able to add to that oranges table, but no other users can create another table called oranges.
How should I approach this matter?
What is the code for letting the users create the table but only once?
Also how safe is it to give the users the ability to create tables?
Here is some code I have that lets users add and displays data from the database.
<?php include 'connection.php'; $query = "SELECT * FROM people"; $result = mysql_query($query); While($person = mysql_fetch_array($result)) { echo "<h3>" . $person['Name'] . "</h3>"; echo "<p>" . $person['Description'] . "</p>"; echo "<a href=\"modify.php?id=" . $person['ID']. "\">Modify User</a>"; echo "<span> </span>"; echo "<a href=\"delete.php?id=" . $person['ID']. "\">Delete User</a>"; } ?> <h1>Create a User</h1> <form action="create.php" method="post"> Name<input type ="text" name="inputName" value="" /><br /> Description<input type ="text" name="inputDesc" value="" /> <br /> <input type="submit" name="submit" /> </form> You advice will be great help!
-16004799 0Since you're using WordPress, the propper way of doing this is to send a JavaScript variable with wp_localize_script in functions.php:
add_action('wp_enqueue_scripts', 'my_frontend_data'); function my_frontend_data() { global $current_user; wp_localize_script('data', 'Data', array( 'userMeta' => get_user_meta($current_user->ID, '_fbpost_status', true), 'templateUrl' => get_template_directory_uri() )); } The above will add a JavaScript Data variable that's accessible in all your pages. Then you can use it in the front-end like so:
var ajaxUrl = Data.templateUrl +'/includes/ajaxswitch/'; $('#1').iphoneSwitch(Data.userMeta, function() { $('#ajax').load(ajaxUrl +'on.php'); }, function() { $('#ajax').load(ajaxUrl +'off.php'); }, { switch_on_container_path: Data.templateUrl +'iphone_switch_container_off.png'; });
-15966057 0 You said you set a custom image for the UIControlStateHighlighted state. This should disable the default behaviour.
If you still have problems you can disable this effect by setting the adjustsImageWhenHighlighted property to NO and use whatever custom effect you want.
i wanto dynamic add 5 TLable in my iOS app.
like this
Procedure Form1.FormCreate(Sender: TObject) var I: Integer; begin for I := 1 to 5 do begin with TLabel.Create(Self) do begin Parent := self; Align := TAlignLayout.Top; Height := 50; Text := IntToStr(I); end; end; end; i think the order is 12345, but I get 15432.
What can I do to get the desired results?
-27384081 0Add before RewriteRule:
RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f Not rewrite real file or folder
-32767829 0Quick example of drawing the line in the Paint() event, and allowing it to be toggled with a Button:
Public Class Form1 Private x1 As Integer = 0 Private y1 As Integer = 0 Private x2 As Integer = 0 Private y2 As Integer = 0 Private DrawLine As Boolean = False Private stift As New Pen(Brushes.Black, 3) Public Sub New() InitializeComponent() x2 = Me.ClientSize.Width y2 = Me.ClientSize.Height End Sub Private Sub Form1_SizeChanged(sender As Object, e As EventArgs) Handles MyBase.SizeChanged x2 = Me.ClientSize.Width y2 = Me.ClientSize.Height Me.Refresh() End Sub Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles MyBase.Paint If DrawLine Then Dim g As Graphics = e.Graphics g.DrawLine(stift, x1, y1, x2, y2) End If End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click DrawLine = Not DrawLine Me.Refresh() End Sub End Class This approach allows you to change the coords from somewhere else and call Refresh() to update the screen. For more than one line, consider using a List() that holds information about the coords, then iterate over that in the Paint() event.
-16255556 0Install db
sudo -u _mysql /opt/local/lib/mariadb/bin/mysql_install_db Change root password
/opt/local/lib/mariadb/bin/mysqladmin -u root password 'new-password' Alternatively you can run:
/opt/local/lib/mariadb/bin/mysql_secure_installation' You can start the MariaDB daemon with:
cd /opt/local; /opt/local/lib/mariadb/bin/mysqld_safe --datadir='/opt/local/var/db/mariadb'
-35963859 0 Try this:
$total = array(); foreach ($data as $key => $row) { $total[$key] = $row['total']; } // this sorts your $data array by `total` in descending order // so the max for `total` is the first element array_multisort($total, SORT_DESC, $data); And now, use $data[0];
$( document ).ready(function() { paypal.use(["login"], function (login) { login.render({ "appid": "-************", "authend": "sandbox", "scopes": "profile email address phone", "containerid": "paypalLogin", "locale": "en-us", "text": "Verify your account with Paypal", "redirect_uri": "http://localhost:57559/" }); }); }); while creating the button request as a text attribute, we can set the button text
-8156114 0You can pass your array as a JSON string to JavaScript inside the loaded page by calling UIWebView stringByEvaluatingJavascriptFromString:.
First, use a JSON library to encode the contents of your array into a JSON-encoded string. If you use SBJSON then something like this:
NSString* json = [myArray JSONRepresentation]; (this will work with your simple array of strings. If you have a more complicated array of other objects, they will have to be compatible with the JSON serializer)
Then, pass this to your webview:
NSString* js = [NSString stringWithFormat: "myJavaScriptFunction( '%@' );", json]; [myWebView stringByEvealuatingJavascriptFromString: js]; In your HTML file you will have to implement a JavaScript function (in this example, "myJavaScriptFunction") that accepts the passed JSON, and decodes it into a Javascript array.
-28588354 0Presumably something like this:
#!/bin/bash class=org.gnome.settings-daemon.peripherals.touchpad name=tap-to-click status=$(gsettings get "$class" "$name") status=${status,,} # normalize to lower case; this is a modern bash extension if [[ $status = true ]]; then new_status=false else new_status=true fi gsettings set "$class" "$name" "$new_status" Breaking it down into pieces:
#!/bin/bash ensures that the interpreter for this script is bash, enabling extended syntax such as [[ ]].$( ) is "command substitution"; this runs a command, and substitutes the output of that command. Thus, if the output is true, then status=$(...) becomes status=true.${name,,} expands the contents of name while converting those contents to all-lowercase, and is only available in newer versions of bash. If you want to support /bin/sh or older releases of bash, consider status=$(printf '%s\n' "$status" | tr '[:upper:]' '[:lower:]') instead, or just remove this line if the output of gsettings get is always lowercase anyhow.[[ $status = true ]] relies on the bash extension [[ ]] (also available in other modern ksh-derived shells) to avoid the need for quoting. If you wanted it to work with #!/bin/sh, you'd use [ "$status" = true ] instead. (Note that == is allowable inside [[ ]], but is not allowable inside of [ ] on pure POSIX shells; this is why it's best not to be in the habit of using it).Note that whitespace is important in bash! foo = bar, foo= bar and foo=bar are completely different statements, and all three of them do different things from the other two. Be sure to be cognizant of the differences in copying from this example.
I looked up intent filters and found that they will be used when "Android finds the appropriate component to start by comparing the contents of the intent to the intent filters declared in the manifest file of other apps on the device"(http://developer.android.com/guide/components/intents-filters.html#Building)
In my manifest file, I have
<intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> which from reading that guide means that this activity can handle an implicit intent with action of main and category of launcher.
However what if i have multiple applications with the same intent filter in the manifest file. I know that some implicit intent will be called with action of main and category of launcher. How does the Android O.S know to choose this application?
-17610376 0Strictly speaking, those declarations are not attributes but namespaces nodes. To get them with XPath, it depends of what version of XPath you use.
For XPath 1, use :
/*/namespace::* For XPath 2, use : fn:in-scope-prefixes and fn:namespace-uri-for-prefix to get the prefix and the associated namespace uri.
In your case, control will go to the while-condition after sorting all the elements.so no need to add do-while.Only set size you want. int i,j,n=4,k,temp; int arr[]={3,5,1,7,9,1,2};
for(i=0; i<n; i++){ for(j=i+1; j<n; j++){ if(arr[j] < arr[i]){ temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } }
-9479729 0 In the project's properties (right-click on project => Properties => Resource) there is a Text File Encoding section.
Did you configure the encoding here? If not, you have two choices : "Inherited from container" (which should be the workspace default, in your case UTF-8) and "Other" which let you choose a specific encoding (ISO-88591)...
I just tested that on one of my projects, closed it and reopened it and the ISO88591 encoding is still configured.
Note that I'm using a plain Eclipse though, not a PDT project. PDT may handle encoding settings differently, but somehow I doubt that (file encoding being a low level functionality it makes sense that all plugins share this behavior).
-29943083 0 Angular pass dynamic scope to directiveI have a directive that takes an attribute value from a an http call like so:
Controller
app.controller("HomeController", function($scope){ $http.get("/api/source").then(function(res){ $scope.info = res.data }); }); HTML
<div ng-controller="MainController"> <ng-mydirective data-info="{{info}}"></ng-mydirective> </div> Directive:
app.directive("ngMydirective", function(){ return { restrict: "E", templateUrl: "/partials/info.html", link: function(scope, element, attrs){ scope.info = attrs.info; } } }); I'm trying to pass that info variable from the controller, into the directive, through an attribute. It doesn't work because the variable value is initially created from an asynchronous http call, so at the time the directive is created, there is no value.
Is there a way to do this?
-31191462 0You can't copy a range with more than one area. You will have to transfer the data over one range at a time. Using Range.Areas you can see that you have multiple areas in multipleRanges.
I have the following program snippet
my $nfdump_command = "nfdump -M /data/nfsen/profiles-data/live/upstream1 -T -R ${syear}/${smonth}/${sday}/nfcapd.${syear}${smonth}${sday}0000:${eyear}/${emonth}/${eday}/nfcapd.${eyear}${emonth}${eday}2355 -n 100 -s ip/bytes -N -o csv -q | awk 'BEGIN { FS = \",\" } ; { if (NR > 1) print \$5, \$10 }'"; syslog("info", $nfdump_command); my %args; Nfcomm::socket_send_ok ($socket, \%args); my @nfdump_output = `$nfdump_command`; my %domain_name_to_bytes; my %domain_name_to_ip_addresses; syslog("info", Dumper(\@nfdump_output)); foreach my $a_line (@nfdump_output) { syslog("info", "LINE: " . $a_line); } Bug: @nfdump_output is empty. 
The $nfdump_command is correct and it printing output when ran individually

For finding out amount from bank transaction message.
(?i)(?:(?:RS|INR|MRP)\.?\s?)(\d+(:?\,\d+)?(\,\d+)?(\.\d{1,2})?) For finding out merchant name from bank transaction message.
(?i)(?:\sat\s|in\*)([A-Za-z0-9]*\s?-?\s?[A-Za-z0-9]*\s?-?\.?) For finding out card name(debit/credit card) from bank transaction message.
(?i)(?:\smade on|ur|made a\s|in\*)([A-Za-z]*\s?-?\s[A-Za-z]*\s?-?\s[A-Za-z]*\s?-?)
-13359337 0 I had the problem yesterday and after trying out answers in the forum and others but made no headway. My code looked like this.
// Open up the file and read the fields on it. var pdfReader = new PdfReader(PATH_TO_PDF); var fs = new FileStream(pdfFilename, FileMode.Create, FileAccess.ReadWrite) var stamper = new PdfStamper(pdfReader, fs); var pdfFields = stamper.AcroFields; //I thought this next line of code I commented out will do it //pdfFields.RenameField("currentFieldName", "newFieldName"); // It did for some fields, but returned false for others. // Then I looked at the AcroFields.RenameField method in itextSharp source and noticed some restrictions. You may want to do the same. // So I replaced that line pdfFields.RenameField(currentFieldName, newFieldName); with these 5 lines AcroFields.Item item = pdfFields.Fields[currentFieldName]; PdfString ss = new PdfString(newFieldName, PdfObject.TEXT_UNICODE); item.WriteToAll(PdfName.T, ss, AcroFields.Item.WRITE_VALUE | AcroFields.Item.WRITE_MERGED); item.MarkUsed(pdfFields, AcroFields.Item.WRITE_VALUE); pdfFields.Fields[newFieldName] = item; And that did the job
-11621525 1 How to get the records from the current month in App Engine (Python) Datastore?Given the following entity:
class DateTest(db.Model): dateAdded = db.DateTimeProperty() #... What would be the best way to get the records from the current month?
-1368413 0The code works fine for me, too. As Justin suggested, you're probably overwriting your extracted data.
May I suggest less-redundant code? For example:
$urls = array('http://www.wowarmory.com/character-sheet.xml?r=Crushridge&n=Thief', 'http://www.wowarmory.com/character-sheet.xml?r=Ursin&n=Kiona'); $browser = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 YFF3 Firefox/3.0.1'; $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); curl_setopt($ch, CURLOPT_USERAGENT, $browser); foreach ($urls as $url) { curl_setopt($ch, CURLOPT_URL, $url); $result20 = curl_exec($ch); // Extract the values out of the xml here (to separate variables). } curl_close($ch);
-16132752 0 How do I alter the value being updated in a ListView? I can't seem to find an answer to this, maybe I'm not using the correct terminology.
I have a ListView that is editable, I want it so that if a user clicks on Edit and then Update, that the field is updated with the value from another textbox, not the field they are editing.
The reason for this is that I have a Colour Picker that alters the value of a textbox, when they click Update I want this value to be the updated value.
I guess I utilise the ItemUpdating event, but I don't have much in the way of code because I'm pretty lost. I have this so far:
protected void ListView2ItemUpdating(object sender, ListViewUpdateEventArgs e) { var selectedItem = ListView2.Items[ListView2.EditIndex]; // I have no idea what to put here something = ColourChosen.Value; } Here is an image that I hope will make what I'm trying to do a little more understandable:

If any one could point me in the right direction of any examples, that would be much appreciated.
-14062700 0 Refactor code with return statementsThe "if" blocks with checkcustomers are exactly used in other methods in this class, so there is a lot of code dublication for same checks. But I cant also directly extract this checksomethings to one single method because they have return values.
Some good ideas to refactor this code? I just modified this code to simplify here, so dont get caught on minor issues in this code(if any), Basically question is how to a extract a piece of code to a method(because it is dublicated on other methods) when there are many returns in that current method.
public Details getCustomerDetails(){ if(checkifcustomerhasnoboobs){ ..worry about it.. return new Details("no"); } if(checkifcustomerplaytenniswell){ ..do find a tennis teacher return new Details("no cantplay"); } //...ok now if customer passed the test, now do the some real stuff // // CustomerDetails details= getCustomerDetailsFromSomewhere(); return details; }
-5605470 0 Created by Dr. Martin Porter, Snowball is a small string processing language designed for creating stemming algorithms for use in Information Retrieval. It was created partially to provide a canonical implementation of Porter's stemming algorithm, and partially to facilitate the creation of stemmers for languages other than English.
A further aim of Porter's was to provide a way of creating and defining stemmers that could readily or automatically be translated into C, Java, or other programming languages. The Snowball compiler translates a Snowball script (a .sbl file) into either a thread-safe ANSI C program or a Java program. For ANSI C, each Snowball script produces a program file and corresponding header file (with .c and .h extensions).
The name "Snowball" is a tribute to the SNOBOL programming language.
-17185389 1 How would I get the detailed version of my Python interpreter via a one-liner or command-line option?The output of --version itself is a little too brief:
C:\>python --version Python 2.7.5 However, if I run Python from the command prompt, I get something similar to the following, with verbose version info for the interpreter all on one line:
C:\> python Python 2.7.5 (default, May 15 2013, 22:44:16) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. Is there a simple way, in a one-line command or via some options to get that same verbose version info line as a string that I could use to populate an environment variable or such?
In effect, is there a more verbose variant of --version I'm unaware of?
-35729161 0Your JSX syntax was not correct. I tested this by copying your code into https://babeljs.io/repl/. Specifically, in your User component, you have:
<img src="{this.props.pics} /> You need to remove the double quote from that line.
-36355136 0 Bind dynamic parameters to SQL SP with php pdoThis question is related to this SQL Stored procedure formatting error
Wanna bind dynamic parameters from PHP PDO. Only getting results for one parameter(@rep=:rep). When second parameter added won't getting any out put
public function ar_report($rep,$market,$agent,$warehouse,$customername,$regionalname){ $query = "{CALL arReports(@rep=:rep,@market=:market)}"; $stmt = $this->db->prepare($query); if ($rep != "") { $stmt->bindParam(':rep', $rep); } if ($market != "") { $stmt->bindParam(':market', $market); } $stmt->execute(); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); return $rows; }
-10421664 0 remove dot . after $.("
$("#test1").click( function () { $ratio = 1; }); $("#test2").click( function () { $ratio = 2; });
-31869705 0 I got this answer by casting value into dacimal.
SET p_percentage = DECIMAL(((p_obtain_marks * 100)/p_total),3,2);
Thanks Henrik Loeser and Alex.
-36102038 0First modify your tableView:cellForRowAtIndexPath: implementation as follows. Then you need to implement the click handler. One way would be in the MyCell class. Another would be to override selectRowAtIndexPath. Without knowing more about what you want (e.g. multiple vs single selection), it's hard to give actual code but here's something.
BOOL clickedRows[MAX_ROWS]; // Init this array as all false in your init method. It would be better to use NSMutableArray or something similar... // selectRowAtIndexPath code int row = indexPath.row if(clickedRows[row]) clickedRows[row]=NO; // we reverse the selection for the row else clickedRows[row]=YES; [self.tableView reloadData]; // cellForRowAt... code MyCell *cell = [tableView dequeueResuableCell... if(cell.clicked) { // Nice Nib [tableView registerNib:[UINib nibWithNibName... for CellReuse... } else { // Grey Nib [tableView registerNib:[UINib nibWithNibName... for CellReuse... }
-33873782 0 Thanks alvas for summing it up so nicely, this would help other people too. Moreover I also find any version of the Reuters dataset which has relatively less number of categories. This article here explains it better.
-7743588 0There's not much to go on here but it sounds like you are looking for the Admin Skin functionality. The admin skin is the skin used when you are editing the contents of a module.You can specify the Admin skin in Site Settings. There are definitely cases, and I suspect this is one of them, where it's helpful to have a separate Admin skin.
But generally, I'm not aware of any cases where DotNetNuke will prevent you from doing something you can do outside of DNN. There really are no limitations in it's skinning implementation, as it exposes the full capabilities of ASP.NET. The only caveat is sometimes some additional unwanted markup is added around your content. With DNN6, they are making the rendering of lots of elements cleaner and more semantic.
-33565196 0Just use
onblur="fnx()" It may work!!
-8146024 0 Controlling color and width of HTML input boxThe box diameter created by the code below is gray and about 1 pixel wide. Is there any way I could make it 3 pixels wide and this color: #DE2A00?
<div class="usernameformfield"><input tabindex="1" accesskey="u" name="username" type="text" maxlength="35" id="username" /></div>
-22906138 0 function paging_nav() { $paged = get_query_var( 'paged' ) ? intval( get_query_var( 'paged' ) ) : 1; $pagenum_link = html_entity_decode( get_pagenum_link() ); $query_args = array(); $url_parts = explode( '?', $pagenum_link ); if ( isset( $url_parts[1] ) ) { wp_parse_str( $url_parts[1], $query_args ); } $pagenum_link = remove_query_arg( array_keys( $query_args ), $pagenum_link ); $pagenum_link = trailingslashit( $pagenum_link ) . '%_%'; $format = $GLOBALS['wp_rewrite']->using_index_permalinks() && ! strpos( $pagenum_link, 'index.php' ) ? 'index.php/' : ''; $format .= $GLOBALS['wp_rewrite']->using_permalinks() ? user_trailingslashit( 'page/%#%', 'paged' ) : '?paged=%#%'; $links = paginate_links( array( 'base' => $pagenum_link, 'format' => $format, 'total' => $GLOBALS['wp_query']->max_num_pages, 'current' => $paged, 'mid_size' => 1, 'add_args' => array_map( 'urlencode', $query_args ), 'prev_text' => __( 'Previous Page ' ), 'next_text' => __( 'Next Page' ), ) ); echo $links ;
-3452327 0 C# Adding one more option to PictureBox i was wondering how could i add .customString to PictureBox object.
Something like:
PictureBox box = new PictureBox(); box.CustomString = "string here"; And then later on i would be access it.
MessageBox.Show(boxname.CustomString); Thank you.
-21755538 0 Nginx proxy rewrite configurationit is possible to rewrite a url and use a proxy server for backgound connection?
An example, I want to use this URL my.domain.org/demo on my proxy server and redirect this into the root directory of my tomcat on another server with proxy_pass my.tomcat.local.
The url must be place my.domain.org/demo and must used the proxy url my.tomcat.local (without any subdomains). Is this hook possible?
Thanks !!!!
-39697560 0Orientation attribute is per activity so you can declare the orientation for only the activity that contains the fragment so that it is in landscape and the rest of the activities will remain as they are.
So you need set orientation in onCreateView of each fragment Plse Check below code:
FragmentA
public class FragmentA extends Fragment { @Override public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_a, container, false); changeFragmentOrientation(); return view; } } public void changeFragmentOrientation(){ getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } FragmentB
public class FragmentB extends Fragment { @Override public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_b, container, false); changeFragmentOrientation(); return view; } } public void changeFragmentOrientation(){ getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); }
-35386714 0 Why is my code not displaying the string value attached to an integer? I'm totally new to programming and Swift is the first language I'm learning.
I've been researching this issue, but I'm not really sure I'm researching the right thing. Until now all my research has been about converting integers to strings etc, but I suspect that I'm barking up the wrong tree. And perhaps my question title is misleading too, but here's my scenario.
I am working on a quiz app that stores all the questions and answers in a .json file in the following format:
{ "id" : "1", "question": "Earth is a:", "answers": [ "Planet", "Meteor", "Star", "Asteroid" ], "difficulty": "1" } The correct answer is always the one listed first within the .json file.
The app presents the question with the four possible answer buttons (which have been shuffled using the following code):
func loadQuestions(index : Int) { let entry : NSDictionary = allEntries.objectAtIndex(index) as! NSDictionary let question : NSString = entry.objectForKey("question") as! NSString let arr : NSMutableArray = entry.objectForKey("answers") as! NSMutableArray //println(question) //println(arr) labelQuestion.text = question as String let indices : [Int] = [0,1,2,3] //let newSequence = shuffle(indices) let newSequence = indices.shuffle() var i : Int = 0 for(i = 0; i < newSequence.count; i++) { let index = newSequence[i] if(index == 0) { // we need to store the correct answer index currentCorrectAnswerIndex = i } let answer = arr.objectAtIndex(index) as! NSString switch(i) { case 0: buttonA.setTitle(answer as String, forState: UIControlState.Normal) break; case 1: buttonB.setTitle(answer as String, forState: UIControlState.Normal) break; case 2: buttonC.setTitle(answer as String, forState: UIControlState.Normal) break; case 3: buttonD.setTitle(answer as String, forState: UIControlState.Normal) break; default: break; } } Once a button is pressed, the app checks the answer chosen with the following code:
func checkAnswer( answerNumber : Int) { if(answerNumber == currentCorrectAnswerIndex) { // we have the correct answer labelFeedback.text = "Correct!" labelFeedback.textColor = UIColor.greenColor() score = score + 1 labelScore.text = "Score: \(score)" totalquestionsasked = totalquestionsasked + 1 labelTotalQuestionsAsked.text = "out of \(totalquestionsasked)" accumulatedquestionsasked = accumulatedquestionsasked + 1 percentagecorrect = score / totalquestionsasked SaveScore() SaveBestScore() // later we want to play a "correct" sound effect PlaySoundCorrect() } else { // we have the wrong answer labelFeedback.text = "Wrong!" labelFeedback.textColor = UIColor.blackColor() totalquestionsasked = totalquestionsasked + 1 labelTotalQuestionsAsked.text = "out of \(totalquestionsasked)" accumulatedquestionsasked = accumulatedquestionsasked + 1 SaveScore() SaveBestScore() // we want to play a "incorrect" sound effect PlaySoundWrong() } } So, what I'd like to do is change the labelQuestion text to present the correct answer if the user was wrong.
I've tried a few options as follows:
labelQuestion.text = "The correct answer was: \(currentCorrectAnswerIndex)" and
labelQuestion.text = "The correct answer was: \(currentCorrectAnswerIndex)" as string and
let answertext = String(currentCorrectAnswerIndex) labelQuestion.text = "The correct answer was: \(answertext)" All of these attempts have the same outcome - they provide the integer value corresponding to the button with the correct answer. For example, the user is presented with a message like:
The correct answer was: 2 instead of The correct answer was: Planet
I know I must be making a newbie mistake, but any direction would be much appreciated. I'm using the latest version of Xcode / Swift.
-26589849 0I finally found a solution so I thought I'd share.
To start with it turns out I was editing an old index file so any changes weren't taking affect. Once I realised this I noticed I was including cordova.js twice, once in the head and once below the body, this was causing the following error to occur
module org.apache.inappbrowser does not exist I removed this but still couldn't get the plugin to work, I used the CLI to add and remove the plugin several times but still no joy.
After hours of digging I realised I had old redundant plugin code in several different directories, I deleted all plugins from the following directories, along with the android.json file:
[my_project]/plugins [my_project]/platforms/android/src/org/apache/cordova/inappbrowser [my_project]/platforms/android/cordova/plugins/ [my_project]/platforms/android/assets/www/plugins Once I had removed all this I then added the plugin
cordova plugin add org.apache.cordova.inappbrowser This appears to have fixed everything for me so hopefully it'll help someone else!
-11870157 0 Knockout, ViewModel inside an other object and data-bindingI'm doing a javascript application for a game, the goal is to make a "build calculator" for a MMORPG. I want to synchronize the view with data already stocked in my application. I searched and tested different framework, and knockout-js appeared to be the best solution for me
Html:
<script> var simulatorTool = new SimulatorTool(); </script> <body> <p data-bind="text: test"> </p> <p data-bind="text: test2"> </p> </body> Javascript Tool:
function SimulatorTool() { meSim = this; this.config = new Config(); this.data = new Data(); this.stuff = new Stuff(); this.traits = new Traits(); this.view = new AppViewModel(); $(function(){ ko.applyBindings(meSim.view); }); ... functions } View Model:
function AppViewModel() { this.test = "Test!"; this.test2 = ko.computed(function() { return meSim.data.selectedData['profession'] }, this); } The problem is that i don't know how to bind the html to the view in an other object. I don't even know if it's possible. I'd like to do something like that
<p data-bind="simulatorTool.view, text: test"> </p> If not, how can i access to the data inside "SimulatorTool" if the view is separated from the application ?
-19751094 0 Valgrind out of memoryThis is the message I get when valgrind crashes and stops profiling my app:
==16317== ==16317== Valgrind's memory management: out of memory: ==16317== newSuperblock's request for 4194304 bytes failed. ==16317== 3013349376 bytes have already been allocated. ==16317== Valgrind cannot continue. Sorry. ==16317== ==16317== There are several possible reasons for this. ==16317== - You have some kind of memory limit in place. Look at the ==16317== output of 'ulimit -a'. Is there a limit on the size of ==16317== virtual memory or address space? ==16317== - You have run out of swap space. ==16317== - Valgrind has a bug. If you think this is the case or you are ==16317== not sure, please let us know and we'll try to fix it. ==16317== Please note that programs can take substantially more memory than ==16317== normal when running under Valgrind tools, eg. up to twice or ==16317== more, depending on the tool. On a 64-bit machine, Valgrind ==16317== should be able to make use of up 32GB memory. On a 32-bit ==16317== machine, Valgrind should be able to use all the memory available ==16317== to a single process, up to 4GB if that's how you have your ==16317== kernel configured. Most 32-bit Linux setups allow a maximum of ==16317== 3GB per process. ==16317== ==16317== Whatever the reason, Valgrind cannot continue. Sorry. I 've tried using huge swap files but it doesn't get better. The crash happens long before my swap file is nearly full. I 'm using Fedora 19. Does anyone know anything about this?I think I read something on the internet about how there may be a limit to the memory a single process can allocate.If this is the case ,where can I set it?At least give me a good alternative to valgrind people :P.
Thanks in advance
-11004959 0That article "Little bit about encoding" should help you with your problem.
-31948662 0You should be able to configure these mappings using either Data Annotations or the Fluent API. Here's a sample of how you might do it using the annotations:
[Table("Clients")] class Client { [Key] public int Client_Id {get;set;} public virtual ICollection<Note> Notes {get;set;} } [Table("Notes")] class Note { [Key] public int Note_Id {get;set;} public int Account_Id {get;set;} [ForeignKey("Account_Id")] public virtual Client Client {get;set;} }
-39287113 0 How to mock a Wicket component I am trying to unittest a wicket panel with the help of WicketTester and Spock/Mockito.
In this panel, a ModalWindow (confirmation dialog) is show in a good case scenario.
I want to validate this dialog will be shown, so I tried to mock the component, inject it into the panel and test if the show method is called. This won't work, as Wicket throws the following error:
java.lang.IllegalStateException: org.apache.wicket.Component has not been properly detached. Something in the hierarchy of X has not called super.onDetach() in the override of onDetach() method It's not suprising a mock can not call the onDetach method on it's super class.
I've tried stubbing the ModalWindow and using a spy to verify if the show method is called, but the implementation of that method has dependencies / external calls that are hard to mock.
Which way should I approach this problem? Or shouldn't I even try to make this kind of test work?
-34247799 0The columns in the output array from predict_proba are the probabilities of the different labels being predicted by your classifier. In your case, you've built a binary classifier, so the first column modl.predict_proba(X_test)[:,0] is the probability of the label being 0 and the second column modl.predict_proba(X_test)[:,1] is the probability of the label being 1.
I have a function my_function() which I need to run 10 times. Right now all 10 functions are running at the same time (asynchronously?). How can the next execution of the function occur after the previous one has finished?
my_function contains CURL calls and reading/writing to database tables. I wonder if any of these are running asynchronously
$repetitions = 10; for($i = 0; $i < $repetitions; $i++) { my_function($param); }
-26644824 0 Right off hand it looks like you're trying to reference the images and container in your JavaScript before the document is loaded. Try moving your script tag with code after (or right before) the closing </body> tag.
Because the document hasn't fully loaded, the DOM API in JavaScript can't yet access those elements if your JavaScript is in the head.
-526733 0 Maven plugin executing another pluginI'm trying to create a new plugin to package my latest project. I'm trying to have this plugin depend on the maven-dependency-plugin to copy all my projects dependencies.
I've added this dependency to my plugin's pom, but I can't get it to execute.
I have this annotation in my plugins main Mojo:
@execute goal="org.apache.maven.plugins:maven-dependency-plugin:copy" I've tried a few other names for the goal, like dependency:copy and just copy but they all end with a message saying that the required goal was not found in my plugin. What am I doing wrong?
Secondary to this is where to I provide configuration info for the dependency plugin?
-27240585 0 Private namespaces for library sub-modules using prototypeI'm working on a large JavaScript UI module, think about something in the dimension of iScroll. For keeping the thing sane, I split the library up into several logical sub-modules (like: touch interaction, DOM interaction, etc.) that communicate with each other using a simple pubsub system.
Each of these sub-modules has it's own namespace I use for storing variables. To enable several instances of the library running at the same time, the constructor includes some logic to copy every namespace that has been assigned to a 'toCopy' object directly into every new instance.
The basic structure looks something like this:
// constructor function Constructor() { for (var key in this.toCopy) { // create a deep copy and store it inside the instance this[key] = utils.copyObj(this.toCopy[key]); } } Constructor.prototype.toCopy = {} // sub-module #1 Constructor.prototype.toCopy._module1Namespace = {} Constructor.prototype._privateFn = function() { /** do stuff within this._module1Namespace or send events */ } Constructor.prototype._privateFn = function() { /** do stuff within this._module1Namespace or send events */ } // sub-module #2 Constructor.prototype.toCopy._module2Namespace = {} Constructor.prototype._privateFn = function() { /** do stuff with this._module2Namespace or send events */ } Constructor.prototype._privateFn = function() { /** do stuff with this._module2Namespace or send events */ } My problem: I really dislike having to expose the namespace of each sub-module to the rest of the library. Although I'm disciplined enough not to access the namespace of sub-module #1 within a function of sub-module #2, I want it to be technically impossible.
However, as several instances of the UI library have to run at the same time, I cannot put every sub-module inside a closure and define a private namespace inside this closure. This would result in every instance of the library accessing the same sub-module closure and therefore the same namespace.
Also, putting everything inside the constructor instead of into the prototype would create a new set of functions for every new instance, which somehow contradicts the idea of a good library.
My research hasn't brought up any useful patterns for this problem so far, I'm thankful for all suggestions.
-2430963 0I ended up having to set the innerHTML of the select.
I came up with the following extension method that has a special routine for IE6:
$.fn.setDropDownValue = function(valueToSet) { if ((!this[0].options) || (this[0].options.length == 0)) return; if ($.browser.msie && $.browser.version == 6.0) { var open = '<OPTION value=\''; var html = ''; for (var i = 0; i < this[0].options.length; i++) { var opt = $(this[0].options[i]); html += open + $(opt).val() + '\''; if (opt.val() == valueToSet) { html += ' selected'; } html += '>' + opt.html() + '</OPTION>'; } $(this).html(html); } else { this.val(valueToSet); } };
-22882564 0 Go/Mgo -> []byte in MongoDB, slice of unaddressable array I'm getting a:
reflect.Value.Slice: slice of unaddressable array
Error when I'm trying to add a sha256 hash to a mongoDB with mgo. Other []bytes work fine.
hash := sha256.Sum256(data) err := c.Col.Insert(bson.M{"id": hash}) Any idea what the problem might be? I know I could encode the hash as a string but that should not be necessary.
-20375665 0 How to run a loop with a specific interval in casperjs?I want to automate clicking a button with id='vote' 3 times with an interval of say 5 seconds with casperjs, for that I have written the code below
var casper = require('casper').create(); casper.start('http://www.mysite.com/mypage'); casper.repeat(3, function() { this.click('#vote'); }); casper.then(function() { console.log('clicked vote ,and voted successfully , and curernt url is ' + this.getCurrentUrl()); }); casper.run(); But this only working once, what I want to do is to repeat the loop 3 times with a specific interval, since this is a JavaScript ajax post on clicking the vote button and it updates the database, is it doing all 3 clicks at once? What do I have to do to avoid that, and update the database 3 times?
-20244172 0The problem was in drawer_list_item.xml. In Android 2.x the style attributes starting with "?android:attr/" were not available. Removing them fixed the problem.
-16825149 1 Can't get "retry" to work in CeleryGiven a file myapp.py
from celery import Celery celery = Celery("myapp") celery.config_from_object("celeryconfig") @celery.task(default_retry_delay=5 * 60, max_retries=12) def add(a, b): with open("try.txt", "a") as f: f.write("A trial = {}!\n".format(a + b)) raise add.retry([a, b]) Configured with a celeryconfig.py
CELERY_IMPORTS = ["myapp"] BROKER_URL = "amqp://" CELERY_RESULT_BACKEND = "amqp" I call in the directory that have both files:
$ celeryd -E And then
$ python -c "import myapp; myapp.add.delay(2, 5)" or
$ celery call myapp.add --args="[2, 5]" So the try.txt is created with
A trial = 7! only once. That means, the retry was ignored.
I tried many other things:
print (like the PING example) and loggingException is raised, raising or returning the retry(), changing the "throw" parameter to True/False/not specified.celery flower (in which the "broker" link shows nothing)But none happened to work =/
My celery report output:
software -> celery:3.0.19 (Chiastic Slide) kombu:2.5.10 py:2.7.3 billiard:2.7.3.28 py-amqp:N/A platform -> system:Linux arch:64bit, ELF imp:CPython loader -> celery.loaders.default.Loader settings -> transport:amqp results:amqp Is there anything wrong above? What I need to do to make the retry() method work?
-13486351 0[Solved] Just update Java for Windows plugin for your browser (Firefox, Chrome...) Go to Java site and update Java Firefox plugin.
One more solution is install and use SQLyog;
-32629979 0 How to cancel Picasso requests after fragment transitions in androidI have a fragment with a gridview, which loads say 20 images simultaneously using an adapter. I want to make sure that unfinished Picasso requests terminate gracefully when fragment has disappeared/disposed.
Question
So it turned out, that there was something wrong with the connection. It was created with that code:
void PostgresqlDatabase::pgMDBconstruct(std::string host, std::string port, std::string user, std::string password, std::string dbname ) { std::string conn_info = "host=" + host + " port=" + port + " user=" + user + " password=" + password + " dbname=" + dbname; connection_= PQconnectdb(conn_info.c_str()); if (PQstatus(connection_)!=CONNECTION_OK) { ROS_ERROR("Database connection failed with error message: %s", PQerrorMessage(connection_)); } } With host=192.168.10.100, port=5432, user=turtlebot, password= , dbname=rosdb.
But an empty username doesn't satisfy the usage of PQconnectdb, which, for some parsing-reason, caused it to login to the database "turtlebot". That database unfortunately existed on my server. And there it - of course - didn't get any notifications sent out in the "rosdb"-database and had a good connection.
What an, for me, awkward and unlucky behaviour.
-15829271 0You can easy add it as static param to url manager rules. I recommend using urls in form /en/controller/action etc, so first parameter is always language. I'm using this approach for long time and works like a charm.
For details check this answer: http://stackoverflow.com/a/4625710/133408
-37057778 0 Passing select value from SQL database with phpI am attempting to use a select form that has fields populated from an SQL database. There is a table of stores in the database and I used this method to get those distinct fields into the select tool.
echo '<select name="StoreName" />'."\n"; while ($row = mysqli_fetch_assoc($distinctResult)){ echo '<option value="'.$row["StoreID"].'">'; echo $row["StoreName"]; echo '</option>'."\n"; }; echo '</select>'."\n"; The correct store names show up on the select tool but when I submit the form data, the value of the form doesn't get passed properly. Here in the initial page:
<?php require_once 'login.php'; $connection = mysqli_connect( $db_hostname, $db_username, $db_password, $db_database); if(mysqli_connect_error()){ die("Database Connection Failed: " . mysqli_connect_error() . " (" . mysqli_connect_errno() . ")" ); }; $query = "SELECT * from PURCHASE"; //echo $query; $result = mysqli_query($connection,$query); if(!$result) { die("Database Query Failed!"); }; $distinct = "SELECT DISTINCT StoreName FROM PURCHASE"; $distinctResult = mysqli_query($connection,$distinct); if(!$result) { die("Database Query Failed!"); }; echo '<title>Output 1</title>'; echo '</head>'; echo '<body>'; echo '<h1>Required Output 1</h1>'; echo '<h2>Transaction Search</h2>'; echo '<form action="output1out.php" method="get">'; echo 'Search Store:<br/>'; echo '<br/>'; echo '<select name="StoreName" />'."\n"; while ($row = mysqli_fetch_assoc($distinctResult)){ echo '<option value="'.$row["StoreID"].'">'; echo $row["StoreName"]; echo '</option>'."\n"; }; echo '</select>'."\n"; echo '<input name="Add Merchant" type="submit" value="Search">'; echo '</form>'; mysqli_free_result($result); mysqli_close($connection); ?> And this is the output page:
<?php $transaction = $_REQUEST["StoreName"]; require_once 'login.php'; $connection = mysqli_connect( $db_hostname, $db_username, $db_password, $db_database); $sql = "SELECT * FROM PURCHASE WHERE StoreName LIKE '%".$transaction."%'"; $result = $connection->query($sql); ?> Purchases Made From <?php echo $transaction ?> <table border="2" style="width:100%"> <tr> <th width="15%">Item Name</th> <th width="15%">Item Price</th> <th width="15%">Purchase Time</th> <th width="15%">Purchase Date</th> <th width="15%">Category</th> <th width="15%">Rating</th> </tr> </table> <?php if($result->num_rows > 0){ // output data of each row while($rows = $result->fetch_assoc()){ ?> <table border="2" style="width:100%"> <tr> <td width="15%"><?php echo $rows['ItemName']; ?></td> <td width="15%"><?php echo $rows['ItemPrice']; ?></td> <td width="15%"><?php echo $rows['PurchaseTime']; ?></td> <td width="15%"><?php echo $rows['PurchaseDate']; ?></td> <td width="15%"><?php echo $rows['Category']; ?></td> <td width="15%"><?php echo $rows['Rating']; ?></td> </tr> <?php } } ?> I am calling the select name StoreName in the output page but it is not passing the value from the drop down. I need to run a query with that term on the second page so I can pull the relevant data for it. If anyone can see what I'm doing wrong, please advise. Thank you.
Maybe you should take a look at CompletionService
It is designed to combine executor and a queue functionality in one. Tasks which completed execution will be available from the completions service via
completionServiceInstance.take() You can then again use another executor for 3. i.e. fill DB with the results, which you will feed with the results taken from the completionServiceInstance.
-29551594 0As stated in the iOS 8.3 API Diffs in the MapKit module, the setCoordinate method was removed:
Removed MKAnnotation.setCoordinate(CLLocationCoordinate2D)
Fortunately, you must now use the simpler assignment syntax (which was already available in previous versions of Swift and the same could be done in Objective-C):
annotation.coordinate = location
-11812394 0 Applescript- combine multiple IF statments and an abbreviation for home folders I'm trying to make an applescript to make a backup of some files to dropbox. My question was if it was possible to combine multiple IF statmens in my script and if it was possible to make a shorten SET name TO path, like Macintosh HD:Users:svkrzn:Dropbox to ~:Dropbox.
Here is my script:
set destination to "Macintosh HD:Users:svkrzn:Dropbox:Backup" set safari to "Macintosh HD:Users:svkrzn:Library:Safari:Bookmarks.plist" set safariplist to "Macintosh HD:Users:svkrzn:Dropbox:Backup:Safari_Bookmarks.plist" set things to "Macintosh HD:Users:svkrzn:Library:Application Support:Cultured Code:Things:Database.xml" set thingsxml to "Macintosh HD:Users:svkrzn:Dropbox:Backup:THINGS_Database.xml" tell application "Finder" try set S1 to duplicate file safari to folder destination with replacing set T1 to duplicate file things to folder destination with replacing if exists file safariplist then display dialog "It exists." delete file safariplist end if if exists file thingsxml then display dialog "It exists." delete file thingsxml end if set name of S1 to "Safari_Bookmarks.plist" set name of T1 to "THINGS_Database.xml" on error display dialog "Oops, a problem occurred duplicating the file." end try end tell
-966691 0 You wouldn't retain ClassA in ClassB, because ClassA already owns ClassB and it's assumed that when ClassA is deallocated, it will take care of cleaning up any references in ClassB.
If you followed the "normal" rules of ownership and retained ClassA when setting the delegate method in ClassB, you'd end up with a retain loop where neither objects would ever be deallocated. Instead, you should be using a weak reference exactly like you are.
-14783690 0Instead of immediately echoing out the responses, try stacking them an array and then outputting the JSON.
<?php //...... $result = arrray(); $result[] = $this->alerts->generate(); $result[] = $this->alerts2->generate(); echo json_encode($result);
-36620854 0 I would use a lookup transformation No need for staging - no need to write SQL code - it's the way SSIS was meant to be!
-28505021 0 Nservicebus failing to start on localsystemI recently upgraded to v4.6 of nservicebus and when I am trying to start locally using services.msc, it is throwing error "services on local system started and stopped". Can't make out what is missing. I can use command line to start the nservicebus using like this:
NServiceBus.Host.Exe NServiceBus.Master NService.Integration Can someone please help?
-4443321 0I would check out the fantastic Rome library: http://wiki.java.net/bin/view/Javawsxml/Rome
-33318146 0Make change in your gruntfile.js
htmlmin. files.src: ['.html', '{,/}*.html']and
copy.dist.files.src:[ '.{ico,png,txt}', '.htaccess', '.html', '{,/}.html', 'images/{,/}.{webp}', 'styles/fonts/{,/}.*' ]
In this way it is working for me.
-25333120 0There's 2 ways you could solve this that don't require your application code to be aware of your container.
The first method, instead replacing the registered instance of UserModel with a new instance, you'd just update the registered instances properties to the new values. This is probably the simplest, if your type is mutable and not overly complex.
This second method would be appropriate if updating the original UserModel instance is undesirable or impossible. Basically, just add a layer of indirection:
// ------------------------- // add this class: public class Changeable<T> { public T Value { get; set; } } // ------------------------- // set up registrations like so: // register the default value like so builder.RegisterInstance( new Changeable<UserModel> { Value = new UserModel { Id = Migration001.GuestUserId, Email = Migration001.GuestEmail, PasswordHash = Migration001.GuestPassword } }); // register UserModel directly, which can be used by all the classes that don't // need to change the instance builder.Register(c => c.Resolve<Changeable<UserModel>>().Value); Now your service classes can take a constructor parameter of either Changeable<UserModel> or just UserModel depending on whether they need to be able to change the instance or not, with no more direct reference to the container.
In your env file, the value should not have any single or double quotes.
-24145737 0Something like this?

<Grid HorizontalAlignment="Center" VerticalAlignment="Center"> <Grid.RowDefinitions> <RowDefinition Height="25"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Grid.Resources> <Style TargetType="Rectangle"> <Setter Property="Stroke" Value="Black"/> <Setter Property="StrokeThickness" Value="1"/> <Setter Property="Height" Value="11"/> <Setter Property="Width" Value="11"/> <!-- For hittestvisibility --> <Setter Property="Fill" Value="Transparent"/> </Style> </Grid.Resources> <Line X1="0" Y1="1" X2="0" Y2="0" Stretch="Fill" Stroke="Black" /> <Rectangle VerticalAlignment="Top" HorizontalAlignment="Center"/> <Grid Grid.Row="1" Height="200" Width="200" Margin="-5"> <Rectangle Margin="5" Height="Auto" Width="Auto" Fill="{x:Null}"/> <Rectangle VerticalAlignment="Top" HorizontalAlignment="Left"/> <Rectangle VerticalAlignment="Top" HorizontalAlignment="Center"/> <Rectangle VerticalAlignment="Top" HorizontalAlignment="Right"/> <Rectangle VerticalAlignment="Center" HorizontalAlignment="Left"/> <Rectangle VerticalAlignment="Center" HorizontalAlignment="Right"/> <Rectangle VerticalAlignment="Bottom" HorizontalAlignment="Left"/> <Rectangle VerticalAlignment="Bottom" HorizontalAlignment="Center"/> <Rectangle VerticalAlignment="Bottom" HorizontalAlignment="Right"/> <!-- The Content --> <Rectangle Width="Auto" Height="Auto" Margin="20" Fill="Green"/> <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="Content"/> </Grid> </Grid> The terminology is Bounding Box
-27816094 0sawa's answer is ok, and also you can use a method like this to dynamically create logger for each class.
However, I prefer not to get all classes under a module. In able to create logger for every single class, you can do things as follow.
module Kernel ####### private ####### def logger Log4r::Logger[logger_name] end def logger_name clazz = self.class unless clazz.respond_to? :logger_name name = clazz.module_eval 'self.name' clazz.define_singleton_method(:logger_name) { name } end clazz.logger_name end end module A module B class C def hello logger.debug logger_name end end end end A::B::C.new.hello For classes within a specific module you can write a filter in the logger_name method, for example:
module Kernel ####### private ####### def logger Log4r::Logger[logger_name] end def logger_name clazz = self.class unless clazz.respond_to? :logger_name name = clazz.module_eval 'self.name' name = 'root' unless name.start_with?('A::B') clazz.define_singleton_method(:logger_name) { name } end clazz.logger_name end end module A module B class C def hello logger.debug logger_name end class << self def hello logger.debug logger_name end end end end class D def hello logger.debug logger_name end end end A::B::C.new.hello # A::B::C A::B::C.hello # A::B::C A::D.new.hello # root And also, you can cache the logger:
def logger _logger = Log4r::Logger[logger_name] self.class.send(:define_method, :logger) { _logger } self.class.define_singleton_method(:logger) { _logger } return _logger end Hope it helps.
-3429683 0I'd would dinamically set the limit by constantly checking the average load/cpu usage/query time of the database... That way when there are a few users online they can do their work faster. You could set a "maximum" like twitter and if total-load > max-load-you-want maximum=150% and so on...
On one of the service-based sites i've applied this method it actually removed 60% of the spikes after i told the users about the change...
Thanks for your question. It is possible to process multiple refunds (or rebates as we refer to them) against a single transaction. This isn't setup by default on your account, however. You can email your account manager and request that multiple rebates be enabled.
Best,
Seán
Channel Support
Realex Payments
-7438268 0 elasticsearch boosting slowing querythis is a very novice question but I'm trying to understand how boosting certain elements in a document works.
I started with this query,
{ "from": 0, "size": 6, "fields": [ "_id" ], "sort": { "_score": "desc", "vendor.name.stored": "asc", "item_name.stored": "asc" }, "query": { "filtered": { "query": { "query_string": { "fields": [ "_all" ], "query": "Calprotectin", "default_operator": "AND" } }, "filter": { "and": [ { "query": { "query_string": { "fields": [ "targeted_countries" ], "query": "All US" } } } ] } } } } then i needed to boost certain elements in the document more than the others so I did this
{ "from": 0, "size": 60, "fields": [ "_id" ], "sort": { "_score": "desc", "vendor.name.stored": "asc", "item_name.stored": "asc" }, "query": { "filtered": { "query": { "query_string": { "fields": [ "item_name^4", "vendor^4", "id_plus_name", "category_name^3", "targeted_countries", "vendor_search_name^4", "AdditionalProductInformation^0.5", "AskAScientist^0.5", "BuyNowURL^0.5", "Concentration^0.5", "ProductLine^0.5", "Quantity^0.5", "URL^0.5", "Activity^1", "Form^1", "Immunogen^1", "Isotype^1", "Keywords^1", "Matrix^1", "MolecularWeight^1", "PoreSize^1", "Purity^1", "References^1", "RegulatoryStatus^1", "Specifications/Features^1", "Speed^1", "Target/MoleculeDescriptor^1", "Time^1", "Description^2", "Domain/Region/Terminus^2", "Method^2", "NCBIGeneAliases^2", "Primary/Secondary^2", "Source/ExpressionSystem^2", "Target/MoleculeSynonym^2", "Applications^3", "Category^3", "Conjugate/Tag/Label^3", "Detection^3", "GeneName^3", "Host^3", "ModificationType^3", "Modifications^3", "MoleculeName^3", "Reactivity^3", "Species^3", "Target^3", "Type^3", "AccessionNumber^4", "Brand/Trademark^4", "CatalogNumber^4", "Clone^4", "entrezGeneID^4", "GeneSymbol^4", "OriginalItemName^4", "Sequence^4", "SwissProtID^4", "option.AntibodyProducts^4", "option.AntibodyRanges&Modifications^1", "option.Applications^4", "option.Conjugate^3", "option.GeneID^4", "option.HostSpecies^3", "option.Isotype^3", "option.Primary/Secondary^2", "option.Reactivity^4", "option.Search^1", "option.TargetName^1", "option.Type^4" ], "query": "Calprotectin", "default_operator": "AND" } }, "filter": { "and": [ { "query": { "query_string": { "fields": [ "targeted_countries" ], "query": "All US" } } } ] } } } } the query slowed down considerably, am I doing this correctly? Is there a way to speed it up? I'm currently in the process of doing the boosting when I index the document, but using it in the query that way is best for the way my application runs. Any help is much appreciated
-29489857 0As far as I know you can't build your custom transitions and use them like normal WinRT Transitions, that is, inside a TransitionCollection.
<ListView.Transitions> <TransitionCollection> <myTransitions:PotatoeTransition/> </TransitionCollection> </ListView.Transitions> You can't do the above as far as I know. (ignore the fact that I exemplified with a ListView, it applies to everything, I think)
You'll probably have to use a Storyboard that animates both the RenderTransform (TranslateTransform) and the Opacity to achieve your objective.
I think you can still create a Behavior though if you want to make it more reusable.
I need to give read/write access for a user to an exactly one repository.
Why this doesn't work?
[groups] dev = dvolosnykh,sam [/ukk] ukk = rw [/] @dev = rw Why should I add this?
[/] @dev = rw * = r # read access for everyone. Why? I'm using dav_svn, apache2, Linux Ubuntu server 11.04
My dav_svn.conf:
<Location /svn> DAV svn SVNParentPath /var/svn SVNListParentPath On AuthType Basic AuthName "Subversion Repository" AuthUserFile /etc/apache2/dav_svn.passwd AuthzSVNAccessFile /etc/apache2/dav_svn.authz Require valid-user </Location>
-14151028 0 I know you didn't ask this, and I'm not sure about the problem you are solving, but your code where you manipulate the size of the FormItems outside of the standard lifecycle functions kind of smells funny. Just a suggestion.
-9825691 0yuo can add a screen for enter a coupons.
and the user can go in there and insrert his code and if it is correct you can give him whatever you want.
Try changing this line:
RewriteCond %{QUERY_STRING} ^_escaped_fragment_=/?(.*)$ to
RewriteCond %{QUERY_STRING} ^_escaped_fragment_=/?([^/]+(?:/[^/]+|)) So the regex will only attempt to capture as many as 2 virtual paths.
-19267010 0If you want a really real-time(around 200ms) response for your search application, for both the first time search query response and further suggested search response, Hadoop is not a good choice, not even Hive, HBase, or even Impala (or Apache Drill, Google Dremel like system).
Hadoop is a batch processing system which is good for write once, read multiple times use cases. And the strength of it is good at scalability and I/O throuput. The trend I saw is that many organizations are using that as a data warehouse for offline data mining and BI analysis purpose as a replacement for data warehosue based on relational databases.
Hive and HBase all provides extra features on top of Hadoop, but neither of those could possibly reach 200ms real time for average complex query workload.
Check the high level view of how 'real-time' each possible solution can really reach, on Apache Drill homepage. CloudEra Impala, or Apache Drill, which borrows the idea from Google Dremel, have the intention to enhance the query speed on top of Hadoop by doing query optimization, column based storage, massive parallelism of I/O. I believe these 2 are still in early stage to achieve the goals they claim. Some initial performance benchmarking result of Impala I found.
If you decide to go with Hadoop or related solution stack, there are possible ways to load data from MySQL to Hadoop using Sqoop or other customized data load applications leveraging Hadoop Distributed File System API. But if you will have new data coming into MySQL time to time, then you need to schedule a job to run periodically to do delta load from MySQL to Hadoop.
On the other hand, the workload to build a Hadoop cluster and find or build suitable data loading tool from MySQL to Hadoop might be a huge workload. Also you need to find a suitable extra layer for runtime data access and build code around that, no mater Impala or other things. To solve your own problem, it's probably better to build your own customized solution, like using in memory cache for hot records with the meta data in your database, along with some index mechanism to quickly locate the data you need for suggested search query calculation. If the memory on one machine cannot hold enough records, a memory cache grid or cluster component comes in handy like Memcached or Reddis, EhCache, etc.
-2244274 0Transliterate any relevant punctuation to words. C++ -> Cplusplus, C# -> Csharp, PL/SQL -> PLslashSQL
-40665526 0Not easily, the default size of a JLabel, JTextArea etc. is delegated to the "look and feel", this determines the size using the font metrics of the font, the size and the text.
Thefore bigger font, bigger buttons.
I'd advise you to just accept this, and use a layout manager that deals with the nicely...
i.e. don't assume precise layout, instead use something grid-based with enough free-space so that font size can vary.
If you're still desperate to do this you could override the preferred size of the controls with the following, although this pre-supposes you're using a layout manager that respects these hints.
public static void main(String [] args) { JFrame frame = new JFrame(); JTextField small = new JTextField("small"); JTextField big = new JTextField("big"); big.setFont(big.getFont().deriveFont(Font.BOLD, 40)); big.setPreferredSize(new Dimension(123, 20)); big.setMaximumSize(new Dimension(123, 20)); frame.setLayout(new FlowLayout()); frame.add(small); frame.add(big); frame.setVisible(true); }
-12338176 0 It is not possible.
I refer to the following part of Matlab documentation:
Valid Names
A valid variable name starts with a letter, followed by letters, digits, or underscores. MATLAB is case sensitive, so A and a are not the same variable. The maximum length of a variable name is the value that the namelengthmax command returns.
Letter is defined as ANSI character between a-z and A-Z. For example, the following hebrew letter Aleph returns false:
isletter('א') By the way, you can always check whether your variable name is fine by using genvarname.
genvarname('א') ans = x0x1A
-151059 0 you're telling the system that whatever work would have been done in the finalizer has already been done, so the finalizer doesn't need to be called. From the .NET docs:
Objects that implement the IDisposable interface can call this method from the IDisposable.Dispose method to prevent the garbage collector from calling Object.Finalize on an object that does not require it.
In general, most any Dispose() method should be able to call GC.SupressFinalize(), because it should clean up everything that would be cleand up in the finalizer.
SupressFinalize is just something that provides an optimization that allows the system to not bother queing the object to the finalizer thread. A properly written Dispose()/finalizer should work properly with or without a call to GC.SupressFinalize().
-24659922 0 Can't boot into OSXI have two HDs in my Macbook Pro 15 in late 2009. I installed bootcamp and updated to Mavericks. My Windows partition in running Win7 Ultimate. I set the the boot disk in OSX to be my windows partition and now my laptop doesn't recognize me holding down the option key to choose which partition to boot. When windows boots i have to start the on screen keyboard and then close it for my keyboard presses to be recognized. The quote key causes the option and control keys to stick and delete doesn't work at all. I would use the bootcamp panel to switch back but it didn't install. i would really appreciate any help because i'm behind in my web dev projects and don't want to reinstall OSX because i'll lose my data, plus i took out the disc drive for my other HD.
-15594360 0On a quick glance, I see a couple of instances of:
IF NEW.id_club = NULL ... There may be more problems, I stopped looking there.
Nothing is ever the same as NULL. Use instead:
IF NEW.id_club IS NULL ... Make sure you understand the nature of a NULL value, before you go on writing complex triggers. Basics first. Start in the manual here.
I'm having some trouble with data-attributes, I can't get anything to work for some reason so I must be doing something wrong:
Set:
$('#element').data('data1', '1'); //Actually in my case the data is been added manually Does that make a difference?
Get:
$('#element').data('data1'); Select:
$('#element[data1 = 1]') None of this works for me, am I making this up or how is it?
-22981546 0library(data.table) library(reshape2) library(lubridate) df = fread("/storage/Downloads/Watertable_fluctuations_All_Original.txt", skip = 1, header = T) # dropbox file df = df[, date := dmy(date)] dfm = melt(df, id.vars = "date", value.name = "water.level") wl.threshold = -0.22 dfm[water.level < wl.threshold,.N, keyby = variable] # count per measuring station # bonus library(openair) timePlot(dfm[variable == "Yel342(2010)"], pollutant = "water.level", smooth = T, ref.y = wl.threshold) 
I'm trying to send messages every 15 minutes. I have 20 messages, and I want each message to be sent about 15 minutes apart, i.e. message 3 is sent 15 minutes after message 2, message 4 15 minutes after message 3. Right now I'm just trying to stagger the contab jobs, but is there a more efficient/elegant solution? Thanks for the help!
14,29,44,59 10-21 * * * wget -q http://site/message2.php 13,28,43,58 10-21 * * * wget -q http://site/message3.php 12,27,43,57 10-21 * * * wget -q http://site/message4.php 11,26,42,56 10-21 * * * wget -q http://site/message5.php 10,25,41,55 10-21 * * * wget -q http://site/message6.php 9,24,40,55 10-21 * * * wget -q http://site/message7.php 8,23,39,54 10-21 * * * wget -q http://site/message8.php 7,22,38,53 10-21 * * * wget -q http://site/message9.php 6,21,37,52 10-21 * * * wget -q http://site/message10.php 5,20,36,51 10-21 * * * wget -q http://site/message11.php 4,19,35,50 10-21 * * * wget -q http://site/message12.php 3,18,34,49 10-21 * * * wget -q http://site/message13.php 2,17,33,48 10-21 * * * wget -q http://site/message14.php 1,16,33,47 10-21 * * * wget -q http://site/message15.php 0,15,32,46 10-21 * * * wget -q http://site/message16.php 14,31,45,59 10-21 * * * wget -q http://site/message17.php 13,30,44,58 10-21 * * * wget -q http://site/message18.php 12,28,43,57 10-21 * * * wget -q http://site/message19.php 11,27,42,56 10-21 * * * wget -q http://site/message20.php
-36238231 0 How to run supervised LDA I did topic modeling on my documents using topicmodels package. Now, I want to do supervised LDA. I used this function to convert my topicmodels output to lda package output. But, now I don't know how to run slda and interpret the results.
Here's the code I have so far:
# A function that converts topicmodels output to lda output topicmodels_json_ldavis <- function(fitted, corpus, doc_term){ # Required packages library(topicmodels) library(dplyr) library(stringi) library(tm) library(LDAvis) # Find required quantities phi <- posterior(fitted)$terms %>% as.matrix theta <- posterior(fitted)$topics %>% as.matrix vocab <- colnames(phi) doc_length <- vector() for (i in 1:length(corpus)) { temp <- paste(corpus[[i]]$content, collapse = ' ') doc_length <- c(doc_length, stri_count(temp, regex = '\\S+')) } temp_frequency <- inspect(doc_term) freq_matrix <- data.frame(ST = colnames(temp_frequency), Freq = colSums(temp_frequency)) rm(temp_frequency) # Convert to json json_lda <- LDAvis::createJSON(phi = phi, theta = theta, vocab = vocab, doc.length = doc_length, term.frequency = freq_matrix$Freq) return(json_lda) } ## end of function docs <- tm_map(docs, removePunctuation) docs <- tm_map(docs, removeNumbers) docs <- tm_map(docs, content_transformer(tolower)) docs <- tm_map(docs, removeWords, stopwords("english")) library(SnowballC) docs <- tm_map(docs, stemDocument) docs <- tm_map(docs, stripWhitespace) tfm <- DocumentTermMatrix(docs) # remove empty documents library(slam) tfm = tfm[row_sums(tfm)>0,] # Use topicmodels package to conduct LDA analysis. library(topicmodels) results5 <- LDA(tfm, k = 5, method = "Gibbs") ### converting topicmodels output to lda output ldaoutput = topicmodels_json_ldavis(lda,corpus, dtm) Now I don't know how to run supervised lda and interpret it.
I really appreciate your help.
-37583068 0Include your card_view after AppBarLayout and setheight for AppBarLayout instead ImageView and make ImageView height match_parent
You can do this using scripting variable and using the -v option of SQLCMD utility. A small example from MSDN Documentation
Consider that the script file name is testscript.sql, Col1 is a scripting variable; your SQL script look like
USE test; SELECT x.$(Col1) FROM Student x WHERE marks < 5; You can then specify the name of the column that you want returned by using the -v option like
sqlcmd -v Col1 = "FirstName" -i c:\testscript.sql Which will resemble to below query
SELECT x.FirstName FROM Student x WHERE marks < 5; EDIT:
If you just want to capture the output from your script file then you can use -o parameter and specify a outfile like
sqlcmd -v Col1 = "FirstName" -i c:\testscript.sql -o output.txt
-1336851 0 From python docs:
Advanced usage: you can derive subclasses of Template to customize the placeholder syntax, delimiter character, or the entire regular expression used to parse template strings. To do this, you can override these class attributes:
delimiter – This is the literal string describing a placeholder introducing delimiter. The default value $. Note that this should not be a regular expression, as the implementation will call re.escape() on this string as needed.
idpattern – This is the regular expression describing the pattern for non-braced placeholders (the braces will be added automatically as appropriate). The default value is the regular expression [_a-z][_a-z0-9]*.
Example:
from string import Template class MyTemplate(Template): delimiter = '#' idpattern = r'[a-z][_a-z0-9]*' >>> s = MyTemplate('#who likes $what') >>> s.substitute(who='tim', what='kung pao') 'tim likes $what' In python 3:
New in version 3.2.
Alternatively, you can provide the entire regular expression pattern by overriding the class attribute pattern. If you do this, the value must be a regular expression object with four named capturing groups. The capturing groups correspond to the rules given above, along with the invalid placeholder rule:
- escaped – This group matches the escape sequence, e.g. $$, in the default pattern.
- named – This group matches the unbraced placeholder name; it should not include the delimiter in capturing group.
- braced – This group matches the brace enclosed placeholder name; it should not include either the delimiter or braces in the capturing group.
- invalid – This group matches any other delimiter pattern (usually a single delimiter), and it should appear last in the regular expression.
Example:
from string import Template import re class TemplateClone(Template): delimiter = '$' pattern = r''' \$(?: (?P<escaped>\$) | # Escape sequence of two delimiters (?P<named>[_a-z][_a-z0-9]*) | # delimiter and a Python identifier {(?P<braced>[_a-z][_a-z0-9]*)} | # delimiter and a braced identifier (?P<invalid>) # Other ill-formed delimiter exprs ) ''' class TemplateAlternative(Template): delimiter = '[-' pattern = r''' \[-(?: (?P<escaped>-) | # Expression [-- will become [- (?P<named>[^\[\]\n-]+)-\] | # -, [, ], and \n can't be used in names \b\B(?P<braced>) | # Braced names disabled (?P<invalid>) # ) ''' >>> t = TemplateClone("$hi sir") >>> t.substitute({"hi": "hello"}) 'hello sir' >>> ta = TemplateAlternative("[-hi-] sir") >>> ta.substitute({"hi": "have a nice day"}) 'have a nice day sir' >>> ta = TemplateAlternative("[--[-hi-]-]") >>> ta.substitute({"hi": "have a nice day"}) '[-have a nice day-]' Apparently it is also possible to just omit any of the regex groups escaped, named, braced or invalid to disable it.
I think this tutorial will help you a lot to access Windows IoT device via PowerShell:
https://www.hackster.io/AnuragVasanwala/windows-10-iot-core-setting-startup-app-887ed0
This article reveals how to set specific Universal App as startup app but also covers the basic aspects of PowerShell, how to connect to it and some known issue(s).
-25186839 0Well you cannot actually get session time with an AJAX request as the request it self will also reset the session timeout time. What you can do is get it when you are rendering the page in a js function and start a counter with setTimeout when and show your message pop when less then 30 seconds left.
If you are using OS X hardware with an NVIDIA GPU, both CULA and Jacket includes SVD routines, and both are available for OS X (as far as I know). But I am not aware of anything similar for OpenCL.
-14858239 0The error above occurs when you return certain objects (XML, Socket) from a function call, but the return values does not get assigned anywhere.
function test() { var xml = new XML('<test />'); return xml; } test(); The above will cause an error. To get around it you have to assign the return value somewhere.
var result = test(); Try to put all collect all function calls result. I am not sure which one causes the error.
var reply = ""; var conn = new Socket; // access Adobe’s home page if (conn.open ("www.adobe.com:80")) { // send a HTTP GET request var result = conn.write ("GET /index.html HTTP/1.0\n\n"); // and read the server’s reply reply = conn.read(999999); var close = conn.close(); }
-30642633 0 How to sort Arraylist consisting of pojo class in java I have POJO class Student like this
class Student { private int score; private String FirstName; //Getters and setters ................. } I am creating ArrayList like this
public static void main(String[] args) { List<Student> al_students= new ArrayList<Student>(); Student s1= new Student(); s1.setScore(90); s1.setFirstName("abc"); al_students.add(s1); Student s2= new Student(); s2.setScore(95); s2.setFirstName("def"); al_students.add(s2); Student s3= new Student(); s3.setScore(85); s3.setFirstName("xyz"); al_students.add(s3); } Now I want to sort it based on scores in descending order i.e
output
1)def 95 2)abc 90 3)xyz 85
-30666492 0 Use a delegated event handler :
$('#table').on('click', '.pay-btn', function(e) { dataTables inject and remove table rows to the DOM in order to show pages. Thats why your event handler not is working except from page #1.
NB: Dont know what your <table> id is - replace #table with your id.
This should work:
$(".checkall").click(function(){ var $table = $(this).closest("table"); var col = $(this).closest("tr").children().index($(this).closest("td")); var index = col + 1; // offset for nth-child $table.find("td:nth-child("+index+") input:checkbox").attr("checked",$(this).is(":checked")); });
-34965429 0 Giving VersionPress write permissions via ssh on bitnami WP ami running on EC2 instance Thanks in advance for your patience and support helping me with this issue. I can normally work around most problems by reading online, but when it comes to linux and ssh I cant - it's too complex. No two explanations seem the same.
The problem is this:
I launched an EC2 instance using the bitnami wordpress ami (i think its an ami?) and everything works great.
Im super excited about this new wordpress project called VersionPress, link below.
I managed to install git and get a tick in that box. Now I need to satisfy the plugin's requirements for write permission on several folders.
I've been reading up on chmod, and checking out what permission are currently in place using ssh, but can not, for the life of me, make sense of it.
The info on what VersonPress needs is here: http://docs.versionpress.net/en/getting-started/installation-uninstallation
If we take for example the plugins own folder /versionpress, I can navigate to it and see the current permissions using ls:
drwxr-xr-x 7 bitnami bitnami ... versionpress
So I'm like ok, I suppose I'd better give group write permissions. But, no version of the chmod command I write will execute and even then, it's only one of the folders that I need to change.
UPDATE: I added '~' and got chmod working on the /versionpress dir
As a next step I tried to change rights on /wordpress dir. This was initially unsuccessful until I applied command with Sudo.
VersionPress still reports it does not have the correct permissions however.
Error msg: VersionPress needs write access in the site root, its nested directories and the system temp directory. Please update the permissions.
END UPDATE
Anyone experienced this, got VersionPres up and running on EC2 or with any advice to move me forward?
Thanks.
-18543228 0 Statically linking a C library with a Haskell libraryI have a Haskell project that aims to create some C++ bindings. I've written the C wrappers and compiled them into a stand-alone statically linked library.
I'd like to write the Haskell bindings to link statically to the C wrappers so that I don't have to distribute the C wrappers separately but I can't seem to get it working and would appreciate some help.
I specify the C library as an extra library but my cabal build step doesn't seem to add it to compile command.
I've created a small project to illustrate this (http://github.com/deech/CPlusPlusBindings).
It contains a small C++ class (https://github.com/deech/CPlusPlusBindings/tree/master/cpp-src), the C wrapper (https://github.com/deech/CPlusPlusBindings/tree/master/c-src), a working C test routine (https://github.com/deech/CPlusPlusBindings/tree/master/c-test) and the Haskell file (https://github.com/deech/CPlusPlusBindings/blob/master/src/BindingTest.chs).
The C library is added in Setup.hs not in the Cabal file because that's how I have it my real project which builds the C library using "make" through Cabal just before the build stepf. I have verified that at the build step the extraLibs part of BuildInfo contains the library name and extraLibDirs contains the right directory.
The output of my cabal build is:
creating dist/setup ./dist/setup/setup build --verbose=2 creating dist/build creating dist/build/autogen Building CPlusPlusBinding-0.1.0.0... Preprocessing library CPlusPlusBinding-0.1.0.0... Building library... creating dist/build /usr/local/bin/ghc --make -fbuilding-cabal-package -O -odir dist/build -hidir dist/build -stubdir dist/build -i -idist/build -isrc -idist/build/autogen -Idist/build/autogen -Idist/build -I/home/deech/Old/Haskell/CPlusPlusBinding/c-src -I/home/deech/Old/Haskell/CPlusPlusBinding/cpp-includes -optP-include -optPdist/build/autogen/cabal_macros.h -package-name CPlusPlusBinding-0.1.0.0 -hide-all-packages -package-db dist/package.conf.inplace -package-id base-4.6.0.1-8aa5d403c45ea59dcd2c39f123e27d57 -XHaskell98 -XForeignFunctionInterface BindingTest Linking... /usr/bin/ar -r dist/build/libHSCPlusPlusBinding-0.1.0.0.a dist/build/BindingTest.o /usr/bin/ar: creating dist/build/libHSCPlusPlusBinding-0.1.0.0.a /usr/bin/ld -x --hash-size=31 --reduce-memory-overheads -r -o dist/build/HSCPlusPlusBinding-0.1.0.0.o dist/build/BindingTest.o In-place registering CPlusPlusBinding-0.1.0.0... /usr/local/bin/ghc-pkg update - --global --user --package-db=dist/package.conf.inplace Unfortunately neither the compilation nor the linking step uses the C library. There are no other warnings or errors.
-18650163 0index.php or index.html should be the default files loaded by your server when visiting a site, not home.html. Try clearing your cache. If that doesn't help it could be an issue in httpd.conf - but that sounds kind of extreme in this scenario.
You can also look into using mod_rewrite in your .htaccess file so the redirect happens at the server level
Options +FollowSymLinks -MultiViews RewriteEngine On RewriteBase / # redirect home.html to index.php RewriteRule ^home.html index.php [R=301,L]
-6363825 0 TableViewer cell editor not working - SWT I am trying to implement an editable table viewer in Eclipse SWT. I think I've done everything ok until now, problem is the table is not editable - nothing happens if I click on any row.
I have registered some CellEditors with all my columns:
CellEditor[] editors = new CellEditor[columnNames.length]; editors[0] = new TextCellEditor(table); //do the above for all columns tableViewer.setCellEditors(editors); and then I specify a cell modifier for my table:
tableViewer.setCellModifier(new CellModifier(this)); The CellModifier class looks like this:
public class CellModifier implements ICellModifier{ private DBStructureView dbView; public CellModifier(DBStructureView view){ super(); this.dbView = view; } @Override public boolean canModify(Object element, String property) { return true; } @Override public Object getValue(Object element, String property) { int columnIndex = dbView.getColumnNames().indexOf(property); Object result = null; AttributeNode node = (AttributeNode) element; switch(columnIndex){ case 0://row id result = node.getRow(); case 1://name result = node.getName(); case 2://value result = node.getValue(); default: result = "unknown"; } System.out.println(result); return result; } @Override public void modify(Object element, String property, Object value) { int columnIndex = dbView.getColumnNames().indexOf(property); TableItem item = (TableItem) element; AttributeNode node = (AttributeNode)item.getData(); String valueString; switch(columnIndex){ case 0: valueString = ((String) value).trim(); node.setRow(valueString); break; case 1: valueString = ((String) value).trim(); node.setName(valueString); break; case 2: valueString = ((String) value).trim(); node.setValue(valueString); break; default: break; } } } Having done all this, what can go wrong?
Thanks in advance!
-26307385 0Like Christian Conkle hinted at, we can determine if a type has an Integral or Floating instance using more advanced type system features. We will try to determine if the second argument has an Integral instance. Along the way we will use a host of language extensions, and still fall a bit short of our goal. I'll introduce the following language extensions where they are used
{-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE OverlappingInstances #-} To begin with we will make a class that will try to capture information from the context of a type (whether there's an Integral instance) and convert it into a type which we can match on. This requires the FunctionalDependencies extension to say that the flag can be uniquely determined from the type a. It also requires MultiParamTypeClasses.
class IsIntegral a flag | a -> flag We'll make two types to use for the flag type to represent when a type does (HTrue) or doesn't (HFalse) have an Integral instance. This uses the EmptyDataDecls extension.
data HTrue data HFalse We'll provide a default - when there isn't an IsIntegral instance for a that forces flag to be something other than HFalse we provide an instance that says it's HFalse. This requires the TypeFamilies, FlexibleInstances, and UndecidableInstances extensions.
instance (flag ~ HFalse) => IsIntegral a flag What we'd really like to do is say that every a with an Integral a instance has an IsIntegral a HTrue instance. Unfortunately, if we add an instance (Integral a) => IsIntegral a HTrue instance we will be in the same situation Christian described. This second instance will be used by preference, and when the Integral constraint is encountered it will be added to the context with no backtracking. Instead we will need to list all the Integral types ourselves. This is where we fall short of our goal. (I'm skipping the base Integral types from System.Posix.Types since they aren't defined equally on all platforms).
import Data.Int import Data.Word import Foreign.C.Types import Foreign.Ptr instance IsIntegral Int HTrue instance IsIntegral Int8 HTrue instance IsIntegral Int16 HTrue instance IsIntegral Int32 HTrue instance IsIntegral Int64 HTrue instance IsIntegral Integer HTrue instance IsIntegral Word HTrue instance IsIntegral Word8 HTrue instance IsIntegral Word16 HTrue instance IsIntegral Word32 HTrue instance IsIntegral Word64 HTrue instance IsIntegral CUIntMax HTrue instance IsIntegral CIntMax HTrue instance IsIntegral CUIntPtr HTrue instance IsIntegral CIntPtr HTrue instance IsIntegral CSigAtomic HTrue instance IsIntegral CWchar HTrue instance IsIntegral CSize HTrue instance IsIntegral CPtrdiff HTrue instance IsIntegral CULLong HTrue instance IsIntegral CLLong HTrue instance IsIntegral CULong HTrue instance IsIntegral CLong HTrue instance IsIntegral CUInt HTrue instance IsIntegral CInt HTrue instance IsIntegral CUShort HTrue instance IsIntegral CShort HTrue instance IsIntegral CUChar HTrue instance IsIntegral CSChar HTrue instance IsIntegral CChar HTrue instance IsIntegral IntPtr HTrue instance IsIntegral WordPtr HTrue Our end goal is to be able to provide appropriate instances for the following class
class (Num a, Num b) => Power a b where pow :: a -> b -> a We want to match on types to choose which code to use. We'll make a class with an extra type to hold the flag for whether b is an Integral type. The extra argument to pow' lets type inference choose the correct pow' to use.
class (Num a, Num b) => Power' flag a b where pow' :: flag -> a -> b -> a Now we'll write two instances, one for when b is Integral and one for when it isn't. When b isn't Integral, we can only provide an instance when a and b are the same.
instance (Num a, Integral b) => Power' HTrue a b where pow' _ = (^) instance (Floating a, a ~ b) => Power' HFalse a b where pow' _ = (**) Now, whenever we can determine if b is Integral with IsIntegral and can provide a Power' instance for that result, we can provide the Power instance which was our goal. This requires the ScopedTypeVariables extension to get the correct type for the extra argument to pow'
instance (IsIntegral b flag, Power' flag a b) => Power a b where pow = pow' (undefined::flag) Actually using these definitions requires the OverlappingInstances extension.
main = do print (pow 7 (7 :: Int)) print (pow 8.3 (7 :: Int)) print (pow 1.2 (1.2 :: Double)) print (pow 7 (7 :: Double)) You can read another explanation of how to use FunctionalDependencies or TypeFamilies to avoid overlap in overlapping instances in the Advanced Overlap article on HaskellWiki.
Have you considered a WYSIWYG editor? For example the editor in which you typed your question in this site is WMD and it allows to bold the text.
-10207141 0 Windows Phone 7 Play Vimeo VideoI am trying to get Vimeo videos to play in a windows 7 phone app, we need to online streaming specific video from vimeo in our Application. i have revieved following links but still i have not found any solution.
any one know how to play online stream Vimeo video in Windows Phone 7 Application?
Thanks In Advance.
-13480990 0 linkout failing with conflicting JSESSIONIDI have an issue with the linkout of my application (say App2) on another application (say App1).
Both are web applications and so both are creating there own JSESSION IDs. The linkout opens in a pop up and single sign on works (siteminder passing the sm user cookie), but as soon as I perform any transaction on the linked application I am thrown out stating the session is either timed out or invalid.
I looked at the cookies present on the browser and found that both the JSESSION IDs are present. The only difference is in the domain scope of both the JSESSION IDs. App1 application has domain scope of say abc.com whereas App2 has app2.abc.com
I tried changing the name of the JSESSION ID cookie of App2 but the application did not work with the renamed JSESSION cookie.
Any suggestion on how can I fix this ?
Note : The environment for App2 is was5
Regards AVN
-7012138 0 ASP.NET web control panel for a desktop applicationI'm working on a C# windows application but I'd like to create a website to be hosted on the same machine that could provide monitoring, other people on the network would be able to login and see the state of certain variables, maybe trigger methods to turn things on and off. I'm looking for a point in the right direction as to how I'd go about doing this?
Thanks, Ben
-26749255 0Before using the "prompt" module, I used the ReadLine interface; sadly I had the same problem. However, the fix was simple:
Remove the
rli.close();and then run it.Then re-add the
rli.close();and it works!
Thanks mscdex for the input, though :)
-18755341 0 Handle $_GET requests with Clean URLsI am have a clear URL based system so the categories will be shown like this
http://www.mysite.com/category/23/cat-name Inside the categories page I have some sorting and pages options such as sorting by latests and lower price. Also, I have a pages navigation system
The problem is when the request is happening inside the page the $_GET[] doesn't show the variables I need. However it shows in the URL as
http://www.mysite.com/category/23/cat-name?page=3 The $_GET variable only shows the id of the category which is in our case now = 23 and ignored the page number which is in the url.
.htaccess content
RewriteEngine On RewriteRule ^category/([0-9]+)/[a-z][-a-z0-9]*$ cat.php?id=$1
-39413786 1 Can I make an ipywidget floatslider with a list of values? I would like to make an ipywidget floatslider, but passing it a list of values, rather than a range and step. Is there a way to do this, or is making a dropdown widget the only option?
-19335973 0In base class, create abstract virtual method that returns some kind of "ID". (string, int, enum, whatever).
In "save" method, write ID first, for all classes. You could embed ID writing into base class, so derived classes won't override this behavior.
typedef SomeType ClassId; class Serializeable{ protected: virtual ClassId getClassId() const = 0; virtual void saveData(OutStream &out) = 0; public: void save(OutStream &out){ out << getClassId(); saveData(out); } }; Make a factory, that constructs required class given its ID.
--edit--
Example with factory (C++03 standard):
#include <map> #include <string> #include <iostream> #include <QSharedPointer> #include <utility> typedef std::string ClassId; typedef std::ostream OutStream; class Serializeable{ protected: virtual void saveData(OutStream &out) = 0; public: virtual ClassId getClassId() const = 0; void save(OutStream &out){ out << getClassId(); saveData(out); } virtual ~Serializeable(){ } }; class Derived: public Serializeable{ protected: virtual void saveData(OutStream &out){ out << "test"; } public: virtual ClassId getClassId() const{ return "Derived"; } }; typedef QSharedPointer<Serializeable> SerializeablePtr; //basically std::shared_ptr SerializeablePtr makeDerived(){ return SerializeablePtr(new Derived()); } class ClassFactory{ protected: typedef SerializeablePtr (*BuilderCallback)(); typedef std::map<ClassId, BuilderCallback> BuilderMap; BuilderMap builderMap; template<class C> static SerializeablePtr defaultBuilderFunction(){ return SerializeablePtr(new C()); } public: SerializeablePtr buildClass(ClassId classId){ BuilderMap::iterator found = builderMap.find(classId); if (found == builderMap.end()) return SerializeablePtr();//or throw exception return (*(found->second))(); } void registerClass(ClassId classId, BuilderCallback callback){ builderMap[classId] = callback; } template<typename T> void registerClassByValue(const T &val){ registerClass(val.getClassId(), ClassFactory::defaultBuilderFunction<T>); } template<typename T> void registerClassWithTemplate(ClassId classId){ registerClass(classId, ClassFactory::defaultBuilderFunction<T>); } }; int main(int argc, char** argv){ ClassFactory factory; std::string derivedId("Derived"); factory.registerClass(derivedId, makeDerived); SerializeablePtr created = factory.buildClass(derivedId); created->save(std::cout); std::cout << std::endl; Derived tmp; factory.registerClassByValue(tmp); created = factory.buildClass(derivedId); created->save(std::cout); std::cout << std::endl; factory.registerClassWithTemplate<Derived>(derivedId); created = factory.buildClass(derivedId); created->save(std::cout); std::cout << std::endl; return 0; } QSharedPointer is smart pointer class from Qt 4, roughly equivalent to std::shared_ptr. Use either std::shared_ptr or boost::shared_ptr instead of QSharedPointer in your code.
I'm testing something in Oracle and populated a table with some sample data, but in the process I accidentally loaded duplicate records, so now I can't create a primary key using some of the columns.
How can I delete all duplicate rows and leave only one of them?
-4628503 0The answer is pretty simple, clearing the FLAG_FULLSCREEN flag is all thats necessary:
if (isStatusBarVisible) getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); else getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
-41073589 0 If the parts to remove are always the same you can use str_replace() function passing as serach value an array with both parts you want to remove
function remove_strings($string) { return str_replace(array('LifeSteal ', ' \n'), '', $string); }
-9943617 0 Do I understand it correctly? You want to invoke something like...
postUser(user); postFile(myFile); and in the client, to process the two different requests in some stateful manner(the receiver is supposed to know that ).
@Post public void userPost(String name) { User.getInstance().addUser(name); } @Post public void filePost(File file) { //processing the file, ONLY IF the userPost method is already invoked } Instead, can you encapsulate the two requests in one(one request with two parameters). Something like
postUserFile(user,file); And in the request reciever...
@Post public void nameFilePost(String name, File file) { userPost(name); filePost(file) } I don't recognize the framework which you are using, but in JAX-RS the method will looks something like this
@PATH("/yourPath/") public class YourClassNameHere{ @POST public void nameFilePost(@QueryParam("name") String name, @QueryParam("file") File file) { userPost(name); filePost(file) } } One last thing: Don't use Singletons, they are global variables, and therefore bad. Why global variables are bad.
-39467407 0One-liner direct computation (no Date object):
function daysInMonth(m, y) {//m is 1-based, feb = 2 return 31 - (--m ^ 1? m % 7 & 1: y & 3? 3: y % 25? 2: y & 15? 3: 2); } console.log(daysInMonth(2, 1999)); // February in a non-leap year console.log(daysInMonth(2, 2000)); // February in a leap year Variation with 0-based months:
function daysInMonth(m, y) {//m is 0-based, feb = 1 return 31 - (m ^ 1? m % 7 & 1: y & 3? 3: y % 25? 2: y & 15? 3: 2); }
-37254777 0 Here is a nasty, hacky, quick-fix solution which will stop the nasty cropping by resizing Swing's own icons to 80%.
In main, add this:
String[] iconOpts = {"OptionPane.errorIcon", "OptionPane.informationIcon", "OptionPane.warningIcon", "OptionPane.questionIcon"}; for (String key : iconOpts) { ImageIcon icon = (ImageIcon) UIManager.get(key); Image img = icon.getImage(); BufferedImage bi = new BufferedImage( img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); java.awt.Graphics g = bi.createGraphics(); g.drawImage(img, 0, 0, (int) (img.getWidth(null) * 0.8), (int) (img.getHeight(null) * 0.8), null); ImageIcon newIcon = new ImageIcon(bi); UIManager.put(key, newIcon); } You might want to first check whether this is actually required - Windows 8/10 defaults to 125% but some people will switch it back to 100%. I haven't found an elegant way to do this, but something along these lines will give you an idea:
java.awt.Font font = (java.awt.Font) UIManager.get("Label.font"); if (font.getSize() != 11) { //resize icons in here }
-5753775 0 Refer to this link. you will find many examples related to animation.
http://www.vellios.com/2010/07/11/simple-iphone-animation-tutorial/
-7905816 0Here's my wild guess: cache
It could be that you can fit 2 rows of 2000 doubles into the cache. Which is slighly less than the 32kb L1 cache. (while leaving room other necessary things)
But when you bump it up to 2048, it uses the entire cache (and you spill some because you need room for other things)
Assuming the cache policy is LRU, spilling the cache just a tiny bit will cause the entire row to be repeatedly flushed and reloaded into the L1 cache.
The other possibility is cache associativity due to the power-of-two. Though I think that processor is 2-way L1 associative so I don't think it matters in this case. (but I'll throw the idea out there anyway)
Possible Explanation 2: Conflict cache misses due to super-alignment on the L2 cache.
Your B array is being iterated on the column. So the access is strided. Your total data size is 2k x 2k which is about 32 MB per matrix. That's much larger than your L2 cache.
When the data is not aligned perfectly, you will have decent spatial locality on B. Although you are hopping rows and only using one element per cacheline, the cacheline stays in the L2 cache to be reused by the next iteration of the middle loop.
However, when the data is aligned perfectly (2048), these hops will all land on the same "cache way" and will far exceed your L2 cache associativity. Therefore, the accessed cache lines of B will not stay in cache for the next iteration. Instead, they will need to be pulled in all the way from ram.
I'm guessing that it has to do with using a keyword as a function name. I tried defining a function print() in a module just now for testing and got the same sort of error. Try changing the name of this function slightly and see if it fixes the problem.
If I have understood the question correctly I think you just need a CASE statement in the SELECT e.g.
CASE WHEN blackLIST = TRUE OR optout = TRUE THEN 1 ELSE 0 END
-34271936 0 FYI, I was able to customize the watch face, using the extension code you provided. No problem there.
If you notice the bundle id in the crash log error, the system is reporting a problem with the watchkit app (which contains the watchkit extension).
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Application is required. bundleID: ql.ManaEU.watchkitapp ...
You'll need to track down what's wrong with the watchkit bundle. The first place to start would be the Xcode watchkit app build target log. If there are no errors or warnings there, check the iPhone and Apple Watch console logs.
If that doesn't point you to the problem, check the Info.plist to make sure those values are valid, and the required keys are present. Also check the watchkit app target build settings.
You should be able to use the Version Editor to compare the Xcode project against its initial commit, to see if something was inadvertently changed or deleted.
-24521990 0easily done, you just need to set the display to inline-block for those two iframes.
iframe:nth-child(2),iframe:nth-child(3){ display:inline-block; } iframes are somewhat frowned upon. You might like to consider using divs with ajax instead, utilizing the jquery $.load function to load whatever you like into them. You can read up on that here.
Hope that helps...
-549850 0Is the link from a different domain? Browsers may restrict access to any information about what a user has open in other windows or frames if it's on another site as a security precaution.
-6715093 0 Why is there no edit in Blend option in WPF4?I am a Silverlight 4 developer getting started with WPF4. In Silverlight 4, there is option available in menu "Edit in Blend" when you right click on any xaml file. Why is this option not available in WPF4?
Do I need to download some patch for Visual Studio 2010?
Thanks in advance :)
-31450970 0 php dll cannot be loaded into server when using apachelounge VC14 build and php.net VC11 buildI am following this great post
Version details;
Apache 2.4.16 php 5.6.11 mysql community installer 5.6.25
Directory structure:
C: server Every setup goes here
Windows System - 7 - 64 bit.
Error
httpd.exe: Syntax error on line 178 of C:/server/httpd/Apache24 /conf/httpd.conf: Cannot load C:\\server\\php\\php5apache2_4.dll into server: The specified module could not be found. code which causes
LoadModule php5_module C:\server\php\php5apache2_4.dll ----> This Line <IfModule php5_module> DirectoryIndex index.html index.php AddHandler application/x-httpd-php .php PHPIniDir "C:\server\php" </IfModule> It was worked earlier - I just put a new OS and trying the same under C;\server for generic setup so that I can make use of it in every windows 64 bit system with same directory structure.
My doubt : Is it due to version incompatible problems
Download locations:
mysql is from mysql domain php from php domain apache from apachelongue Please help me to solve the error.
EDIT FOR A COMMENT:
php apache dll is present in the php directory
A NOTE
A question becomes stupid when you know the answer like you remember a-z. So no question is stupid generally.
The problem is that you're not escaping the special characters in the text, such as the / delimiter.
The easiest solution is to pick a different delimiter and to specify only a part of the string, for instance
find . -name '*.html' -o -name '*.htm' | xargs fgrep -l '<script>i=0;try' | xargs perl -i.infected -pe 's#<script>i=0;try.*?</script>##g' (untested) may do the job. (The .*? construct picks the shortest match; I don't know how to do that in sed.)
Verify with something like
find . -name '*.infected' | sed -e 's#.*#diff & &#' -e 's#.infected##' | sh -x
-30486321 0 Try the following idea:
try { File file = new File(path); FileWriter writer = new FileWriter(file); BufferedWriter output = new BufferedWriter(writer); for (int[] array : matrix) { for (int item : array) { output.write(item); output.write(" "); } output.write("\n"); } output.close(); } catch (IOException e) { }
-10100237 0 You probably need to set android:fillEnabled="true" and/or android:fillAfter="true".
If that does not work you can apply the change to the layout in AnimationListener#onAnimationEnd.
You need to call addNewMessageToPage in your Post action method.
var hubContext = GlobalHost.ConnectionManager.GetHubContext<ChatHub>(); hubContext.Clients.All.addNewMessageToPage(chat.Name, chat.Message); Then in your JS file:
var chatHub = $.connection.chatHub; chatHub.client.addNewMessageToPage= function (name, message) { //Add name and message to the page here }; $.connection.hub.start();
-31438319 0 C# IEnumerable neededFiles I have this code:
var neededFiles = new[]{ "file1.exe", "file2.exe", "file3.exe", "file4.exe" }; IEnumerable<string> notFound = neededFiles.Where(f => !File.Exists(f)); if (notFound.Any()) { MessageBox.Show(string.Format(notFound.Count() > 1 ? "App cannot find these files - {0}" : "App cannot find this file - {0}", String.Join(", ", neededFiles)), "Test", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } It work's OK, but If I have for example file1.exe, file2.exe, file3.exe files code anyway prints "App cannot find these files - file1.exe, file2.exe, file3.exe, file4.exe". How to make it print only needed file which not exists? Example: if exists file1.exe, file3.exe, it must print: App cannot find these files - file2.exe, file4.exe Thanks in advance
FIXED: The best overloaded method match for 'string.Join(string, string[])' has some invalid arguments This helped me.
-34713327 0 Appending elements to parents that called the createElement() functionI am trying to create a function that creates an element and takes the parameter of element (an object).
var createElement = function(element) { var newElement = document.createElement(element.type); var newElement_textNode = document.createTextNode(element.text); newElement.appendChild(newElement_textNode); element.parent.appendChild(newElement); }; The only problem is I want to append the element to the element that called the function. For example:
var list = document.getElementById('ulList'); list.createElement({ type: 'li', text: 'Another item' }); My question is how do I append it to the element that called the function, in this case, the ul list
You can apply the Holo theme using the HoloEverywhere library. I use it in all my apps, and it works very well.
You have to add it as a library project to use it. If you use Git, you can add it as a submodule.
-8396006 0 Thickbox not opening with anchor tags generated at runtimeI am having an issue opening a thick-box with anchor tags appended to a div at runtime.The anchor tag contains the thick-box css and the href,that is required to open up a thickbox.However,its not opening up the required page in a thickbox. All it does is,open up the page in a new page. However,when i crate a hard coded anchor with the required thickbox stuff,it opens up fine.The only issue is ,it doesn't do the same when it is generated at runtime .
I am using Jquery to append the anchor tags.
Doesn't Jquery understand anchor tags with thickbox property append at runtime ?
-8177807 0You can't send through the email submitted on the form, since you aren't authorized to use that email. You either have to use an email you control or the user's email by connecting to their Google account. http://code.google.com/appengine/docs/python/mail/sendingmail.html This page says which email you can use to send emails from, just scroll down right after the first code block.
-40596310 0 Drop down value replicates in nog options AngularI have a dynamically generated html table that adds rows based on the record that is displayed. I'm adding a column that will contain a dropdown. I used ng-options for it, however every time I change one record, the rest are also updated. Tried changing it to ng-repeat and get the same result. See code below:
<td> <select class="form-control" ng-model="$ctrl.selectedRC" ng- options="r.ccd as (r.OName + ' -- '+ r.RCName) for r in $ctrl.RC track by r.ccd"> </select> <!--if I have 5 records, all dropdowns in the table change --> </td> Using ng-repeat:
<select class="form-control" ng-model="$ctrl.selectedRC" <option value="" ng-selected="true">--Select one--</option> <option ng-repeat="r in $ctrl.RC" value="{{r.OName}}" ng-selected="{{r.OName === selectedRC}}">{{r.RCName}} </option> </select> I know that these two are currently displaying two different things (one a concatenated set of values, the other juts one). But my main interest is to figure out how to have each <td> have its own dropdown without affecting the rest of the rows.
I have this routine,
I want to save that delta to count the days between all to and from days in the from-to pairs I have in the 2 dimensional array, I just need the workdays.
Say for
$date_from = 2012-02-09; $date_to = 2012-02-13; $delta_string = 4 sub calc_usage { use Date::Manip::Date; my $date_from; my $date_to; my $delta; my $i; for $i (0 .. $#DATE_HOLDER) { $date_from = new Date::Manip::Date; $date_to = new Date::Manip::Date; $date_from->parse($DATE_HOLDER[$i][0]); $date_to->parse($DATE_HOLDER[$i][1]); $delta = $date_from->calc($date_to, "business"); } }
-18181567 0 This error is commonly because of a DLL version mismatch. Try deleting your bin folder and rebuilding the application.
USE VISION_DB SELECT tpi.ProfileName, tic.ChannelName FROM T_PROFILE_INFO tpi, T_INPUT_CHANNEL_INFO tic, T_PROFILE_CHANNELS INNER JOIN T_PROFILE_CHANNELS tpc ON tpc.ProfileID = ***T_PROFILE_INFO.ProfileID*** AND tpc.ChannelID = ***T_INPUT_CHANNEL_INFO.ChannelID*** I am able to return the multi-part identifier alert for each of the two entries highlighted.
The alias tpc is referenced correctly, but the right side of each expression will not. I have substituted the alias' from the FROM clause, but they are out of scope here.
I have been trying to sort this for some time. I believe there is a namespace issue, but do not know how to reference the changes required.
I run across this issue regularly, but have always been able to resolve it with a search. I can find nothing that appears to clear this up.
-15193786 0No, you are misunderstanding how that method works. componentsSeparatedByString: doesn't use the individual characters in the passed string, it uses the entire string. Your separator is the three-character sequence [,]. A string like @"pecan[,]pie" uses this separator, but @"1[0,5]" does not. The similar method componentsSeparatedByCharactersInSet: will do what you are expecting:
[string componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"[,]"]]; If you want to pull digits out of strings and get their numerical values, you may want to look at NSScanner.
in ALL browsers, the browser will make padding and margin between all the things. to remove that and control the page yourself add this add the first line of your css:
* {margin:0 auto; padding:0} auto makes all the things (except text and images) at the center of your page.
and for your table if you want texts to be on top of your td, add this:
.tlt{vartical-align:top; text-align:left;}
I created a Java application in NetBeans. That Java application contains a GUI and some external Jars.
In the dist folder I can see a Jar file and a folder called lib where are the jars I use in the project. If I execute the Jar file the application works as expected. If I change the name of the lib folder the application does not work (meaning that the Jar is using the correct files). But when I copy the dist folder to a different machine (with the same Java version) the application does not work as expected. The user interface is shown but the functionalities does not work (the functionalities are in the external Jars i mentioned in the beginning). Can anyone help?
EDIT:
I checked the class-path in the MANIFEST file and everything is ok.
-32712587 0So, you are hitting tomcat hot-redeploy ClassLoader issues.
There are two things you should do:
Make sure that when your application is shutdown, your Hibernate SessionFactory gets close()ed as well. The best place to do this is a ServletContextListener. Otherwise, on hot redeploy, c3p0 Threads from a now-discarded app will continue to be running. See SessionFactory.close()
Try the settings described here to prevent stray references to objects from a defunct ClassLoader. You can just add
<property name="hibernate.c3p0.privilegeSpawnedThreads">true</property> <property name="hibernate.c3p0.contextClassLoaderSource">library</property> to your c3p0 config section.
(p.s. Be sure you are using a recent version of c3p0. These settings are new-ish.)
-37264706 0 names of a dataset returns NULL- R version 3.2.4 Revised-Ubuntu 14.04 LTSI have a small issue regarding a dataset I am using. Suppose I have a dataset called mergedData2 defined using those command lines from a subset of mergedData:
mergedData=rbind(test_set,training_set) lookformean<-grep("mean()",names(mergedData),fixed=TRUE) lookforstd<-grep("std()",names(mergedData),fixed=TRUE) varsofinterests<-sort(c(lookformean,lookforstd)) mergedData2<-mergedData[,c(1:2,varsofinterests)] If I do names(mergedData2), I get:
[1] "volunteer_identifier" "type_of_experiment" [3] "body_acceleration_mean()-X" "body_acceleration_mean()-Y" [5] "body_acceleration_mean()-Z" "body_acceleration_std()-X" (I takes this 6 first names as MWE but I have a vector of 68 names)
Now, suppose I want to take the average of each of the measurements per volunteer_identifier and type_of_experiment. For this, I used a combination of split and lapply:
mylist<-split(mergedData2,list(mergedData2$volunteer_identifier,mergedData2$type_of_experiment)) average_activities<-lapply(mylist,function(x) colMeans(x)) average_dataset<-t(as.data.frame(average_activities)) As average_activities is a list, I converted it into a data frame and transposed this data frame to keep the same format as mergedData and mergedData2. The problem now is the following: when I call names(average_dataset), it returns NULL !! But, more strangely, when I do:head(average_dataset) ; it returns :
volunteer_identifier type_of_experiment body_acceleration_mean()-X body_acceleration_mean()-Y 1 1 0.2773308 -0.01738382 2 1 0.2764266 -0.01859492 3 1 0.2755675 -0.01717678 4 1 0.2785820 -0.01483995 5 1 0.2778423 -0.01728503 6 1 0.2836589 -0.01689542 This is just a small sample of the output, to say that the names of the variables are there. So why names(average_dataset) returns NULL ?
Thanks in advance for your reply, best
EDIT: Here is an MWE for mergedData2:
volunteer_identifier type_of_experiment body_acceleration_mean()-X body_acceleration_mean()-Y 1 2 5 0.2571778 -0.02328523 2 2 5 0.2860267 -0.01316336 3 2 5 0.2754848 -0.02605042 4 2 5 0.2702982 -0.03261387 5 2 5 0.2748330 -0.02784779 6 2 5 0.2792199 -0.01862040 body_acceleration_mean()-Z body_acceleration_std()-X body_acceleration_std()-Y body_acceleration_std()-Z 1 -0.01465376 -0.9384040 -0.9200908 -0.6676833 2 -0.11908252 -0.9754147 -0.9674579 -0.9449582 3 -0.11815167 -0.9938190 -0.9699255 -0.9627480 4 -0.11752018 -0.9947428 -0.9732676 -0.9670907 5 -0.12952716 -0.9938525 -0.9674455 -0.9782950 6 -0.11390197 -0.9944552 -0.9704169 -0.9653163 gravity_acceleration_mean()-X gravity_acceleration_mean()-Y gravity_acceleration_mean()-Z 1 0.9364893 -0.2827192 0.1152882 2 0.9274036 -0.2892151 0.1525683 3 0.9299150 -0.2875128 0.1460856 4 0.9288814 -0.2933958 0.1429259 5 0.9265997 -0.3029609 0.1383067 6 0.9256632 -0.3089397 0.1305608 gravity_acceleration_std()-X gravity_acceleration_std()-Y gravity_acceleration_std()-Z 1 -0.9254273 -0.9370141 -0.5642884 2 -0.9890571 -0.9838872 -0.9647811 3 -0.9959365 -0.9882505 -0.9815796 4 -0.9931392 -0.9704192 -0.9915917 5 -0.9955746 -0.9709604 -0.9680853 6 -0.9988423 -0.9907387 -0.9712319 My duty is to get this average_dataset (which is a dataset which contains the average value for each physical quantity (column 3 and onwards) for each volunteer and type of experiment (e.g 1 1 mean1 mean2 mean3...mean68 2 1 mean1 mean2 mean3...mean68, etc)
After this I will have to export it as a txt file (so I think using write.table with row.names=F, and col.names=T). Note that for now, if I do this and import the dataset generated using read.table, I don't recover the names of the columns of the dataset; even while specifying col.names=T.
-34420330 0Use this method as per notes here http://quickblox.com/developers/Android#How_to:_add_SDK_to_IDE_and_connect_to_the_cloud
Note there is no "User" field for this create session method
QBAuth.createSession(new QBEntityCallbackImpl() {}
-18008502 0If speaking about x86 architecture when an operating system has nothing to do it can use HLT instruction. HLT instruction stops the CPU till next interrupt. See http://en.m.wikipedia.org/wiki/HLT for details.
Other architectures have similar instruction to give CPU a rest.
-28341976 0 Node js functions : sql query result call twiceI've got a problem with javascript/node js functions.
When I send an sql query with function query of "request.service.mssql" object, the result function is called twice...
I don't understand because my sql query is an "update" and the result is empty (I do not have multiple lines of results)
For example, I have a function that send an email with a new password. The email is sent twice... I found a temp solution with an index but it's not very clean.
Can you explain this ?
//construct SQL query var email = "test@toto.com"; var password = require("crypto").randomBytes(4).toString('hex'); var password_md5 = require("crypto").createHash("md5").update(password).digest("hex"); var sql = "update dbo.mytable SET password='"+password_md5+"' where id=12"; var id = 0; //temp solution mssql.query(sql, { success: function(results) { //Send email with new pwd if(id == 0) { response.send(statusCodes.OK,password_md5); sendEmail(email,password); } id++; //temp solution }, error: function(err) { response.send(statusCodes.INTERNAL_SERVER_ERROR,"Error : " + err); } }); Thank you :-)
Steve
-17610531 0Assuming you created this form with Webform...
If you just want to display the form at the end of the page, go to the form advance settings and click on "available as block"
Then on the block sections, add it to the "main content section" and configute the block.
Under Show block on specific pages, write the pages you want it to appear.
To print a block programatically
$block = module_invoke('webform', 'block_view', 'client-block-1'); //add your block id print render($block['content']);
-31159016 0 How to efficiently calculate cotangents from vectors I'm trying to implement a function to compute the cotangents of vectors (the mathematical ones) via the standard formula:
cot(a, b) = (a * b) / |a x b|, where a and b are vectors
A colleague told me that calculating 1/|a x b| is not the best thing to give a computer to calculate. Another alternative coming to my head is first calculating the angle and than using cotan functions for radians angles.
What would be the method of choice here? (Is there maybe another one, other than the mentioned ones)
-39775880 0I'm running into the same issue on Xamarin.android. Here's what the documentation says.
-40333042 0This can only be called before the fragment has been attached to its activity
Yes, you can send a GET request with no query string. In fact, whenever you hit a webpage using with your browser, you are sending a GET request, e.g. when you type http://google.com in the address bar and hit enter, your browser sends GET request to the URI and google server returns its page.
As Mardzis noted in comments, you can use empty() function in your PHP code:
<?php if (!empty($_GET['query'])) { $query = $_GET['query']; // Return results for specific query... } else { // Return all results... } EDIT
Since you've posted your Javascript code, I noticed something:
function showResults(str) { if (str.length == 0) { // If str is empty - isn't this where you want your "empty" query? But you don't } else { // If str is not empty, you send the request. } Seems like if str is empty, you're not sending the request at all. Am I correct?
I have two machines. One machine is a client and the other is a server running JBoss. I have no trouble having the client make requests and the server respond to those requests. However, for a new project that I need to do I have to reverse the roles. I have to implement a push model, so the server will need to make requests from the client. Specifically I need the server to be able to ask the client for files in a directory, copy files from the server to the client, and run programs on the client. I'd like to do this without adding a psedo server on the client (a small daemon process).
Is there a good way to do this?
Thanks
EDIT: So it would appear that I have to set up a server on the client machine to do what I need because I need to have the server push to the client while the client is not running the Java process (but the machine is on). With that in mind, what's the lightest weight Java server?
-13313728 0Replace NSNull objects with nil.
This will prevent your crash from accessing "objectForKey" (doesNotRecognizeSelector).
-39232791 0 how to get the same font effect in photoshop imageI am really new at photoshop and I created some some effect on text few days back now I Want to get the same effect and apply it again in different image It's basically a date and now I want to modify it but I need same effect
Here is the image that I created 
I now want to edit it to todays date but I don't remember how I did.. Please help me people..
-36475742 0To consider page 1 only…
var main = function(){ var doc = app.properties.activeDocument, finds,n; app.findTextPreferences = app.changeTextPreferences = null; app.findTextPreferences.findWhat = "#"; if ( !doc ) return; finds = doc.findText(); n = finds.length; while (n-- ) { finds[n].parentTextFrames.length && finds[n].parentTextFrames[0].isValid && finds[n].parentTextFrames[0].parentPage.id==doc.pages[0].id && finds[n].contents = "no: " + String(n+1); } }; main();
-36596218 0 The application, MyEAR, is trying to modify a cookie which matches a pattern in the restricted programmatic session cookies list I am getting below exception while deploying my application on WebSphere Application Server 8.5.5
java.lang.RuntimeException: SRVE8111E: The application, MyEAR, is trying to modify a cookie which matches a pattern in the restricted programmatic session cookies list [domain=*, name=JSESSIONID, path=/].
I found that if I remove below entry from my web.xml [session-config], then no error is shown with deployment and every things works fine.
<cookie-config> <http-only>true</http-only> </cookie-config> <tracking-mode>COOKIE</tracking-mode> The same ear is able to deploy and run perfectly with JBOSS and WebLogic server.
Please let me know what configuration change I have to do in which xml file to overcome this issue.
My application has application.xml, jboss-deployment-structure.xml and weblogic-application.xml.
Thanks in advance.
-14091715 0I'm using InAppSettingsKit with localized text with no problems. Two things I can think of that you could check: are your Root.strings files located in the correct subdirectories of Settings.bundle (en.lproj and fr.lproj for English and French?
Is there a "Strings Filename" entry in your Root.plist? It should simply contain a string with value "Root"
-12492112 0It looks like you're source code and binary are out of sync, ie. you're debugging a DLL/EXE that has been compiled with different version of the source code.
During debug activate the Debug->Windows->Modules window and check that the DLL/EXE you're debugging is the same as the one you've been compiling with your source code (check date/times, symbol files etc.).
-25622987 0 Authenticating the cobrandI created a new developer account and I am having a problem authenticating with the REST API.
POST https://rest.developer.yodlee.com/services/srest/restserver/v1.0/authenticate/coblogin { cobrandLogin: 'sbCob*****', cobrandPassword: '**********' } the system responds with:
{ Error: [ { errorDetail: 'Internal Core Error has occurred' } ] } am I doing something wrong?
-10447660 0 Switch View on GingerbreadI've coded an app which uses Switch as a toggler. When I run it on ICS I have no problems, but when I run it on gingerbread it crashes:
05-04 11:00:43.261: E/AndroidRuntime(1455): FATAL EXCEPTION: main 05-04 11:00:43.261: E/AndroidRuntime(1455): java.lang.RuntimeException: Unable to start activity ComponentInfo{it.android.smartscreenon/it.android.smartscreenon.ActivityImpostazioni}: android.view.InflateException: Binary XML file line #58: Error inflating class Switch 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1768) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1784) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.app.ActivityThread.access$1500(ActivityThread.java:123) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:939) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.os.Handler.dispatchMessage(Handler.java:99) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.os.Looper.loop(Looper.java:130) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.app.ActivityThread.main(ActivityThread.java:3835) 05-04 11:00:43.261: E/AndroidRuntime(1455): at java.lang.reflect.Method.invokeNative(Native Method) 05-04 11:00:43.261: E/AndroidRuntime(1455): at java.lang.reflect.Method.invoke(Method.java:507) 05-04 11:00:43.261: E/AndroidRuntime(1455): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847) 05-04 11:00:43.261: E/AndroidRuntime(1455): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605) 05-04 11:00:43.261: E/AndroidRuntime(1455): at dalvik.system.NativeStart.main(Native Method) 05-04 11:00:43.261: E/AndroidRuntime(1455): Caused by: android.view.InflateException: Binary XML file line #58: Error inflating class Switch 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:581) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.view.LayoutInflater.rInflate(LayoutInflater.java:623) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.view.LayoutInflater.rInflate(LayoutInflater.java:626) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.view.LayoutInflater.rInflate(LayoutInflater.java:626) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.view.LayoutInflater.rInflate(LayoutInflater.java:626) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.view.LayoutInflater.inflate(LayoutInflater.java:408) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.view.LayoutInflater.inflate(LayoutInflater.java:320) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.view.LayoutInflater.inflate(LayoutInflater.java:276) 05-04 11:00:43.261: E/AndroidRuntime(1455): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:212) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.app.Activity.setContentView(Activity.java:1657) 05-04 11:00:43.261: E/AndroidRuntime(1455): at it.android.smartscreenon.ActivityImpostazioni.onCreate(ActivityImpostazioni.java:43) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1722) 05-04 11:00:43.261: E/AndroidRuntime(1455): ... 11 more 05-04 11:00:43.261: E/AndroidRuntime(1455): Caused by: java.lang.ClassNotFoundException: android.view.Switch in loader dalvik.system.PathClassLoader[/data/app/it.android.smartscreenon-1.apk] 05-04 11:00:43.261: E/AndroidRuntime(1455): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240) 05-04 11:00:43.261: E/AndroidRuntime(1455): at java.lang.ClassLoader.loadClass(ClassLoader.java:551) 05-04 11:00:43.261: E/AndroidRuntime(1455): at java.lang.ClassLoader.loadClass(ClassLoader.java:511) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.view.LayoutInflater.createView(LayoutInflater.java:471) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.view.LayoutInflater.onCreateView(LayoutInflater.java:549) 05-04 11:00:43.261: E/AndroidRuntime(1455): at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:66) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:568) 05-04 11:00:43.261: E/AndroidRuntime(1455): ... 23 more It looks like Switch doesn't exist on Gingerbread. How can I solve the problem?
-35197802 0A bit more late, but I've found another option using ngnix as a proxy:
This guide has been finished by following partially this guideline: https://support.rstudio.com/hc/en-us/articles/213733868-Running-Shiny-Server-with-a-Proxy
On an Ubuntu 14.04:
This:
events { worker_connections 768; multi_accept on; } http { map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen XX; location / { proxy_pass http://localhost:YY; proxy_redirect http://localhost:YY/ $scheme://$host/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_read_timeout 20d; auth_basic "Restricted Content"; auth_basic_user_file /etc/nginx/.htpasswd; } } } XX: Port that the nginx will listen to
YY: Port that the shiny server uses
Using this tutorial, I added password authentication to the nginx server: https://www.digitalocean.com/community/tutorials/how-to-set-up-password-authentication-with-nginx-on-ubuntu-14-04
Set up the shiny process or the shiny server to only listen to localhost (127.0.0.1)
void work() { int *p; p=new int[10]; //some code.... } I have a short question that in the work function, should i use delete[] operator? since when work function is over, p will be destroyed, which is wrong or right ? (My English is bad, i am sorry).
-4160505 0 How can I Center an image within a fixed specified crop frame with graphicsmagick C libraryHey, I was wondering if someone knows a good way to scale an image while maintaining aspect ratio, and then center it with respect to a specified fixed crop area.
The first part is straight forward (resizing while maintaining ratio), just need help with the second part.
Here is a link to something that does this with php and image gd.. PHP crop image to fix width and height without losing dimension ratio
Another link to what I want to achieve is the "Crop" strategy on this page: http://transloadit.com/docs/image-resize#resize-strategies
I want to do this using the graphicsmagick C library.
Thanks a lot.
-3996939 0 how to use operators while making calc in javai used this code and I am having problem in the very basic step of how to use operator. Moreover I am even having problem taking more then 1 digit. If you please just add up the missing statements which would help me out. In the given code I have removed those steps that created problems in actionPerformed function
import java.awt.*; import javax.swing.*; import java.awt.event.*; import javax.swing.event.*; public class calculator1 implements ActionListener { private JFrame f; private JButton a,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15; JTextField tf; String msg=""; public calculator1() { f=new JFrame("Calculator"); f.setLayout(null); a=new JButton("1"); a.setActionCommand("1"); a1=new JButton("2"); a1.setActionCommand("2"); a2=new JButton("3"); a2.setActionCommand("3"); a3=new JButton("4"); a3.setActionCommand("4"); a4=new JButton("5"); a4.setActionCommand("5"); a5=new JButton("6"); a5.setActionCommand("6"); a6=new JButton("7"); a6.setActionCommand("7"); a7=new JButton("8"); a7.setActionCommand("8"); a8=new JButton("9"); a8.setActionCommand("9"); a9=new JButton("0"); a9.setActionCommand("0"); a10=new JButton("+"); a10.setActionCommand("+"); a11=new JButton("-"); a11.setActionCommand("-"); a12=new JButton("*"); a12.setActionCommand("*"); a13=new JButton("/"); a13.setActionCommand("/"); a14=new JButton("="); a14.setActionCommand("="); a15=new JButton("00"); a15.setActionCommand("00"); tf= new JTextField(30); } public void launchframe() { f.setSize(500,600); a.setBounds(100,200,50,50); a.addActionListener(this); a1.setBounds(160,200,50,50); a1.addActionListener(this); a2.setBounds(220,200,50,50); a2.addActionListener(this); a3.setBounds(100,300,50,50); a3.addActionListener(this); a4.setBounds(160,300,50,50); a4.addActionListener(this); a5.setBounds(220,300,50,50); a5.addActionListener(this); a6.setBounds(100,400,50,50); a6.addActionListener(this); a7.setBounds(160,400,50,50); a7.addActionListener(this); a8.setBounds(220,400,50,50); a8.addActionListener(this); a9.setBounds(100,500,50,50); a9.addActionListener(this); a10.setBounds(300,200,50,50); a10.addActionListener(this); a11.setBounds(300,300,50,50); a11.addActionListener(this); a12.setBounds(300,400,50,50); a12.addActionListener(this); a13.setBounds(300,500,50,50); a13.addActionListener(this); a14.setBounds(160,500,50,50); a14.addActionListener(this); a15.setBounds(220,500,50,50); a15.addActionListener(this); f.add(a); f.add(a1); f.add(a2); f.add(a3); f.add(a4); f.add(a5); f.add(a6); f.add(a7); f.add(a8); f.add(a9); f.add(a10); f.add(a11); f.add(a12); f.add(a13); f.add(a14); f.add(a15); tf.setBounds(100,150,250,30); f.add(tf); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); } public void actionPerformed(ActionEvent ae) { String s=ae.getActionCommand(); tf.setText(s); } public static void main(String[]arg) { calculator1 c1=new calculator1(); c1.launchframe(); } }
-30134037 0 It finally worked. Thank you @Oleg! I saw another post here http://goo.gl/Pg5CMn
Additionally, I figured that I was making another mistake. I forgot to enclose btnContactList in double quotes. After debugging in Internet explorer, I found that out. Secondly, as @Oleg suggested that the jsonReader attribute is required. Probably because of the version of jqGrid that I am using.
<script type="text/javascript"> $(document).ready(function () { //alert("this is a test"); $("#btnContactList").click(function () { $("#ContactTable").jqGrid({ url: "/Contact/ContactList", datatype: "json", colNames: ["ID", "First Name", "Last Name", "EMail"], colModel: [ { name: "ContactId", index: "ContactId", width: 80 }, { name: "FirstName", index: "FirstName", width: 100 }, { name: "LastName", index: "LastName", width: 100 }, { name: "EMail", index: "EMail", width: 200 } ], //data: result, mtype: 'GET', loadonce: true, viewrecords: true, gridview: true, caption: "List Contact Details", emptyrecords: "No records to display", jsonReader: { repeatitems: false, //page: function () { return 1; }, root: function (obj) { return obj; }, //records: function (obj) { return obj.length; } }, loadComplete: function () { alert("Complete ok!") }, loadError: function (jqXHR, textStatus, errorThrown) { alert('HTTP status code: ' + jqXHR.status + '\n' + 'textstatus: ' + textstatus + '\n' + 'errorThrown: ' + errorThrown); alert('HTTP message body (jqXHR.responseText: ' + '\n' + jqXHR.responseText); } }); alert("after completion"); }); }); </script>
-39248968 0 SELECT A.SETMOD, B.DESCRP FROM PMS.PSBSTTBL A JOIN PMS.PR029TBL B ON A.SETMOD =convert(decimal, B.PAYMOD)
-19204442 1 nested dictionary get keys sorted by values I'm using a dictionary that has nested dictionaries:
dicc={ 'a': {'a1': 1 }, 'b':{'b1':2 }, 'c':{'c1':3 } } # This is an example. I have lots of other keys and values. I need to get the keys ordered by the values. For example, getting c,b,a values: I will work on them in this order; first I need to use c to do other operations then b then a.
I used this to get the max value but I need all the values and use them in order mayor to minor:
valores=list(diccionario.values()) claves= list(diccionario.keys()) value_= claves[valores.index(max(valores))] edit: i need to get c,b,a sorted on this order and without using a b c , because c has the highest c1 value etc.. ok that works to sort a dict in reverse way but lets say i have this data:
1000 10 20 7 2 0
1001 3 30 3 5 0
1002 3 10 5 3 0
1003 7 22 3 1 0
second column is a prior, all this is stored into a dictionary the main keys are 1000,1001,1002,1003, the rest are values, i want to get 1000,1003,1002,1001 (this last have same prior) on this order,
-16700408 0If you really want to use NodeList, you can do this:
nList.item(i).setNodeValue(a.item(i).getNodeValue()); The better way to do it is just with a List as cmbaxter suggested, though.
List<Node> nodes = new ArrayList<Node>();
-20459887 0 Format specifies type 'int' but the argument has type 'UIViewContentMode' I am getting a warning in Xcode:
Format specifies type 'int' but the argument has type 'UIViewContentMode'
I have a method that I am using to resize an UIImage as follows:
- (UIImage *)resizedImageWithContentMode:(UIViewContentMode)contentMode bounds:(CGSize)bounds interpolationQuality:(CGInterpolationQuality)quality { CGFloat horizontalRatio = bounds.width / self.size.width; CGFloat verticalRatio = bounds.height / self.size.height; CGFloat ratio; switch (contentMode) { case UIViewContentModeScaleAspectFill: ratio = MAX(horizontalRatio, verticalRatio); break; case UIViewContentModeScaleAspectFit: ratio = MIN(horizontalRatio, verticalRatio); break; default: [NSException raise:NSInvalidArgumentException format:@"Unsupported content mode: %d", contentMode]; } ... UIViewContentMode seems to reference an Integer so I am not sure on this warning:
typedef NS_ENUM(NSInteger, UIViewContentMode) { UIViewContentModeScaleToFill, UIViewContentModeScaleAspectFit, // contents scaled to fit with fixed aspect. remainder is transparent UIViewContentModeScaleAspectFill, ... How can I get rid of this warning it seems to be incorrect? Is the NSLog in the exception correct?
It is just formatting the output in your client.
For example, in SQL*Plus set numformat:
SQL> set numformat 999.99 SQL> SELECT CAST((600.2) AS NUMERIC(28,2)) FROM DUAL; CAST((600.2)ASNUMERIC(28,2)) ---------------------------- 600.20 You could also use TO_CHAR, but use it only to display, for any number arithmetic you should leave the number as it is.
SQL> select to_char(600.2, '000.00') from dual; TO_CHAR ------- 600.20
-1541418 0 The other option that you have, depending on what you're trying to do, is to host the CLR in your application which allows you to more tightly integrate the C# code than is possible by going through COM. You can read an overview of doing this in this MSDN Magazine article.
-38539066 0Simply because b variable is initialized inside the function print.. and c variable is initialised on the global scope. so at this line:
document.write("b is : " + b + "<br />"); you trying to get the value of b variable but ur not calling the function print..
look at this :
var a = 45; var b; var c; function print(){ b = 10; document.write(a); } if(a == 45) { var c = 10; } document.write("a is : " + a + "<br />"); document.write("b is : " + b + "<br />"); document.write("c is : " + c + "<br />"); //--> it will print the following:
a is : 45 b is : undefined c is : 10 because b didn`t change as the function has not yet been called .. but c has changed by the if statement which lies on the global scope.
var a = 45; var c; function print() { b = 10; document.write(a); } print() if (a == 45) { var c = 10; } document.write("a is : " + a + "<br />"); document.write("b is : " + b + "<br />"); document.write("c is : " + c + "<br />"); //-->
-41020612 0 Is there a way to use PouchDB Inspector to inspect a remote device? I am using PouchDB with an Ionic APP, I debug it using Chrome and looking into the console. I would like to inspect the device pouchDB database like I do in chrome with the localhost version with PouchDB Inspector
Is there a way to do this? I do not see anything when I enter the PouchDB Inspector while in Chrome -> Inspect Remote Devices
-7544486 0I solved it! This is the query:
select case when (select min(time(myColumn)) from myTable where time(current_timestamp, 'localtime') < time(myColumn)) is null then (select min(time(myColumn)) from myTable where time(current_timestamp, 'localtime') > time(myColumn)) else (select min(time(myColumn)) from myTable where time(current_timestamp, 'localtime') < time(myColumn)) end Thx Tim & Dave who showed me the way.
-4737686 0 How to generate SQL CLR stored procedure installation script w/o Visual StudioI am working on CLR stored procedure using VS2010. I need to generate standalone deployment script to install this procedure at customer servers. Now I am using Visual Studio which generate such script when I press F5 and try to debug SP on DB server. This script is placed at bin\Debug\MyStoredProcedure.sql file. It looks like this:
USE [$(DatabaseName)] GO IF EXISTS (SELECT * FROM tempdb..sysobjects WHERE id=OBJECT_ID('tempdb..#tmpErrors')) DROP TABLE #tmpErrors GO CREATE TABLE #tmpErrors (Error int) GO SET XACT_ABORT ON GO SET TRANSACTION ISOLATION LEVEL READ COMMITTED GO BEGIN TRANSACTION GO PRINT N'Dropping [dbo].[spMyStoredProcedure]...'; GO DROP PROCEDURE [dbo].[spMyStoredProcedure]; GO IF @@ERROR <> 0 AND @@TRANCOUNT > 0 BEGIN ROLLBACK; END IF @@TRANCOUNT = 0 BEGIN INSERT INTO #tmpErrors (Error) VALUES (1); BEGIN TRANSACTION; END GO PRINT N'Dropping [MyStoredProcedure]...'; GO DROP ASSEMBLY [MyStoredProcedure]; GO IF @@ERROR <> 0 AND @@TRANCOUNT > 0 BEGIN ROLLBACK; END IF @@TRANCOUNT = 0 BEGIN INSERT INTO #tmpErrors (Error) VALUES (1); BEGIN TRANSACTION; END GO PRINT N'Creating [MyStoredProcedure]...'; GO CREATE ASSEMBLY [MyStoredProcedure] AUTHORIZATION [dbo] -- here should be long hex string with assembly binary FROM 0x4D5A90000300000004000000FFFCD21546869732070726F6772616D...000000000000000000 WITH PERMISSION_SET = SAFE; GO IF @@ERROR <> 0 AND @@TRANCOUNT > 0 BEGIN ROLLBACK; END IF @@TRANCOUNT = 0 BEGIN INSERT INTO #tmpErrors (Error) VALUES (1); BEGIN TRANSACTION; END GO PRINT N'Creating [dbo].[spMyStoredProcedure]...'; GO CREATE PROCEDURE [dbo].[spMyStoredProcedure] @reference UNIQUEIDENTIFIER, @results INT OUTPUT, @errormessage NVARCHAR (4000) OUTPUT AS EXTERNAL NAME [MyStoredProcedure].[MyCompany.MyProduct.MyStoredProcedureClass].[MyStoredProcedureMethod] GO IF @@ERROR <> 0 AND @@TRANCOUNT > 0 BEGIN ROLLBACK; END IF @@TRANCOUNT = 0 BEGIN INSERT INTO #tmpErrors (Error) VALUES (1); BEGIN TRANSACTION; END GO IF EXISTS (SELECT * FROM #tmpErrors) ROLLBACK TRANSACTION GO IF @@TRANCOUNT>0 BEGIN PRINT N'The transacted portion of the database update succeeded.' COMMIT TRANSACTION END ELSE PRINT N'The transacted portion of the database update failed.' GO DROP TABLE #tmpErrors GO I am wondering, is it possible to generate such script without Visual Studio? For example, what if I build solution with MSBuild and then generate this script with some tool? I believe, that if I read assembly as byte array and then serialize it to hex string and insert into script template - it could work, but maybe there is some easier standard solution?
Thanks.
-31174994 0 How can i make my sub-menu show and hide when click on main item?$('.slideout-menu li').click( function() { $(this).children('.mobile-sub-menu').show(); }, function() { $(this).children('.mobile-sub-menu').hide(); }); .slideout-menu { position: absolute; top: 100px; left: 0px; width: 100%; height: 100%; background: rgb(248, 248, 248); z-index: 1; } .slideout-menu .slideout-menu-toggle { position: absolute; top: 12px; right: 10px; display: inline-block; padding: 6px 9px 5px; font-family: Arial, sans-serif; font-weight: bold; line-height: 1; background: #222; color: #999; text-decoration: none; vertical-align: top; } .slideout-menu .slideout-menu-toggle:hover { color: #fff; } .slideout-menu ul { list-style: none; font-weight: 300; border-top: 1px solid #dddddd; border-bottom: 1px solid #dddddd; } .slideout-menu ul li { /*border-top: 1px solid #dddddd;*/ border-bottom: 1px solid #dddddd; } .slideout-menu ul li a { position: relative; display: block; padding: 10px; color: #999; text-decoration: none; } .slideout-menu ul li a:hover { background: #aaaaaa; color: #fff; } .slideout-menu ul li a i { position: absolute; top: 15px; right: 10px; opacity: .5; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="slideout-menu"> <ul> <li><a href="#">MANUALS</a> <ul class="mobile-sub-menu"> <li><a href="#">1</a></li> <li><a href="#">1</a></li> <li><a href="#">1</a></li> </ul> </li> <li><a href="#">NEWS</a></li> <li><a href="#">SPARE PART</a></li> <li><a href="#">Photo Gallery</a></li> <li><a href="#">WHERE TO BUY</a></li> <li><a href="#">SUPPORT</a></li> <li><a href="#">EDIT BOOK</a></li> </ul> </div> I add some sub-item under MANUALS main item. What can I do to make its sub-menu hide and show when I click on its parent main item?
I try to write some jQuery code but right now only can hide the item but cannot let it show again. Is something wrong on my jQuery code?
-4569656 0django test client uses default base url:
which makes your test url /accounts/register/ into:
http://testserver/accounts/register/
so you should add 'testserver' in django sites.site model as a base url. maximum recursion depth exceed because django client did'nt find 'testserver' as a domain in sites.site
-19942706 0Your first call to hadoop fs -ls is a relative directory listing, for the current user typically rooted in a directory called /user/${user.name} in HDFS. So your hadoop fs -ls command is listing files / directories relative to this location - in your case /user/Li/
You should be able to assert this by running a aboolute listing and confirm the contents / output match: hadoop fs -ls /user/Li/
As these files are in HDFS, you will not be able to find them on the local filesystem - they are distributed across your cluster nodes as blocks (for real files), and metadata entries (for files and directories) in the NameNode.
-20195 0Steve, I had to migrate my old application the way around, that is PgSQL->MySQL. I must say, you should consider yourself lucky ;-) Common gotchas are:
I hope that helps at least a bit. Have lots of fun playing with Postgres!
-20847884 0You'll find the $locationChangeStart is an event you can listen for to detect for a route change.
Try something like
$rootScope.$on('$locationChangeStart', function (event, next, current) { /* do some verification */ }); $route.reload() will prevent the route change from going through.
The distinction between user clicking back or changing the url etc will not make a difference. As browsers don't reload any resources when you alter the url past the # it's all still contained in your angular logic. This means all these methods should trigger the $locationChangeStart event.
@Jon pointed out that the $route service will definitely be of use to you. the .reload() method will prevent the route change from completing but there is much more you can do with the $route service if you look into it - see documentation.
Problem temporarily solved by commenting a check in atlcore.h :
//#error This file requires _WIN32_WINNT to be #defined at least to 0x0403. Value 0x0501 or higher is recommended.
I know it isnt the right way to do [ editing a file shipped by the IDE ] but did since it may be due to Improper installation.
If anyone come across a permanent fix let me know .
-30868377 0Have you looked at the :not selector?
You can try something like this:
.tab:not(.tab2):hover { background-color: #A9E59E; }
-29032872 0 Instead of doing so much of work as mentioned by Muzikant and like this answer
getSupportActionBar().setDisplayShowHomeEnabled(false); getSupportActionBar().setDisplayShowTitleEnabled(false); getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.WHITE)); LayoutInflater mInflater = LayoutInflater.from(this); View mCustomView = mInflater.inflate(R.layout.action_bar_home, null); getSupportActionBar().setCustomView(mCustomView); getSupportActionBar().setDisplayShowCustomEnabled(true); Toolbar parent =(Toolbar) mCustomView.getParent();//first get parent toolbar of current action bar parent.setContentInsetsAbsolute(0,0);// set padding programmatically to 0dp You have to add only the last two lines of code to solve your problem.
I hope this might help you and anyone else.
UPDATE: After making some research on it, i found that this solution will not work in some cases. The left side gap (HOME or BACK) will be removed with this but the right side gap (MENU) will remain as is. Below is the solution in these cases.
View v = getSupportActionBar().getCustomView(); LayoutParams lp = v.getLayoutParams(); lp.width = LayoutParams.MATCH_PARENT; v.setLayoutParams(lp); Add these four lines to above code, so that the right side gap is also removed from support action bar.
-21092538 0set TEXT_T="myfile.txt" set /a c=1 FOR /F "tokens=1 usebackq" %%i in (%TEXT_T%) do ( set /a c+=1 set OUTPUT_FILE_NAME=output_%c%.txt echo Output file is %OUTPUT_FILE_NAME% echo %%i, %c% )
-25347762 0 The border between these two are getting ever so thinner.
Application servers exposes business logic to a client. So its like application server comprises of a set of methods(not necessarily though, can even be a networked computer allowing many to run software on it) to perform business logic. So it will simply output the desired results, not HTML content. (similar to a method call). So it is not strictly HTTP based.
But web servers passes HTML content to web browsers (Strictly HTTP based). Web servers were capable of handling only the static web resources, but the emergence of server side scripting helped web servers to handle dynamic contents as well. Where web server takes the request and directs it to the script (PHP, JSP, CGI scripts, etc.) to CREATE HTML content to be sent to the client. Then web server knows how to send them back to client. BECAUSE that's what a web server really knows.
Having said that, nowadays developers use both of these together. Where web server takes the request and then calls a script to create the HTML, BUT script will again call an application server LOGIC (e.g. Retrieve transaction details) to fill the HTML content.
So in this case both the servers were used effectively.
Therefore .... We can fairly safely say that in nowadays, in most of the cases, web servers are used as a subset of application servers. BUT theatrically it is NOT the case.
I have read many articles about this topic and found this article quite handy.
-10675121 0I'm not sure to what limitations the author of the python tutorial was referring, but I would guess it has in part to do with the way that method / attribute lookup is implemented in python (the "method resolution order" or MRO). Python uses the C3 superclass linearization mechanism; this is to deal with what is termed to be "The Diamond Problem".
Once you've introduced multiple inheritance into your class hierarchy, any given class doesn't have a single potential class that it inherits from, it only has "the next class in the MRO", even for classes that expect that they inherit from some class in particular.
For example, if class A(object), class B(A), class C(A), and class D(B, C), then the MRO for class D is D->B->C->A. Class B might have been written, probably was, thinking that it descends from A, and when it calls super() on itself, it will get a method on A. But this is no longer true; when B calls super(), it will get a method on C instead, if it exists.
If you change method signatures in overridden methods this can be a problem. Class B, expecting the signature of a method from class A when it calls super, instead gets a method from C, which might not have that signature (and might or might not not implement the desired behavior, from class B's point of view).
class A(object): def __init__(self, foo): print "A!" class B(A): def __init__(self, foo, bar): print "B!" super(B, self).__init__(foo) class C(A): def __init__(self, foo, baaz): print "C!" super(C, self).__init__(foo) class D(B, C): def __init__(self, foo, bar): print "D!" super(D, self).__init__(foo, bar) print D.mro() D("foo", "bar") In this code sample, classes B and C have reasonably extended A, and changed their __init__ signatures, but call their expected superclass signature correctly. But when you make D like that, the effective "superclass" of B becomes C instead of A. When it calls super, things blow up:
[<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <type 'object'>] D! B! Traceback (most recent call last): File "/tmp/multi_inherit.py", line 22, in <module> D("foo", "bar") File "/tmp/multi_inherit.py", line 19, in __init__ super(D, self).__init__(foo, bar) File "/tmp/multi_inherit.py", line 9, in __init__ super(B, self).__init__(foo) TypeError: __init__() takes exactly 3 arguments (2 given) This same sort of thing could happen for other methods as well (if they call super()), and the "diamond" doesn't have to only appear at the root of the class hierarchy.
Based on your example, you are trying to delete all files present within some folder. Instead of iterating over all the files of the folder, and delete each file individually, the better way is to use shutil.rmtree(). It will recursively delete all the files for the given path (similar to rm -r /path/to/folder in unix).
import shutil shutil.rmtree('/path/to/folder')
-38372578 0 Storm 1.0.1 Worker error on submitting topology I am getting the error below (worker.log) when submitting a topology to Storm 1.0.1 (despite the error, the topology does get submitted and appears in the Storm UI):
o.a.s.d.worker [ERROR] Error on initialization of server mk-worker java.lang.OutOfMemoryError: unable to create new native thread at java.lang.Thread.start0(Native Method) ~[?:1.8.0_91] at java.lang.Thread.start(Thread.java:714) ~[?:1.8.0_91] at org.apache.storm.timer$mk_timer.doInvoke(timer.clj:77) ~[storm-core-1.0.1.jar:1.0.1] at clojure.lang.RestFn.invoke(RestFn.java:457) ~[clojure-1.7.0.jar:?] at org.apache.storm.daemon.worker$mk_halting_timer.invoke(worker.clj:244) ~[storm-core-1.0.1.jar:1.0.1] at org.apache.storm.daemon.worker$worker_data$fn__8190.invoke(worker.clj:293) ~[storm-core-1.0.1.jar:1.0.1] at org.apache.storm.util$assoc_apply_self.invoke(util.clj:930) ~[storm-core-1.0.1.jar:1.0.1] at org.apache.storm.daemon.worker$worker_data.invoke(worker.clj:268) ~[storm-core-1.0.1.jar:1.0.1] at org.apache.storm.daemon.worker$fn__8450$exec_fn__2461__auto__$reify__8452.run(worker.clj:611) ~[storm-core-1.0.1.jar:1.0.1] at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_91] at javax.security.auth.Subject.doAs(Subject.java:422) ~[?:1.8.0_91] at org.apache.storm.daemon.worker$fn__8450$exec_fn__2461__auto____8451.invoke(worker.clj:609) ~[storm-core-1.0.1.jar:1.0.1] at clojure.lang.AFn.applyToHelper(AFn.java:178) ~[clojure-1.7.0.jar:?] at clojure.lang.AFn.applyTo(AFn.java:144) ~[clojure-1.7.0.jar:?] at clojure.core$apply.invoke(core.clj:630) ~[clojure-1.7.0.jar:?] at org.apache.storm.daemon.worker$fn__8450$mk_worker__8545.doInvoke(worker.clj:583) [storm-core-1.0.1.jar:1.0.1] at clojure.lang.RestFn.invoke(RestFn.java:512) [clojure-1.7.0.jar:?] at org.apache.storm.daemon.worker$_main.invoke(worker.clj:771) [storm-core-1.0.1.jar:1.0.1] at clojure.lang.AFn.applyToHelper(AFn.java:165) [clojure-1.7.0.jar:?] at clojure.lang.AFn.applyTo(AFn.java:144) [clojure-1.7.0.jar:?] at org.apache.storm.daemon.worker.main(Unknown Source) [storm-core-1.0.1.jar:1.0.1] 2016-07-14 11:48:29.568 o.a.s.util [ERROR] Halting process: ("Error on initialization") java.lang.RuntimeException: ("Error on initialization") at org.apache.storm.util$exit_process_BANG_.doInvoke(util.clj:341) [storm-core-1.0.1.jar:1.0.1] at clojure.lang.RestFn.invoke(RestFn.java:423) [clojure-1.7.0.jar:?] at org.apache.storm.daemon.worker$fn__8450$mk_worker__8545.doInvoke(worker.clj:583) [storm-core-1.0.1.jar:1.0.1] at clojure.lang.RestFn.invoke(RestFn.java:512) [clojure-1.7.0.jar:?] at org.apache.storm.daemon.worker$_main.invoke(worker.clj:771) [storm-core-1.0.1.jar:1.0.1] at clojure.lang.AFn.applyToHelper(AFn.java:165) [clojure-1.7.0.jar:?] at clojure.lang.AFn.applyTo(AFn.java:144) [clojure-1.7.0.jar:?] at org.apache.storm.daemon.worker.main(Unknown Source) [storm-core-1.0.1.jar:1.0.1] Also found this entry in the supervisor.log:
o.a.s.util [WARN] Worker Process ea92e1b7-c870-4b4c-b0a6-00272f27f521:# There is insufficient memory for the Java Runtime Environment to continue. However, "free -m" command suggests enough free memory.
Further messages seem to suggest that the worker fails to start and supervisor.log then starts logging INFO message "{id of worker process} still hasn't started" multiple times.
-5073898 0 Why is my program skipping a prompt in a loop?My code is supposed to continuously loop until "stop" is entered as employee name. A problem I am having is that once it does the calculation for the first employee's hours and rate, it will skip over the prompt for employee name again. Why? (The code is in 2 separate classes, btw) Please help. Here is my code:
package payroll_program_3; import java.util.Scanner; public class payroll_program_3 { public static void main(String[] args) { Scanner input = new Scanner( System.in ); employee_info theEmployee = new employee_info(); String eName = ""; double Hours = 0.0; double Rate = 0.0; while(true) { System.out.print("\nEnter Employee's Name: "); eName = input.nextLine(); theEmployee.setName(eName); if (eName.equalsIgnoreCase("stop")) { return; } System.out.print("\nEnter Employee's Hours Worked: "); Hours = input.nextDouble(); theEmployee.setHours(Hours); while (Hours <0) //By using this statement, the program will not { //allow negative numbers. System.out.printf("Hours cannot be negative\n"); System.out.printf("Please enter hours worked\n"); Hours = input.nextDouble(); theEmployee.setHours(Hours); } System.out.print("\nEnter Employee's Rate of Pay: "); Rate = input.nextDouble(); theEmployee.setRate(Rate); while (Rate <0) //By using this statement, the program will not { //allow negative numbers. System.out.printf("Pay rate cannot be negative\n"); System.out.printf("Please enter hourly rate\n"); Rate = input.nextDouble(); theEmployee.setRate(Rate); } System.out.print("\n Employee Name: " + theEmployee.getName()); System.out.print("\n Employee Hours Worked: " + theEmployee.getHours()); System.out.print("\n Employee Rate of Pay: " + theEmployee.getRate() + "\n\n"); System.out.printf("\n %s's Gross Pay: $%.2f\n\n\n", theEmployee.getName(), theEmployee.calculatePay()); } } } AND
package payroll_program_3; public class employee_info { String employeeName; double employeeRate; double employeeHours; public employee_info() { employeeName = ""; employeeRate = 0; employeeHours = 0; } public void setName(String name) { employeeName = name; } public void setRate(double rate) { employeeRate = rate; } public void setHours(double hours) { employeeHours = hours; } public String getName() { return employeeName; } public double getRate() { return employeeRate; } public double getHours() { return employeeHours; } public double calculatePay() { return (employeeRate * employeeHours); } }
-2718574 0 I have a .NET Application that runs on a server with 16 COM ports, about 11 of which are currently connected to various devices, some RS485, many RS-232. (Diagram here: http://blog.abodit.com/2010/03/home-automation-block-diagram/). Most of these devices are running just 9600 baud, and most don't have very tight timing requirements. I have a thread per device handling receiving and while it runs at normal thread priority, all other non-communication threads run at a lower priority (as you should do for most background tasks anyway). I have had no issues with this setup. And, BTW it also plays music on three sound cards at the same time using high-priority threads from managed code and 1second DSound buffers, all without glitching.
So how tight are your latency requirements, what baud rate and how many serial ports are you trying to serve? The buffer on your UART at most normal baud rates is more than sufficient for garbage collection and much more to delay taking the next byte off it.
GC is not as evil as it is made out to be. On a properly prioritized threaded system with good management of object sizes and lifetimes and sufficient buffering (UARTS/Sound buffers etc.) it can perform very well. Microsoft is also continuously improving it and the .NET Framework 4 now provides background garbage collection. This feature replaces concurrent garbage collection in previous versions and provides better performance. See MSDN.
-2761489 0 SVN - Retrieve history of item "replaced into" existing directoryI created a branch from my SVN trunk. In the branch, another developer deleted a directory, but then readded it with the same files. When I merged the changes from the branch back into the trunk (using TortoiseSVN), this directory had a "replace into" message. I unfortunately merged those in (none of these files in the branch had changed, but since it was deleted and added, it showed up as a change). Now, the history for those files only goes back to the time it was readded in the branch. I have the old history in a tag from before the merge, but it is a pain to have to go to that to get the history.
Is there a way to update the files to get the history back into the trunk? Even if I merge the tag into the trunk, would it actually update the full history? I have a feeling it would just merge any file changes, not the history.
-37652378 0 Local passport authorization on different portsI have a node.js application running on port 5000, where I use passport.js as authorization. I authorize users from a post request, where I use a custom callback:
this.router.post('/member/login', (req, res, next) => { passport.authenticate('local', (err, member, info) => { if (err) res.json(400).json({message: "An error ocurred"}); if (!member) { console.log("No member found!"); return res.status(409).json({message: "No member found!"}) } req.logIn(member, (err) => { if (err) { console.log(err); return res.status(400).json({message: "An error ocurred"}); } return res.json(member); }); })(req, res, next); }); This works fine, but when I develop local I have a frontend Angular2 application, which runs on a different port (4200), so in my development I am not possible to get the authorized user: req.user is undefined. I use express-session to store the authorized user.
When I deploy I bundle both applications up together, so everything works.
Does anyone have a good and simple solution for this issue? Again it's only in development I have this problem.
-1088855 0 Suggestions for uploading very large (> 1GB) filesI know that such type of questions exist in SF but they are very specific, I need a generic suggestion. I need a feature for uploading user files which could be of size more that 1 GB. This feature will be an add-on to the existing file-upload feature present in the application which caters to smaller files. Now, here are some of the options
Please suggest.
Moreover, I've to make sure that this upload process don't hamper the task of other users or in other words don't eat up other user's b/w. Any mechanisms which can be done at n/w level to throttle such processes?
Ultimately customer wanted to have FTP as an option. But I think the answer with handling files programmatically is also cool.
-20961651 0 Mercurial Log Graph ComplicationsOkay - I'm definitely learning a lot about Mercurial and version control systems more and more as I use them, but I'm really confused about why my local copies of one of my repositories (call it project-alpha) on three machines I use (machine 1, machine 2, and machine 3) are different. Notably, they do not share the same tip.
I was hoping somebody could explain this to me, and in addition offer some explanation as to how I may avoid having to "merge" branches altogether (which is how this complication came up in the first place). It would be awesome if somebody could provide an example of how certain circumstances will force me to "merge" on one machine, whereas on another it is perfectly fine without.
For clarification, I am including the
hg log --graph commands for each of the three machines I am using (but only where they begin to differ, since it's a long project I'm working on).
Machine 1
@ changeset: 88:e8aafce5753a | tag: tip | user: Your Name <> | date: Mon Jan 06 15:30:15 2014 -0500 | summary: | o changeset: 87:5d76250aad71 | user: Your Name <> | date: Mon Jan 06 11:32:53 2014 -0500 | summary: | o changeset: 86:4788926f4dc9 |\ parent: 84:caf2a2a127e0 | | parent: 85:682beb5c2a22 | | user: Your Name <> | | date: Thu Jan 02 12:52:17 2014 -0500 | | summary: | | | o changeset: 85:682beb5c2a22 | | parent: 83:bde4e46678d8 | | user: Your Name <> | | date: Thu Jan 02 12:38:45 2014 -0500 | | summary: | | o | changeset: 84:caf2a2a127e0 | | parent: 82:729da698a926 | | user: Your Name <> | | date: Tue Dec 17 15:44:17 2013 -0500 | | summary: | | | o changeset: 83:bde4e46678d8 |/ user: Your Name <> | date: Wed Jan 01 22:20:54 2014 -0500 | summary: | o changeset: 82:729da698a926 | user: Your Name <> | date: Mon Dec 16 12:41:54 2013 -0500 | summary: Machine 2
@ changeset: 88:e8aafce5753a | tag: tip | user: Your Name <> | date: Mon Jan 06 15:30:15 2014 -0500 | summary: | o changeset: 87:5d76250aad71 | user: Your Name <> | date: Mon Jan 06 11:32:53 2014 -0500 | summary: | o changeset: 86:4788926f4dc9 |\ parent: 83:caf2a2a127e0 | | parent: 85:682beb5c2a22 | | user: Your Name <> | | date: Thu Jan 02 12:52:17 2014 -0500 | | summary: | | | o changeset: 85:682beb5c2a22 | | user: Your Name <> | | date: Thu Jan 02 12:38:45 2014 -0500 | | summary: | | | o changeset: 84:bde4e46678d8 | | parent: 82:729da698a926 | | user: Your Name <> | | date: Wed Jan 01 22:20:54 2014 -0500 | | summary: | | o | changeset: 83:caf2a2a127e0 |/ user: Your Name <> | date: Tue Dec 17 15:44:17 2013 -0500 | summary: | o changeset: 82:729da698a926 | user: Your Name <> | date: Mon Dec 16 12:41:54 2013 -0500 | summary: Machine 3
o changeset: 89:e8aafce5753a | tag: tip | user: Your Name <> | date: Mon Jan 06 15:30:15 2014 -0500 | summary: | o changeset: 88:5d76250aad71 | user: Your Name <> | date: Mon Jan 06 11:32:53 2014 -0500 | summary: | o changeset: 87:4788926f4dc9 |\ parent: 83:caf2a2a127e0 | | parent: 85:682beb5c2a22 | | user: Your Name <> | | date: Thu Jan 02 12:52:17 2014 -0500 | | summary: | | +---@ changeset: 86:eab05f7f7ab6 | |/ parent: 83:caf2a2a127e0 | | parent: 85:682beb5c2a22 | | user: Your Name <> | | date: Thu Jan 02 12:52:31 2014 -0500 | | summary: | | | o changeset: 85:682beb5c2a22 | | user: Your Name <> | | date: Thu Jan 02 12:38:45 2014 -0500 | | summary: | | | o changeset: 84:bde4e46678d8 | | parent: 82:729da698a926 | | user: Your Name <> | | date: Wed Jan 01 22:20:54 2014 -0500 | | summary: | | o | changeset: 83:caf2a2a127e0 |/ user: Your Name <> | date: Tue Dec 17 15:44:17 2013 -0500 | summary: | o changeset: 82:729da698a926 | user: Your Name <> | date: Mon Dec 16 12:41:54 2013 -0500 | summary: Let me first start off by saying that I understand there are some differences simply due to the fact that some changes were pushed on some machines and pulled on others. Machine 1 and 2 are the primary ones I use, and it clearly doesn't differ too much. What I'm concerned about is Machine 3, which currently has 3 heads, and an additional changeset (89 instead of 88). I'm a bit confused as to what is happening, how I can fix this, and I would appreciate knowing exactly what I did to cause this so that I may avoid this type of behavior next time. Thanks in advance!
-9752320 0 Repeatedly check the login status of the user?I would like to regularly check the status of the logged in user. My method is as follows but I am unsure as to whether this is the best way to go about it.
window.fbAsyncInit=function(){ FB.init({ appId:'123', status:true, cookie:true, xfbml:true, channelUrl:'file', oauth:true }); setInterval(function(){ FB.getLoginStatus(function(a){ // do something },300000); }); } I am aware of the 'subscribe' functions but I am not really sure what they are for. If these are suitable then I will consider using them but I need to have a clearer picture of what they do and how often. I have read the documentation and they simply say that it attaches a handler. This is not very detailed!! What does it attach a handler to!!??
Additionally, if I want to call FB.getLoginStatus outside of the 'fbAsyncInit' function, is this possible?
Any help much appreciated.
-15522958 0 Google Plus Login API not working on production serverI have implemented the google plus api on development server and it works fine. I used the same code on production server. But after requesting the permission it takes a long time to return to my site and login.
Can anyone please let me know what might be the cause. I have used oauth2.
Below is the code I am using
<?php session_start(); require_once 'googleplus/src/Google_Client.php'; require_once 'googleplus/src/contrib/Google_Oauth2Service.php'; class Webpage_UserGPlusLogin extends Webpage { public function __construct() { $temp_redirect = $_SESSION['RETURN_URL_AFTERLOGIN']; $this->title = 'User Account'; $client = new Google_Client(); $client->setApplicationName(WEBSITE_NAME); $client->setClientId(GOOGLE_PLUS_CLIENT_ID); // Client Id $client->setClientSecret(GOOGLE_PLUS_CLIENT_SECRET); // Client Secret $client->setRedirectUri(GOOGLE_PLUS_REDIRECT_URI); // Redirect Uri set while creating API account $client->setDeveloperKey(GOOGLE_PLUS_DEVELOPER_KEY); // Developer Key $oauth2 = new Google_Oauth2Service($client); if (isset($_GET['code'])) { $client->authenticate($_GET['code']); $_SESSION['token'] = $client->getAccessToken(); $redirect = GOOGLE_PLUS_REDIRECT_URI; header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL)); // Redirects to same page return; } if (isset($_SESSION['token'])) { $client->setAccessToken($_SESSION['token']); } if (isset($_REQUEST['logout'])) { unset($_SESSION['token']); $client->revokeToken(); } if(!isset($_SESSION['email_address_user_account'])) // Check if user is already logged in or not { if ($client->getAccessToken()) { $user = $oauth2->userinfo->get(); // Google API call to get current user information $email = filter_var($user['email'], FILTER_SANITIZE_EMAIL); $img = filter_var($user['picture'], FILTER_VALIDATE_URL); $googleuserid = $user['id']; $given_name = $user['given_name']; $family_name = $user['family_name']; // The access token may have been updated lazily. $_SESSION['token'] = $client->getAccessToken(); // If email address is present in DB return user data else insert user info in DB $this->result = UserAccount::gplus_sign_up($email, $googleuserid, $given_name, $family_name); // Create new user object. $this->user_account = new UserAccount($this->result['id'],$this->result['email_address'],$this->result['password'],$this->result['confirmation_code'],$this->result['is_confirmed'], $this->result['first_name'], $this->result['last_name']); $_SESSION['gplus_email_address'] = $email; $_SESSION['gplus_first_name'] = $given_name; $_SESSION['gplus_last_name'] = $family_name; $_SESSION['gplus_id'] = $googleuserid; $_SESSION['gplus_profile_pic'] = $img; $_SESSION['email_address_user_account'] = $email; } else { $authUrl = $client->createAuthUrl(); } } if(isset($temp_redirect)) header("Location:".$temp_redirect); else header("Location:/"); } } Thanks in advance
-12476828 0 Sony Smartwatch widget refreshI have a Problem with my Sony SmartWatch App. I've developed a widget with control, but after the App is installed by users on the device the scheduled refresh task of the widget starts automatically. This means the refresh task is running all the time, even if the user did not turn on SmartWatch Display or start the widget. This drains the battery. If I go to the widget screen and then turn the display from off, the scheduled Task stops like expected. But if I don't do this the task is running and running and running.... How can I detect if the Display is on and the widget is running?
Thank you very much!
P.S.: It makes no difference if the "Activate Widget" preference is checked or not....
EDIT: I've found out that the widget sourcecode does not fire if I uncheck the "Display as Widget" Checkbox in preferences. This means if the refresh schedule is running and I uncheck this box, the onDestroy is never called and so the cancel schedule also not....
-31753262 0 How does calling this function (without a definition) work?So I am trying to get to grips with someone's code (and cannot contact them) and I do not understand why they do this. They call a function in main like this:
LOG_AddFunction(); This function is defined in a header file like this:
#define LOG_AddFunction() LOG_Add(LOG_TYPE_NORMAL, "%s()", __FUNCTION__) Then LOG_Add is defined in the same header file:
extern int LOG_Add(LOG_TYPE eType, const char *pcText, ...); There does not seem to be any ultimate definition of the LOG_AddFunction function and I do not understand why the code calls it. Can someone shed some light on this please?
-6020209 0I believe the problem is that with a key of lang.mail.layout.greeting, Freemarker treats each part between the .s as a hash i.e. a container variable that can have subvariables. So it attempts to get the object referenced by lang from the data-model and then attempts to get the variable referenced by mail from lang. In your case, however, there is no such object, hence the error.
The documentation has this to say about variable names:
In this expression the variable name can contain only letters (including non-Latin letters), digits (including non-Latin digits), underline (_), dollar ($), at sign (@) and hash (#). Furthermore, the name must not start with digit.
You might make use of the alternative syntax to get data from a hash (as long as the expression evaluates to a string)
<p>${lang["mail.layout.greeting"]} ${user.firstname},</p>
-6562248 0 How to optimize full text searches? I know there are a lot of question already on this subject, but I needed more specific information. So here goes:
LIKE %$str% and full-text search?LIKE %$str% and full-text search implemented and use the optimal one dynamically?Here's a general approach:
data.frame(sapply(unique(names(tempList)), function(name) do.call(c, tempList[names(tempList) == name]), simplify=FALSE) )
-16339861 0 Application failed when changing user cession windows 7 I have an application witch run on local admin account with MFC and user interface. When i change logon windows 7 cession, Application failed.
How can i keep the application alive when changing windows cession?
Thanks for your help!
(defclass locatable () ((zone :accessor zone :initform nil) (locator :initarg :locator :initform (error "Must supply a locator parameter for this class.") :allocation :class :accessor locator))) The slot locator is shared in the class. It will be allocated somehow in the class object. The DEFCLASS form creates this class object. Thus the slot locator usually will be initialized when the class object is created and initialized. Way before the first instance of that class is created.
LispWorks Backtrace
CL-USER 50 : 1 > :b Call to CLOS::CLASS-REDEFINITION-LOCK-DEBUGGER-WRAPPER Call to INVOKE-DEBUGGER Call to ERROR Call to (METHOD CLOS::COMPUTE-CLASS-SLOT-CONSES (STANDARD-CLASS)) Call to (METHOD SHARED-INITIALIZE :AFTER (STANDARD-CLASS T)) ; <-- Call to CLOS::ENSURE-CLASS-USING-CLASS-INTERNAL Call to (METHOD CLOS:ENSURE-CLASS-USING-CLASS (CLASS T)) Call to CLOS::ENSURE-CLASS-WITHOUT-LOD Call to LET Call to LET Call to EVAL Call to CAPI::CAPI-TOP-LEVEL-FUNCTION Call to CAPI::INTERACTIVE-PANE-TOP-LOOP Call to MP::PROCESS-SG-FUNCTION As you see SHARED-INITIALIZE is called on the class object, which then initializes the shared slots.
I also don't think calling error like this should be done in user code. You might find a better way to check for missing initargs.
how do i move (not revert) a draggable div to another div which is a droppable when i do an action? for example how do i move a draggable div from div-A to div-B if i click a button?
-24491781 0<script type="text/javascript"> $(document).ready(function() { $("#date, #date2,#date3,#date4").datepicker(); $("#date,#date2,#date3,#date4 ").datepicker("option", "dateFormat", "yy/mm/dd"); var d = new Date(); var todaysM = d.getDate() + "/" + (d.getMonth() + 1) + "/" + d.getFullYear(); var todaysM = d.getFullYear()+ "/" + (d.getMonth() + 1) + "/" + d.getDate(); if ($("#date,#date2,#date3").val() == "") { $("#date,#date2,#date3").val(todaysM); } }); </script>
-38845763 0 Why get error from kendo ui when run the asp.net mvc application? I'm beginner in asp.net mvc use the kendo UI and add it to my project but when i run the my application get this error:
How can i solve that problem?thanks.
Is there away to specify the groupby call to use the group name in the apply lambda function.
For instance, if I iterate through groups I can get the group key via the following tuple decomposition:
for group_name, subdf in temp_dataframe.groupby(level=0, axis=0): print group_name is there away to get the group name in the apply function, such as:
temp_dataframe.groupby(level=0,axis=0).apply(lambda group_name, subdf: foo(group_name, subdf) How can I get the group name as an argument for the apply lambda function?
Thanks!
-13845157 0decimal index = SeriesList.SelectMany(p => p.Childs) .FirstOrDefault(c => c.key == "aa").Value; But keep in mind, that child with provided key should exist in list, otherwise you will get an exception. I think better to find child first, and then if child exist, get its value:
Childs child = SeriesList.SelectMany(p => p.Childs) .FirstOrDefault(c => c.key == "aa"); if (child != null) index = child.Value;
-9795194 0 MSDN has information on how to add items to a contextmenustrip
Sample Code:
// Declare the ContextMenuStrip control. private ContextMenuStrip fruitContextMenuStrip; public Form3() { // Create a new ContextMenuStrip control. fruitContextMenuStrip = new ContextMenuStrip(); // Attach an event handler for the // ContextMenuStrip control's Opening event. fruitContextMenuStrip.Opening += new System.ComponentModel.CancelEventHandler(cms_Opening); // Create a new ToolStrip control. ToolStrip ts = new ToolStrip(); // Create a ToolStripDropDownButton control and add it // to the ToolStrip control's Items collections. ToolStripDropDownButton fruitToolStripDropDownButton = new ToolStripDropDownButton("Fruit", null, null, "Fruit"); ts.Items.Add(fruitToolStripDropDownButton); // Dock the ToolStrip control to the top of the form. ts.Dock = DockStyle.Top; // Assign the ContextMenuStrip control as the // ToolStripDropDownButton control's DropDown menu. fruitToolStripDropDownButton.DropDown = fruitContextMenuStrip; // Create a new MenuStrip control and add a ToolStripMenuItem. MenuStrip ms = new MenuStrip(); ToolStripMenuItem fruitToolStripMenuItem = new ToolStripMenuItem("Fruit", null, null, "Fruit"); ms.Items.Add(fruitToolStripMenuItem); // Dock the MenuStrip control to the top of the form. ms.Dock = DockStyle.Top; // Assign the MenuStrip control as the // ToolStripMenuItem's DropDown menu. fruitToolStripMenuItem.DropDown = fruitContextMenuStrip; // Assign the ContextMenuStrip to the form's // ContextMenuStrip property. this.ContextMenuStrip = fruitContextMenuStrip; // Add the ToolStrip control to the Controls collection. this.Controls.Add(ts); //Add a button to the form and assign its ContextMenuStrip. Button b = new Button(); b.Location = new System.Drawing.Point(60, 60); this.Controls.Add(b); b.ContextMenuStrip = fruitContextMenuStrip; // Add the MenuStrip control last. // This is important for correct placement in the z-order. this.Controls.Add(ms); } Or another link to ContextMenuStrip in C#
-36108966 0You need to put things together differently to accomplish your goal. You can't just replace ++ with :. Try this:
toList t = toListPlus t [] toListPlus :: Tree a -> [a] -> [a] toListPlus t xs should produce toList t ++ xs, but implemented with recursive calls to toListPlus, not using ++ or toList. Let's work through it. The base case is easy:
toListPlus Empty xs = xs The recursive case isn't too bad either. We want to convert the left subtree to a list, sticking other stuff on after:
toListPlus (Node v l r) xs = toListPlus l ??? What comes after? The root, and then the result of converting the right subtree, and then whatever gets tacked on:
toListPlus (Node v l r) xs = toListPlus l (v : toListPlus r xs) This function uses an implicit stack to keep track of the remaining work. This is probably the most efficient way to do it. If you wanted, you could use a zipper-style representation to make the stack explicit.
How does this solution relate to the one leftaroundabout described? Well, they're actually the same. We can see that by shifting the list argument over:
toListPlus Empty = \xs -> xs toListPlus (Node v l r) = \xs -> toListPlus l (v : toListPlus r xs) = toListPlus l . (v :) . toListPlus r
-20743863 0 my bad, I was doing it wrong!!
<?php $risk_numbers = array( '2' => '20', '3' => '23', '10' => '22', '11' => '24', '12' => '25', '13' => '27', '21' => '26', ); foreach($risk_numbers as $description => $other) { if($values[$description]['value'] == 'No'){echo $values[$description]['description'].'<br/>';} if($values[$other]['label'] == 'Other' && $values[$other]['value'] != ''){echo $values[$other]['value']; echo '<br/>';} } ?>
-12900581 0 If I understand your question rightly, it's fairly straightforward.
First, 'flatten' the list using a generator expression: (item for sublist in combs for item in sublist).
Then, iterate over the flattened list. For each item, you either add an entry to the dict (if it doesn't already exist), or add one to the value.
d = {} for key in (item for sublist in combs for item in sublist): try: d[key] += 1 except KeyError: # I'm not certain that KeyError is the right one, you might get TypeError. You should check this d[key] = 1 This technique assumes all the elements of the sublists are hashable and can be used as keys.
-35244459 0Well, question is not fresh, but this situation may still become a piece of pain. You may use toJSON or toObject method to get normal, iterable object. Just like this:
media = media.toJSON() Object.keys(media.audio).forEach(...) See this post for details about toJSON an toObject
You can use a CursorLoader for this. It assumes also that you have a ContentProvider as your data source for the application, which I will not discuss here but you can learn about them in this post if you want.
To sync the database data to your ListView, you will have to do two things:
To implement the LoaderManager just override the three required methods. One is used to setup your Cursor, one will feed the results to your Adapter. From then on, assuming your ContentProvider properly notifies any URIs of changes, you will notice those changes in the Adapter. Here is a snippet of the Loader code:
public class AccountsFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>{ private static final int MY_LOADER = 0; @Override public void onActivityCreated() { super.onActivityCreated(); getLoaderManager.initLoader(MY_LOADER, null, this); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { switch(id){ case MY_LOADER: return new CursorLoader( getActivity(), MY_URI, MY_COLUMNS, null, null, null ); default: throw new UnsupportedOperationException("Unknown loader id: " + id); } } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { switch(loader.getId()){ case MY_LOADER: mAdapter.swapCursor(datA); default: throw new UnsupportedOperationException("Unknown loader id: " + loader.getId()); } } @Override public void onLoaderReset(Loader<Cursor> loader) { switch(loader.getId()){ case MY_LOADER: mAdapter.swapCursor(null); break; default: throw new UnsupportedOperationException("Unknown loader id: " + loader.getId()); } } } I learned much of this from a Udacity course that teaches you a lot about Android from the bottom up, and if you are looking for a complete overview I think it is very much worth your time.
-19449750 0Well I ran into the same problem few months back and the way I fixed this was by presenting mmvc as modal view controller. Please try replacing your else with something like this:
[presentingViewController dismissModalViewControllerAnimated:NO]; GKMatchRequest *request = [[[GKMatchRequest alloc] init] autorelease]; request.minPlayers = minPlayers; request.maxPlayers = maxPlayers; request.playersToInvite = pendingPlayersToInvite; GKMatchmakerViewController *mmvc = [[[GKMatchmakerViewController alloc] initWithMatchRequest:request] autorelease]; mmvc.matchmakerDelegate = self; [presentingViewController presentModalViewController:mmvc animated:YES]; self.pendingInvite = nil; self.pendingPlayersToInvite = nil; Also, there seem to be an issue with your authentication. Your method should use new mechanism for player authentication like:
- (void)authenticateLocalUser { if (!gameCenterAvailable) return; NSLog(@"Authenticating local user..."); if ([GKLocalPlayer localPlayer].authenticated == NO) { // Use new authentication mechanism if the iOS version is 6.0 or above if ([[UIDevice currentDevice].systemVersion compare:@"6.0" options:NSNumericSearch] != NSOrderedAscending) { [[GKLocalPlayer localPlayer] setAuthenticateHandler:^(UIViewController *vc, NSError *error) { if (error) NSLog(@"Error in authenticating User - %@", [error localizedDescription]); else if (vc) { AppDelegate *appDel = (AppDelegate *)[UIApplication sharedApplication].delegate; [appDel.navigationController presentModalViewController:vc animated:YES]; } }]; } else [[GKLocalPlayer localPlayer] authenticateWithCompletionHandler:nil]; } else { NSLog(@"Already authenticated!"); } }
-31813486 0 You actually need to include a fragment (NOT the Relative Layout) to your layout like so:
<fragment android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="match_parent" class="com.google.android.gms.maps.SupportMapFragment" />
-3941261 0 "Why is the compiler not allowed to see"
I don't have an answer for safe bool, but I can do this bit. It's because a conversion sequence can include at most 1 user-defined conversion (13.3.3.1.2).
As for why that is - I think someone decided that it would be too hard to figure out implicit conversions if they could have arbitrarily many user-defined conversions. The difficulty it introduces is that you can't write a class with a conversion, that "behaves like built-in types". If you write a class which, used idiomatically, "spends" the one user-defined conversion, then users of that class don't have it to "spend".
Not that you could exactly match the conversion behaviour of built-in types anyway, since in general there's no way to specify the rank of your conversion to match the rank of the conversion of the type you're imitating.
Edit: A slight modification of your first version:
#define someCondition true struct safe_bool_thing { int b; }; typedef int safe_bool_thing::* bool_type; bool_type safe_bool( const bool b ) { return b ? &safe_bool_thing::b : 0; } class MyTestableClass { public: operator bool_type () const { return safe_bool( someCondition ); } private: bool operator==(const MyTestableClass &rhs); bool operator!=(const MyTestableClass &rhs); }; int main() { MyTestableClass a; MyTestableClass b; a == b; } a == b will not compile, because function overload resolution ignores accessibility. Accessibility is only tested once the correct function is chosen. In this case the correct function is MyTestableClass::operator==(const MyTestableClass &), which is private.
Inside the class, a == b should compile but not link.
I'm not sure if == and != are all the operators you need to overload, though, is there anything else you can do with a pointer to data member? This could get bloated. It's no better really than Bart's answer, I just mention it because your first attempt was close to working.
I'm facing an issue with the Jenkins Violations plug-in when trying to access my source code files from the UI. The paths are relative to the root of the volume :S. So, if my .cs file is in C:\CMSRootFolder\MySolution\MyProject\Namespace\SourceCode.cs, then the link in Jenkins is: http://<jenkins_server>/job/<job_name>/violations/file/CMSRootFolder/MySolution/Namespace/SourceCode.cs/
This happens even after setting the faux project path to "C:\CMSRootFolder\MySolution", and no matter what I try to set in the source code patterns. I think this might be a bug in the plug-in, but I would like to know if there is any workaround.
Thanks.
-35630503 0This is my solution:
foreach ($arr1[0] as $key => $entry) { $arr1[0][$key][$arr1[0][$key]["Str1"]] = $arr2[0][$entry["Str1"]]; } This produces the following output:
[ [ { "Str1":"ABC", "Str2":"Some Value", "Str3":"Something", "ABC":"Hello" }, { "Str1":"DEF", "Str2":"Another Value", "Str3":"Test", "DEF":"Test" }, { "Str1":"GHI", "Str2":"NULL", "Str3":"Blah", "GHI":"Something" } ] ]
-25477450 0 You need to assign your fields actual objects. If you look at Quiz.theContentManager, you'll notice that you never actually assign it a value. You can fix this by passing the ones in from Game1. For instance, Game1 should look like this:
public class Game1 : Microsoft.Xna.Framework.Game { Quiz quiz; protected override void LoadContent() { quiz.LoadContent(Content); } protected override void Update(GameTime gameTime) { quiz.Update(gameTime); } protected override void Draw(GameTime gameTime) { quiz.Draw(spriteBatch, gameTime); } } Then your Quiz class should look like this (note that you don't need class fields for any of the XNA stuff with this approach):
public class Quiz { QuizQuestion no1 = new QuizQuestion(); public void LoadContent(ContentManager content) { no1.LoadContent(content); } public void Update(GameTime gameTime) { // Perform whatever updates are required. } public void Draw(SpriteBatch spriteBatch, GameTime gameTime) { // Draw whatever } }
-7896946 0 Taghrid, It looks like you're getting a Stackoverflow error. This indicates that somewhere in your code you have Infinite recursion. It looks like it's VoiceAlert and ReadyToSpeak functions that keep calling one another. Are you sure the package your using, org.androiddev.android.test is of good quality? Are you using a release version of it?
-4821017 0 EDMX new column generates error on ToList() callWe've added a new column to a database table. The column is defined as follows:
Name: DisplayAsSoldOut Type: Boolean NOT NULLABLE Default Value: 0 We've refreshed our EDMX data model and the new column appears just fine. We are on an ASP.NET 4.0 platform using C#.
We have a class defined as PagedList which inherits from List and implenents an interface IPagedList
Within the PagedList we have the following method:
protected void Initialize(IQueryable<T> source, int index, int pageSize, int? totalCount) { if (index < 0) { throw new ArgumentOutOfRangeException("PageIndex cannot be below 0."); } if (pageSize < 1) { throw new ArgumentOutOfRangeException("PageSize cannot be less than 1."); } if (source == null) { source = new List<T>().AsQueryable(); } if (!totalCount.HasValue) { TotalItemCount = source.Count(); } PageSize = pageSize; PageIndex = index; if (TotalItemCount > 0) { PageCount = (int)Math.Ceiling(TotalItemCount / (double)PageSize); } else { PageCount = 0; } HasPreviousPage = (PageIndex > 0); HasNextPage = (PageIndex < (PageCount - 1)); IsFirstPage = (PageIndex <= 0); IsLastPage = (PageIndex >= (PageCount - 1)); if (TotalItemCount > 0) { AddRange(source.Skip((index) * pageSize).Take(pageSize).ToList()); } } When we reach the following line:
{ AddRange(source.Skip((index) * pageSize).Take(pageSize).ToList()); } we receive the following Exception ...
Type: System.Data.EntityCommandExecutionException Inner Exception: "Invalid column name 'DisplayAsSoldOut'." I've tried searching for this type of exception but to no avail. The column appears in the EDMX dataset just fine. I even created a small throwaway program and imported the EDMX to do a simple read from the database and it worked fine. Has anyone run across something similar?
I apologize for the lengthy post but wanted to present as much info as I could.
-17026940 0 Is there a difference between "and" vs "and then" in an IF statementI'm learning Ada by fixing bugs and reading code. I've noticed some if statements that are ganged with "and" and others with "and then". similarly, there is "or" and other places there is "or else". A co-worker says it's just syntactic sugar and makes no difference. I wonder if he's right?
-23583190 0 Echo Canceller Android API level 10I'm building an android audio app that has to support the API level 10 and I have Larsen effect problems. My android app streams the audio to a java app that outputs the sound.
I found the AcousticEchoCanceller of android but it is only available from the API level 16.
Is there a way to do that without this class ? Or could I do it on the java app ?
Thank's
Lukas
-5012134 0You should use the Feedburner Awareness API. For instance you can retrieve the URL feedburner.google.com/api/awareness/1.0/GetFeedData?uri=http://feeds.feedburner.com/phpclassesblog-xml and then parse the returned XML to extract the relevant statistics.
-2320534 0There are a number of solutions. You should not assume that everyone has Java installed. You can use web start for instance which will help with the setup. You can find some advice here.
More info about web start here.
-25888817 0 Android Bluetooth status 133 in onCharacteristicwriteI'm new to Android and now doing a simple app that requires writing some data into a peripheral device.
Actually nothing goes wrong in a Samsung GT-S7272C device. But when I switch to Sony LT29i, there will always be a status 133 when I'm trying to write into a certain characteristic. I will give out some brief code.
BluetoothGattService syncService = gatt.getService(SYNC_DATA_SERVICE); BluetoothGattCharacteristic tChar = syncService.getCharacteristic(SYNC_TIME_INPUT_CHAR); if (tChar == null) throw new AssertionError("characteristic null when sync time!"); int diff = /*a int*/; tChar.setValue(diff, BluetoothGattCharacteristic.FORMAT_SINT32, 0); gatt.writeCharacteristic(tChar); and the onCharacteristicWrite function:
@Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { Log.d(TAG, String.format("Sync: onCharWrite, status = %d", status)); try { if (status != BluetoothGatt.GATT_SUCCESS) throw new AssertionError("Error on char write"); super.onCharacteristicWrite(gatt, characteristic, status); if (characteristic.getUuid().equals(SYNC_TIME_INPUT_CHAR)) { BluetoothGattService syncService = gatt.getService(SYNC_DATA_SERVICE); BluetoothGattCharacteristic tChar = syncService.getCharacteristic(SYNC_HEIGHT_INPUT_CHAR); if (tChar == null) throw new AssertionError("characteristic null when sync time!"); tChar.setValue(/*another int*/, BluetoothGattCharacteristic.FORMAT_SINT32, 0); gatt.writeCharacteristic(tChar); } else if { ... } } catch (AssertionError e) { ... } Writing into first characteristic has nothing wrong and control will reach the onCharacteristicWrite and enter the first if statement with status 0, which means success. Problem is the second writing action in the if statement, which will also trigger onCharacteristicWrite function but yield a status 133, which cannot be found in the official site. Then the device disconnect automatically.
I've confirmed that the data type and the offset are all correct. And because in another device it works really nice, I think there might be some tiny differences of the bluetooth stack implementation between different device that I should do something more tricky to solve this problem.
I've search for result for a long time. Some results lead me to the C source code(Sorry, I will post the link below because I don't have enough reputation to post more than 2 links), but I can only find that 133 means GATT_ERROR there, which is not more helpful than just a 133. I've also found a issue in google group, discussing some familiar questions, but I failed to find a solution here.
I'm a little bit sad because, if it is something wrong with the C code, even if I can locate what's wrong, I still have no way to make it right in my own code, right?
I hope that someone has the familiar experience before and may give me some suggestions. Thanks a lot!
links:
C source code: https://android.googlesource.com/platform/external/bluetooth/bluedroid/+/android-4.4.2_r1/stack/include/gatt_api.h
Issue: https://code.google.com/p/android/issues/detail?id=58381
I am having trouble with multiple clicks being registered in jQuery when only one element has been clicked. I have read some other threads on Stack Overflow to try and work it out but I reckon it is the code I have written. The HTML code is not valid, but that is caused by some HTML 5 and the use of YouTube embed code. Nothing that affects the click.
The jQuery, triggered on document.ready
function setupHorzNav(portalWidth) { $('.next, .prev').each(function(){ $(this).click(function(e){ var target = $(this).attr('href'); initiateScroll(target); console.log("click!"); e.stopPropagation(); e.preventDefault(); return false; }); }); function initiateScroll(target) { var position = $(target).offset(); $('html, body').animate({ scrollLeft: position.left }, 500); } } Example HTML
<nav class="prev-next"> <a href="#countdown-wrapper" class="prev">Prev</a> <a href="#signup-wrapper" class="next">Next</a> </nav> In Firefox one click can log a "Click!" 16 times! Chrome only sees one, but both browsers have shown problems with the above code.
Have I written the code wrongly or is there a bug?
-- Some extra info ------------------------------------------
setupHorzNav is called by another function in my code. I have tested this and have confirmed it is only called once on initial load.
if ( portalWidth >= 1248 ) { wrapperWidth = newWidth * 4; setupHorzNav(newWidth); } else { wrapperWidth = '100%'; } There are mutiple instances of nav 'prev-next'. All target different anchors. All are within the same html page.
<nav class="prev-next"> <a href="#video-wrapper" class="prev">Prev</a> </nav>
-13171436 0 put this in you viewDidLoad, and i think you will get what you need.
UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"yourTitle" style:UIBarButtonItemStylePlain target:nil action:nil]; self.navigationItem.backBarButtonItem = backBarButtonItem; [backBarButtonItem release];
-24920553 0 Create a public bool variable and check against it for if the analytics have been sent previously.
-2829829 0You should be able to use the CASE construct, and it would look something like this:
select order.foo, case when sale.argle is null then 'N' else 'Y' end from order left join sale on order.product_number = sale.product_number;
-2497710 0 Assuming you have interop, it would be like the below. Note xlValidateWholeNumber, that can be changed to xlValidateDecimal (and the subsequent Formula1 below would need to be a decimal) for decimals).
private void SetValidationBetweenNumbers() { Microsoft.Office.Tools.Excel.NamedRange cellThatNeedsValidating = this.Controls.AddNamedRange(this.Range[""A1"", missing], "cellThatNeedsValidating"); cellThatNeedsValidating.Validation.Add( Excel.XlDVType.xlValidateWholeNumber, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlBetween, "1", "=B1"); }
-37053732 0 In adition to the break statement to exit a for or [do] while loop, the use of goto is permitted to break out nested loops, e.g.:
for (i=0; i<k; i++) { for (j=0; j<l; j++) { if (someCondition) { goto end_i; } } } end_i:
-13290350 0 You can manage privileges at the column-level: http://dev.mysql.com/doc/refman/5.1/en/grant.html.
-36637021 0 Width - fifty per cent for table cell display breaks into seperate lineI am trying to display a panel that displays information in a tabular fashion as, 
My pluker code is here. Now, i use display:table-row to put NAME label and value My Venue in one place. When i give 50% width to the table-cell display, it breaks into next line as,
I am able to fix it by making the width as 49% for table-cell display.
I am curious why does 50% width break it into a different line, since table display doesn't have any margin.
Using the following program I'm trying to insert all the filenames listed in a folder on ftp server into a SQL table.
While Writing to table I'm getting an error
c# cannot access a disposed object. object name 'system.net.sockets.networkstream'
reader.ReadToEnd() Writing the whole stream where I want one by one filename.
namespace Examples.System.Net { public class WebRequestGetExample { public static void Main() { FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://myftpaddress.com/0708/"); request.Method = WebRequestMethods.Ftp.ListDirectory; request.Credentials = new NetworkCredential("vish10", "MyPasswd"); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); StreamReader reader = new StreamReader(responseStream); Console.WriteLine(reader.ReadToEnd()); SqlConnection sqlConnection1 = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DMSTG;Data Source=."); SqlCommand cmd = new SqlCommand(); cmd.CommandText = @"Insert into FTPfileList0708Folder values('" + reader.ReadToEnd().ToString() + "')"; cmd.Connection = sqlConnection1; sqlConnection1.Open(); cmd.ExecuteNonQuery(); sqlConnection1.Close(); Console.WriteLine("Directory List Complete, status {0}", response.StatusDescription); reader.Close(); response.Close(); } } }
-40079029 0 how to prompt a pop up message right after user input in jtextfield I am new in Java and now trying to develop a simple program to support my research findings. In this program, I'll be displaying randomized images and users were to enter single integer in jtextfield provided. The users are required to count and answer the number of animals displayed. Since I want to develop the program as simple as possible, I imagine my tool will be straight forward.
Question 1: There will be a JTextField provided for user to input their answer. Is there any coding that could restrict user input right after a single integer(between 1-6) has been keyed in the box? As I need my program to be straight forward and easy to understand, I do not want user to click on any button so as to lead them to next image. May I know is there any way to restrict user input and lead the program to next image right after user enter a number without clicking any button? Question 1
Question 2: Right after the user key in the single integer answer, I would like to prompt a simple popup that includes a praise to user such as "Well done". Since the JOptionPane I'll be using will contain two buttons: "OK" and "cancel", may I know how to make sure the program leads to next randomized image after user click on "OK" button. Question 2
Question 3: Is there any ways to keep the input cursor for typing just in the JTextField provided? This is because I want the program as simple as possible that user do not need to waste their time moving their mouse and click at the jtextfield to start entering their answer. I want my program to work like: everytime user enter a single integer, a pop up message appear, user click "OK" and lead to next randomized image. At the next image, user just have to enter the answer without moving the cursor to click at the jtextfield(Example:By referring to image question 2, after user click "OK", how to make the program leads to next randomized image as image question 1). May I know is there any way to develop the program in such way?
This is my code.
package Project; import java.awt.*; import java.awt.event.*; import java.sql.*; public class Task implements KeyListener, ActionListener { static JFrame frame = new JFrame("FYP"); JPanel content = new JPanel(); JPanel content2 = new JPanel(); JLabel lbl2 = new JLabel(); JLabel labelUsername = new JLabel(""); JTextField textField = new JTextField(); long StartA=System.currentTimeMillis(); //connectionMSAccess Connection c; Statement s; ResultSet r; int sum=0; int Error=0; int total_test=0; static String inputID; static int index = 0; String[] imgFileHP = {"1.jpg","2.jpg","3.jpg","4.jpg","5.jpg","6.jpg","7.jpg","8.jpg","9.jpg","10.jpg", "11.jpg","12.jpg","13.jpg","14.jpg","15.jpg","16.jpg","17.jpg","18.jpg","19.jpg","20.jpg"}; String[] imgNo = {"5","5","4","6","4","6","3","4","5","3","5","4","3","5","4","5","6","4","4","6"}; List <String> pictureFileArray = Arrays.asList(imgFileHP); int randomNo; public Task(String inputID){ frame.setSize(2200,2500);; frame.setLocationRelativeTo(null);; frame.setVisible(true);; frame.getContentPane().setLayout(new BorderLayout(0,0)); Collections.shuffle(pictureFileArray); Task(inputID); } public void Task(String inputID){ JPanel panel = new JPanel(); JLabel labelUsername = new JLabel(""); frame.getContentPane().add(panel, BorderLayout.CENTER); panel.setBackground(Color.WHITE); Image im = new ImageIcon(Task.class.getResource("/images/" + imgFileHP[index])).getImage(); ImageIcon iconLogo = new ImageIcon(im); labelUsername.setIcon(iconLogo); panel.add(labelUsername); textField.setText(""); textField.setColumns(10); textField.setVisible(true); textField.addKeyListener(this); panel.add(labelUsername); panel.add(textField); frame.setVisible(true); int keyb = JOptionPane.showOptionDialog(null, "Well done!", "Message", JOptionPane.OK_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE,null,null,null); if(keyb == JOptionPane.OK_OPTION) { frame.dispose(); } } public void actionPerformaed(ActionEvent ae){ if(!textField.getText().equals("")){ total_test += 1; if(booleanisNumeric(textField.getText())){ if(Integer.valueOf(imgNo[randomNo])==Integer.valueOf(textField.getText())){ System.out.println("Correct"); sum+=1; }else{ System.out.println("Invalid input"); Error+=1; } refreshFrame(); }else{ System.out.println("Null Input"); } } } public void refreshFrame(){ if(total_test>=20){ System.out.println("Correct:" +sum+" Incorrect: "+Error); frame.dispose(); }else{ frame.getContentPane().removeAll(); //getContentPane().removeAll(); Task(inputID); } } public static void main(String args[]){ Task a = new Task(inputID); } @Override public void keyPressed(KeyEvent e){ } @Override public void keyTyped(KeyEvent e){ } public static boolean booleanisNumeric(String str){ try{ Integer.valueOf(str); } catch(NumberFormatException nfe){ return false; } return true; } @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub } @Override public void keyReleased(KeyEvent arg0) { // TODO Auto-generated method stub } }
-33528555 0 Error thrown when using BlockMatrix.add I'm attempting to use the distributed matrix data structure BlockMatrix (Spark 1.5.0, scala) and having some issues when attempting to add two block matrices together (error attached below).
I'm constructing the two matrices by creating a collection of MatrixEntry's, putting that into CoordinateMatrix (with specifying Nrows,Ncols), and then using the CoordinateMatrix routine toBlockMatrix(Rpb,Cpb). For both matrices the Rpb/Cpb's are the same.
Unfortunately when attempting to use the BlockMatrix.add routine I'm getting:
15/11/04 10:17:27 ERROR executor.Executor: Exception in task 0.0 in stage 11.0 (TID 30) java.lang.IllegalArgumentException: requirement failed: The last value of colPtrs must equal the number of elements. values.length: 9164, colPtrs.last: 5118 at scala.Predef$.require(Predef.scala:233) at org.apache.spark.mllib.linalg.SparseMatrix.<init>(Matrices.scala:373) at org.apache.spark.mllib.linalg.SparseMatrix.<init>(Matrices.scala:400) at org.apache.spark.mllib.linalg.Matrices$.fromBreeze(Matrices.scala:701) at org.apache.spark.mllib.linalg.distributed.BlockMatrix$$anonfun$5.apply(BlockMatrix.scala:321) at org.apache.spark.mllib.linalg.distributed.BlockMatrix$$anonfun$5.apply(BlockMatrix.scala:310) at scala.collection.Iterator$$anon$11.next(Iterator.scala:328) at scala.collection.Iterator$$anon$13.hasNext(Iterator.scala:371) at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:327) at org.apache.spark.util.collection.ExternalSorter.insertAll(ExternalSorter.scala:202) at org.apache.spark.shuffle.sort.SortShuffleWriter.write(SortShuffleWriter.scala:56) at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:68) at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:41) at org.apache.spark.scheduler.Task.run(Task.scala:64) at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:203) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) 15/11/04 10:17:27 INFO scheduler.TaskSetManager: Starting task 2.0 in stage 11.0 (TID 32, localhost, PROCESS_LOCAL, 2171 bytes) 15/11/04 10:17:27 INFO executor.Executor: Running task 2.0 in stage 11.0 (TID 32) 15/11/04 10:17:27 WARN scheduler.TaskSetManager: Lost task 0.0 in stage 11.0 (TID 30, localhost): java.lang.IllegalArgumentException: requirement failed: The last value of colPtrs must equal the number of elements. values.length: 9164, colPtrs.last: 5118 at scala.Predef$.require(Predef.scala:233) at org.apache.spark.mllib.linalg.SparseMatrix.<init>(Matrices.scala:373) at org.apache.spark.mllib.linalg.SparseMatrix.<init>(Matrices.scala:400) at org.apache.spark.mllib.linalg.Matrices$.fromBreeze(Matrices.scala:701) at org.apache.spark.mllib.linalg.distributed.BlockMatrix$$anonfun$5.apply(BlockMatrix.scala:321) at org.apache.spark.mllib.linalg.distributed.BlockMatrix$$anonfun$5.apply(BlockMatrix.scala:310) at scala.collection.Iterator$$anon$11.next(Iterator.scala:328) at scala.collection.Iterator$$anon$13.hasNext(Iterator.scala:371) at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:327) at org.apache.spark.util.collection.ExternalSorter.insertAll(ExternalSorter.scala:202) at org.apache.spark.shuffle.sort.SortShuffleWriter.write(SortShuffleWriter.scala:56) at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:68) at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:41) at org.apache.spark.scheduler.Task.run(Task.scala:64) at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:203) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) 15/11/04 10:17:27 ERROR scheduler.TaskSetManager: Task 0 in stage 11.0 failed 1 times; aborting job 15/11/04 10:17:27 INFO storage.ShuffleBlockFetcherIterator: Getting 4 non-empty blocks out of 4 blocks 15/11/04 10:17:27 INFO storage.ShuffleBlockFetcherIterator: Started 0 remote fetches in 0 ms 15/11/04 10:17:27 INFO storage.ShuffleBlockFetcherIterator: Getting 2 non-empty blocks out of 4 blocks 15/11/04 10:17:27 INFO storage.ShuffleBlockFetcherIterator: Started 0 remote fetches in 1 ms 15/11/04 10:17:27 INFO scheduler.TaskSchedulerImpl: Cancelling stage 11 15/11/04 10:17:27 INFO executor.Executor: Executor is trying to kill task 1.0 in stage 11.0 (TID 31) 15/11/04 10:17:27 INFO scheduler.TaskSchedulerImpl: Stage 11 was cancelled 15/11/04 10:17:27 INFO executor.Executor: Executor is trying to kill task 2.0 in stage 11.0 (TID 32) 15/11/04 10:17:27 INFO scheduler.DAGScheduler: Stage 11 (map at kmv.scala:26) failed in 0.114 s 15/11/04 10:17:27 INFO executor.Executor: Executor killed task 2.0 in stage 11.0 (TID 32) 15/11/04 10:17:27 INFO scheduler.DAGScheduler: Job 2 failed: reduce at CoordinateMatrix.scala:143, took 6.046350 s Exception in thread "main" org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 11.0 failed 1 times, most recent failure: Lost task 0.0 in stage 11.0 (TID 30, localhost): java.lang.IllegalArgumentException: requirement failed: The last value of colPtrs must equal the number of elements. values.length: 9164, colPtrs.last: 5118 at scala.Predef$.require(Predef.scala:233) at org.apache.spark.mllib.linalg.SparseMatrix.<init>(Matrices.scala:373) at org.apache.spark.mllib.linalg.SparseMatrix.<init>(Matrices.scala:400) at org.apache.spark.mllib.linalg.Matrices$.fromBreeze(Matrices.scala:701) at org.apache.spark.mllib.linalg.distributed.BlockMatrix$$anonfun$5.apply(BlockMatrix.scala:321) at org.apache.spark.mllib.linalg.distributed.BlockMatrix$$anonfun$5.apply(BlockMatrix.scala:310) at scala.collection.Iterator$$anon$11.next(Iterator.scala:328) at scala.collection.Iterator$$anon$13.hasNext(Iterator.scala:371) at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:327) at org.apache.spark.util.collection.ExternalSorter.insertAll(ExternalSorter.scala:202) at org.apache.spark.shuffle.sort.SortShuffleWriter.write(SortShuffleWriter.scala:56) at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:68) at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:41) at org.apache.spark.scheduler.Task.run(Task.scala:64) at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:203) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) Driver stacktrace: at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1204) at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1193) at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1192) at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59) at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:47) at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1192) at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:693) at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:693) at scala.Option.foreach(Option.scala:236) at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:693) at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1393) at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1354) at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48) 15/11/04 10:17:27 WARN scheduler.TaskSetManager: Lost task 2.0 in stage 11.0 (TID 32, localhost): TaskKilled (killed intentionally) 15/11/04 10:17:27 INFO executor.Executor: Executor killed task 1.0 in stage 11.0 (TID 31) 15/11/04 10:17:27 WARN scheduler.TaskSetManager: Lost task 1.0 in stage 11.0 (TID 31, localhost): TaskKilled (killed intentionally) 15/11/04 10:17:27 INFO scheduler.TaskSchedulerImpl: Removed TaskSet 11.0, whose tasks have all completed, from pool Edit: Below is a small reproducer (not the original) for the problem. It fails for 1.3.0 and 1.5.0 at least. Is there a dense+sparse issue I'm not understanding?
import org.apache.spark.mllib.linalg._ import org.apache.spark.mllib.linalg.distributed._ import org.apache.spark.{SparkConf, SparkContext} object runAddBug { def main(args: Array[String]) { val appName = "addbug" val conf = new SparkConf().setAppName(appName) val sc = new SparkContext(conf) val N = 200 val Nbx = 10 val diags = sc.parallelize(0 to N-1) val Eyecm = new CoordinateMatrix(diags.map{d => MatrixEntry(d, d, 1.0)}, N, N) val diagsq = diags.cartesian(diags) val Bcm = new CoordinateMatrix(diagsq.map{dd => MatrixEntry( dd._1, dd._2, 1.0*dd._1*dd._2)}, N, N) val Rpb = (N/Nbx).toInt val Cpb = (N/Nbx).toInt var A = Eyecm.toBlockMatrix(Rpb,Cpb) var B = Bcm.toBlockMatrix(Rpb,Cpb) var C = A.add(B) val entsOut = C.toCoordinateMatrix().entries val outLines = entsOut.map{anent => anent.i.toString + "\t" + anent.j.toString + "\t" + anent.value.toString } outLines.saveAsTextFile("Outdata") } } Thanks for any help!
-39146457 0Don't use mysql for this stuff. You need an engine optimized for indexing search material. You can use elasticsearch or solr for this purpose and index it using mysql. Mysql is simply not designed for this purpose
Recently (only a few months ago) the folks behind Phusion Passenger add support to Heroku. Definitely this is an alternative you should try and see if fits your needs.
Is blazing fast even with 1 dyno and the drop in response time is palpable. A simple Passenger Ruby Heroku Demo is hosted on github.
The main benefits that Passengers on Heroku claims are:
Static asset acceleration through Nginx - Don't let your Ruby app serve static assets, let Nginx do it for you and offload your app for the really important tasks. Nginx will do a much better job.
Multiple worker processes - Instead of running only one worker on a dyno, Phusion Passenger runs multiple worker on a single dyno, thus utilizing its resources to its fullest and giving you more bang for the buck. This approach is similar to Unicorn's. But unlike Unicorn, Phusion Passenger dynamically scales the number of worker processes based on current traffic, thus freeing up resources when they're not necessary.
Memory optimizations - Phusion Passenger uses less memory than Thin and Unicorn. It also supports copy-on-write virtual memory in combination with code preloading, thus making your app use even less memory when run on Ruby 2.0.
Request/response buffering - The included Nginx buffers requests and responses, thus protecting your app against slow clients (e.g. mobile devices on mobile networks) and improving performance.
Out-of-band garbage collection - Ruby's garbage collector is slow, but why bother your visitors with long response times? Fix this by running garbage collection outside of the normal request-response cycle! This concept, first introduced by Unicorn, has been improved upon: Phusion Passenger ensures that only one request at the same time is running out-of-band garbage collection, thus eliminating all the problems Unicorn's out-of-band garbage collection has.
JRuby support - Unicorn's a better choice than Thin, but it doesn't support JRuby. Phusion Passenger does.
Hope this helps.
-12792342 0 How to scaling big image smoothly in canvas with drawImage?When I use drawImage to scalle a big image (like 5M), the result looks terrible, is there any easier way that can scalling image with anti-aliasing? MDN has mentioned about this:
Note: Images can become blurry when scaling up or grainy if they're scaled down too much. Scaling is probably best not done if you've got some text in it which needs to remain legible.
EIDT: I wanna scale a image to 90x90, and my code is like this:
that.avatar_height >= that.avatar_width ? that.context.drawImage($(this)[0], 86, 2, 90, that.avatar_height*90/that.avatar_width) : that.context.drawImage($(this)[0], 86, 2, that.avatar_width*90/that.avatar_height, 90); avatar is the image to be scaled.
-20001908 0 String reverse without to turn the numbers in cint main() { char str[1000],temp; int i,j=0; printf("String: "); gets(str); i=0; j=strlen(str)-1; while(i<j) { temp=str[i]; str[i]=str[j]; str[j]=temp; i++; j--; } printf("\n"); printf("%s",str); return 0; } I want to change the rota
- In: 15 15 15 15 15 0 0
- Out: 0 0 51 51 51 51 51 but i want : 0 0 15 15 15 15 15
I ran into some werid behavior, these two functions echo different sizes always. The first one echoes certain and right result, while the second one echoes random wrong results, is there anyone who knows why? I am using Python 2.7.10.
import urllib2 url = 'ftp://ftp.ripe.net/pub/stats/ripencc/delegated-ripencc-extended-latest' def one(): response = urllib2.urlopen(url) data = response.read() print len(data) def two(): print len(urllib2.urlopen(url).read()) one() two()
-11437854 0 As far as I can see mContext is null; and it may be causing this exception when instantiating the Intent.
-20158550 0You might look into using a modal for videos instead of the router if you want to overlay it on top of multiple states. If you stick with using the router, you might want to define videos as a child state of both home and portfolio instead of defining three states at the same level.
-22443545 0 Running batch file at Windows 7 UNLOCKI have a very simple .bat file. It only has one line:
powercfg -h off What this does is turn off the computer's ability to hibernate. It works fine when I double click the file. I can confirm this by going into the command prompt and typing "powercfg /a", which shows me that hibernate is indeed off. The problem is that this batch file doesn't seem to be running at logon even though it's in my Startup folder.
I've tested it by turning hibernate on using the command prompt ("powercfg -h on") and then actually putting my computer into hibernation. Then I turn it back on and log in to Windows. But when I open a command prompt and type "powercfg /a" it shows me that hibernate is still on. It seems the batch file doesn't run at logon even though it is in my Startup folder.
I've also tried making it run from a task scheduled to run at logon, but that didn't work either.
-34066153 0 How to exclude unit-tests with TestCaseFilter in TFS Build which do contain a namespaceI want to exclude all tests which include Abc in the namespace.
What is the correct pattern to use ?
!(FullyQualifiedName~.Abc.) is not valid ?
I used this web-page as reference : http://blogs.msdn.com/b/visualstudioalm/archive/2012/09/26/running-selective-unit-tests-in-vs-2012-using-testcasefilter.aspx
-38014617 0 batch script for loop teminates the batchI'm trying to use for loop and read contents of a file line by line the file is an xml and contains urls and paths delimited by <>
I am using the following code
set @LOGFILE=F:\nircmd\hosts.xml :loop for /F "tokens=2-3 delims=<>" %%a in (%LOGFILE%)do echo "it works" timeout /t goto :loop the batch is terminating as soon as it encounters the for loop
i have already tried to pause or timeout the batch but nothing seems to work batch is anyway terminating
what to do?
-36130431 0There is a very minor difference (effectively negligible, we're talking micro-optimization here), since the string should be stored in a local variable which takes that extra bit of memory on the stack frame of the corresponding method. Whereas the constants are actually stored in the constant pool and shared. With the likely optimizations of the JVM based on the number of invocations, it won't make a difference.
Note that the bytecode would be the same if the variables were final or effectively final (assigned only once), since in this case they are treated as constants.
GMP provides a convenient c++ binding for arbitrary precision integers
-13204142 0Since the internal pointer of the stream is at index 4 after you write the data, you need to fseek back to the beginning of your stream:
// fwrite fseek($memory, 0); // same as rewind($memory); // fread
-25772669 0 understanding compareto() method in java i came across a MIT lecture on recursion where they checked palindrome using recursion,and there they checked it using logic where they compare first and last alphabet and so on.. what i thought is something as follows
just a pseudo code:
String original="abba"; String reverse = ""; for(int i=original.length()-1;i>=0;i--) { reverse+=new String(original.substring(i,i+1)); } if(original.equals(reverse)) System.out.println("palindrome"); else System.out.println("not palindrome"); i have two doubts
compareTo() method checks if strings are equal? DOes it compare bytecode or something?You have forgotten to close the $(document).ready function
Yes, absolutely, that's possible and pretty easy to do: all you need is to create an extension with a content script that will be injected into that particular page and remove the element for you.
To do what you want you'll need to:
manifest.json file.Specify the "content_scripts" field in the manifest.json, and declare the script you want to inject. Something like this:
"content_scripts": [ { "matches": "http://somesite.com/somepage.html", "js": "/content_script.js" } ] Take a look here to find out how content scripts work.
Create a content_script.js, which will delete the element for you. This script will basically contain the following two lines:
var element = document.querySelector('div.feedmain'); element.parentElement.removeChild(element); You need this: http://www.iis.net/download/WebDeploy
-24757768 0In TreeView.SelectedItemChanged event, we get e.NewValue which is type of TreeViewItem, so I think you can use following code to select an item when it's group is selected.
var item = (e.NewValue as TreeViewItem); if (item.Items.Count > 0) { (item.Items[0] as TreeViewItem).IsSelected = true; }
-2646694 0 Running job in the background from Perl WITHOUT waiting for return First of all, I know this question (or close variations) have been asked a thousand times. I really spent a few hours looking in the obvious and the not-so-obvious places, but there may be something small I'm missing.
Let me define the problem more clearly: I'm writing a newsletter app in which I want the actual sending process to be async. As in, user clicks "send", request returns immediately and then they can check the progress in a specific page (via AJAX, for example). It's written in your traditional LAMP stack.
In the particular host I'm using, PHP's exec() and system() are disabled for security reasons, but Perl's system functions (exec, system and backticks) aren't. So my workaround solution was to create a "trigger" script in Perl that calls the actual sender via the PHP CLI, and redirects to the progress page.
The very line the calls the sender is, as of now:
system("php -q sender.php &"); Problem being, it's not returning immediately, but waiting for the script to finish. I want it to run in the background and have the system call itself return right away. I also tried running a similar script in my Linux terminal, and in fact the prompt doesn't show until after the script has finished, even though my test output doesn't run, indicating it's really running in the background.
Just to be sure that I'm not missing anything obvious, I created a sleeper.php script which just sleeps five seconds before exiting. And a test.cgi script that is like this, verbatim:
#!/usr/local/bin/perl system("php sleeper.php &"); print "Content-type: text/html\n\ndone"; I am trying to set Up Animated GIF with player card. but when I test my player card https://cards-dev.twitter.com/validator it dosen't show animated GIF.
Here is my meta code for player card
<meta content='text/html; charset=UTF-8' http-equiv='Content-Type'/> <meta name="twitter:card" value="player"> <meta name="twitter:site" value="@uncleLaravel"> <meta name="twitter:title" value="domain.com"> <meta name="twitter:description" value="sample"> <meta name="twitter:image" value="http://domain.com/img/sample.gif"> <meta name="twitter:player" value="http://www.domain.com/container.html"> <meta name="twitter:player:width" value="320"> <meta name="twitter:player:height" value="320"> <meta name="twitter:domain" value="domain.com"> container.html
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <style> html, body{ margin: 0; padding: 0; overflow: hidden; } img{ border: 0; } </style> </head> <body> <img id="gif" src="/sample.gif" width="100%"> </body> </html> Is anything wrong here?
-39007139 0 How can I getText() from EditText in Fragment and pass in Volley Parameters?I am using Volley in Fragments for the first time.
Can anyone help me with this. I am trying this following code for the fragment which I am calling from a navigation drawer:
public class ChangePassword extends android.app.Fragment implements View.OnClickListener { EditText etOldSignUpPassword; EditText etNewSignUpPassword; EditText etNewSignUpConfirmPassword; ImageButton imageChangePasswordButton; ProgressBar pbWeb; String old,npass,ncpass; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_change_password, container, false); etOldSignUpPassword = (EditText)v.findViewById(R.id.etOldPassword); etNewSignUpPassword = (EditText)v.findViewById(R.id.etNewSignUpPassword); etNewSignUpConfirmPassword = (EditText)v.findViewById(R.id.etNewSignUpConfirmPassword); imageChangePasswordButton = (ImageButton)v.findViewById(R.id.imageChangePasswordButton); pbWeb = (ProgressBar)v.findViewById(R.id.pbWebC); pbWeb.setVisibility(View.GONE); imageChangePasswordButton.setOnClickListener(this); return v; } @Override public void onClick(View view) { if(view.getId() == R.id.imageChangePasswordButton) { old = etOldSignUpPassword.getText().toString(); npass = etNewSignUpPassword.getText().toString(); ncpass = etNewSignUpConfirmPassword.getText().toString(); if (!isNetworkAvailable()) { Toast.makeText(getActivity(), "Your Wifi/Data is disabled. Please switch on and try again", Toast.LENGTH_SHORT).show(); } else { pbWeb.setVisibility(View.VISIBLE); String server_url = "url_working_fine_for_activity_so_no_issue_here"; StringRequest strReq = new StringRequest(Request.Method.POST, server_url, new Response.Listener<String>() { @Override public void onResponse(String response) { if (response.equals("SUCCESS")) { Toast.makeText(getActivity(), "Password Changed Successfully", Toast.LENGTH_SHORT).show(); Intent loginIntent = new Intent(getActivity(), LoginActivity.class); startActivity(loginIntent); pbWeb.setVisibility(View.GONE); getActivity().finish(); } else { pbWeb.setVisibility(View.GONE); Toast.makeText(getActivity(), "Couldn't Change Password. Old Password Exists", Toast.LENGTH_SHORT).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { pbWeb.setVisibility(View.GONE); Toast.makeText(getActivity(), error.toString(), Toast.LENGTH_SHORT).show(); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> map = new HashMap<String, String>(); map.put("old", old);//etOldPassword.getText().toString() throws NullPointerException map.put("new", npass);//"MY_DEFAULT_VALUE" as value is working fine but that is not the use case map.put("newCon", ncpass); return map; } }; //VolleySingleton is fine as working in Activity as well as when I give default values in getParams so no issue in this class VolleySingleton.getInstance(getActivity().getApplicationContext()).addToReqQueue(strReq); } } } PREV: Currently this code leads to a crash.
NOTE: I have tried using onClickListener() directly on imageChangePasswordButton inside onActivityCreated() method without implemeting onClickListener on the class but found on a thread that there is a bug.
EDIT: Current Code as seen is working fine.
Here is the xml as requested:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".mypackage.ChangePassword"> <!--The class ChangePassword is inside mypackage--> <ProgressBar android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/pbWebC" style="@android:style/Widget.ProgressBar.Small" android:layout_centerInParent="true" /> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_alignParentTop="true"> <ImageView android:layout_width="150dp" android:layout_height="150dp" android:src="@drawable/image1" android:id="@+id/logo" android:layout_gravity="center_horizontal" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPassword" android:hint="@string/prompt_old_email" android:ems="10" android:layout_marginTop="10dp" android:id="@+id/etOldPassword" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPassword" android:hint="@string/prompt_new_password" android:ems="10" android:layout_marginTop="10dp" android:id="@+id/etNewSignUpPassword" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPassword" android:hint="@string/prompt_new_confirm_password" android:ems="10" android:layout_marginTop="10dp" android:id="@+id/etNewSignUpConfirmPassword" /> <ImageButton android:layout_width="150dp" android:layout_height="50dp" android:layout_gravity="center" android:id="@+id/imageChangePasswordButton" android:layout_marginTop="20dp" android:src="@drawable/reset" /> </LinearLayout> </RelativeLayout> EDIT: Code working fine. Thanks for the help. @LongRanger @i-Droid
-37453207 0Generate array of values of data-x and data-y values using map() and get(). Then use Math.min and Math.max with apply() to get maximum and minimum value from array.
// generate array of `data-x` attribute var arr1 = $('[data-x]').map(function() { return $(this).data('x'); }).get(); // generate array of `data-y` attribute var arr2 = $('[data-y]').map(function() { return $(this).data('y'); }).get(); console.log( Math.min.apply(Math, arr1), Math.min.apply(Math, arr2), Math.max.apply(Math, arr1), Math.max.apply(Math, arr2) ) <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="container"> <div class="right" data-x="1" data-y="1"></div> <div class="right" data-x="2" data-y="1"></div> <div class="right" data-x="3" data-y="1"></div> <div class="right" data-x="4" data-y="1"></div> </div> Answer from author of the library. Example linked here.
$: << File.dirname(__FILE__) + '/../lib' require 'em-whois' require 'atomic' # Asynchronous, parallel multi-domain WHOIS lookup domains = ARGV.empty? ? ["github.com", "google.com", "bing.com", "yahoo.com", "mikejarema.com"] : ARGV whois = {} EM.synchrony do # Progress indicator EM.add_periodic_timer(0.1) do STDERR.print "." end # Exit condition EM.add_periodic_timer(0.1) do if domains.size == whois.keys.size puts "" whois.each do |k,v| if v.properties[:available?] puts "#{k}: available" else puts "#{k}: taken, expires #{v.properties[:expires_on]}" end end EM.stop end end # Async WHOIS lookup - fire and forget via parallel fibers domains.each do |i| Fiber.new do whois[i] = Whois.whois(i) end.resume end end
-12654110 0 Can not seem to change SSL cert on httpd server I am trying to setup SSL using httpd server. At I created self cert and it worked fine, of course displaying brocker lock in browsers.
Now I got proper entrust cert but I can not seem to replace the old one. browser shows broken lock and when i open certificate info box it still does not show company name or proper server name, even though it has been changed.
how do you properly replace SSL certificate?
-30293174 0 How to use SDL locally in Visual Studio 2013I want to add SDL and SDL_image to my Visual Studio project. But can I do it locally only for this project? I don't want to put the dlls in System32 folder.
-2291633 0In my company's toolkit, we implemented a technology we call remote invoke. This consists of two parts - on the client side, there is a javascript method called RemoteInvoke() which takes a method name and an array of arguments to pass to the method. On the server side, you decorate a public method you would like to call with the attribute [RemoteInvokable]. RemoteInvoke matches signature as best as it can (type casting if needed) and then called the appropriate public method (if it found one).
It's not for things as simple as click actions, but it if you need more complicated things, it will work just great.
-10899761 0 C# - Passing an anonymous function as a parameterI'm using FluentData as an orm for my database and I'm trying to create a generic query method:
internal static T QueryObject<T>(string sql, object[] param, Func<dynamic, T> mapper) { return MyDb.Sql(sql, param).QueryNoAutoMap<T>(mapper).FirstOrDefault(); } Except in my class's function:
public class MyDbObject { public int Id { get; set; } } public static MyDbObject mapper(dynamic row) { return new MyDbObject { Id = row.Id }; } public static MyDbObject GetDbObjectFromTable(int id) { string sql = @"SELECT Id FROM MyTable WHERE Id=@Id"; dynamic param = new {Id = id}; return Query<MyDbObject>(sql, param, mapper); } at Query<MyDbObject>(sql, param, mapper) the compilers says:
An anonymous function or method group connot be used as a constituent value of a dynamically bound object.
Anyone have an idea of what this means?
Edit:
The compiler doesn't complain when I convert the method into a delegate:
public static Func<dynamic, MyDbObject> TableToMyDbObject = (row) => new MyDbObject { Id = row.Id } It still begs the question of why one way is valid but not the other.
-32584865 0 How to bind AJAX loaded elements to JQuery plugins with on() functionI am using a JQuery plugin datepicker that allows me to set options e.g. default date, format, minimum date etc.
Here is the code
$(".standardDatePicker").datepicker({ defaultDate: "+1w", dateFormat: 'dd/mm/yy', changeMonth: true, numberOfMonths: 1, minDate: new Date(_currentTime.getFullYear(), _currentTime.getMonth(), _currentTime.getDate(), 1) }); I am loading content via Ajax into a modal, but am then trying to bind those elements that have been inserted into the DOM with a call to the datepicker plugin.
The following code has worked fine on other code but i cant find a way to use it with plugins, is this even possible without modifying the plugin?
What I have tried
$("document.standardDatePicker").on(datepicker({ defaultDate: "+1w", dateFormat: 'dd/mm/yy', changeMonth: true, numberOfMonths: 1, minDate: new Date(_currentTime.getFullYear(), _currentTime.getMonth(), _currentTime.getDate(), 1) }));
-9743948 0 It's best if you can add a field that will not display on the application for the file unique_id in the table and then use that in a join to the data to populate the child tables. But sometimes you can't mess with the structure of a database especially if it is a COTS product.
We have a sneaky trick for that. First load the data to a staging table (adding an identity if the file has no unique identifier on it's own) and an empty field for the parent_id.
Next put the unique identifier into some other required field instead of its normal value (We use last_name but if you have one taht is the same datatype as the uniqueid that's better). Then you can join on the required field and the uniqueid from the staging table to update it to get the real parentid. Then update the field where you stored the temporary id with its real value (becasue now you can use teh real parent_id). Now you have the real parent_id in a table, the data flows for the child tables can join to that. This creates more work for the database, so only use it if you can't change the structure.
Alternatively you can do all the inserting from a staging table using a stored proc and the execute SQL task rather than in a dataflow.
-7921648 0 In Perl, can refer to an array using its name?I'm new to Perl and I understand you can call functions by name, like this: &$functionName();. However, I'd like to use an array by name. Is this possible?
Long code:
sub print_species_names { my $species = shift(@_); my @cats = ("Jeffry", "Owen"); my @dogs = ("Duke", "Lassie"); switch ($species) { case "cats" { foreach (@cats) { print $_ . "\n"; } } case "dogs" { foreach (@dogs) { print $_ . "\n"; } } } } Seeking shorter code similar to this:
sub print_species_names { my $species = shift(@_); my @cats = ("Jeffry", "Owen"); my @dogs = ("Duke", "Lassie"); foreach (@<$species>) { print $_ . "\n"; } }
-3219863 0 In addition to what others have said, pointers are necessary for dynamic memory allocation (this also applys to higher level languages, but is (usually) abstracted away). This means that without pointers, you're limited to the (generally rather small) stack memory, which is more in need of conservation.
-39811346 0 Simple C++ demo for caffe?I want to implement a simple C++ demo. Its purpose is in loading an image and predicting its class using caffe network. There is examples/classification/classification.cpp. This example takes exactly 5 arguments:
deploy.prototxt network.caffemodel mean.binaryproto labels.txt img.jpg But after training lenet as example, I have only
lenet.prototxt and lenet_iter_10000.caffemodel Where should I get mean.binaryproto labels.txt?
-2177194 0switch($argv[$i]) { case '-V': case '--version': $displayVersion = true; break; }
-32888565 0 the api (or by url) does not support converting a csv into an existing spreadsheet.
you could instead convert into a new sheet and then use the spreadsheet api to copy the sheet data into your spreadsheet. you can also skip the csv upload step and directly parse and write to the existing sheet using that api.
-38183260 0 RallyRestToolkitForRuby - Unable to pull user permissionsAm trying to use https://github.com/RallyTools/RallyRestToolkitForRuby to pull permissions of all users in my Rally Subscription. My authentication is through API Key. It fails with below error:
C:\Users\Administrator\Desktop\Rally-User-Management-master\Rally-User-Management-master>user_permissions_summary.rb Connecting to Rally: https://rally1.rallydev.com/slm as ganra08@ca.com... Running initial query of users... Found a total of 12392 Enabled Users. Summarizing users and writing permission summary output file... C:/Users/Administrator/Desktop/Rally-User-Management-master/Rally-User-Management-master/lib/go_user_permissions_summary.rb:224:in block (2 levels) in go_user_permissions_summary' C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/rally_api-1.2.1/lib/rally_api/rally_colle ction.rb:36:ineach' C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/rally_api-1.2.1/lib/rally_api/rally_collection.rb:36:in each' C:/Users/Administrator/Desktop/Rally-User-Management-master/Rally-User-Management-master/lib/go_user_permissions_summary.rb:201:inblock in go_user_permissions_summary' C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/rally_api-1.2.1/lib/rally_api/rally_query_result.rb:22:in block in each' C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/rally_api-1.2.1/lib/rally_api/rally_query_result.rb:21:ineach' C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/rally_api-1.2.1/lib/rally_api/rally_query_result.rb:21:in each' C:/Users/Administrator/Desktop/Rally-User-Management-master/Rally-User-Management-master/lib/go_user_permissions_summary.rb:180:ingo_user_permissions_summary'
C:/Users/Administrator/Desktop/Rally-User-Management-master/Rally-User-Management-master/user_permissions_summary.rb:38:in <main>' undefined method[]' for nil:NilClass
How do i get over this error? The Readme.pdf in the GitHub page provides no info about this.
-7530532 0 Sort product listings in Spree based on created_atI'm using spree and I want to sort product listing based on created_at of the product.
I tried to find the way to override the spree default scope under lib/scopes/product.rb but couldn't find it.
I want to list recently created products on public panel. How can I do it with spree?
-40294163 0 __WEBPACK_AMD_DEFINE_ARRAY__ is not defined import Jquery with webpackI have tried severally without luck importing jquery to global scope using webpack with below methods , but all throw errors :
Try 1 : Expose Loader
Used it in my webpack.config as below
{ test: require.resolve('jquery'), loader: 'expose?$!expose?jQuery' }, Throws error $ is not defined when i console.log(typeof $)
Try 2 : Webpack ProvidePlugin
Used it in my webpack.config as below
plugins: [ new webpack.ProvidePlugin({ '$': 'jquery', 'jQuery': 'jquery', 'window.jQuery': 'jquery' }) ] throws error WEBPACK_AMD_DEFINE_ARRAY is not defined when hot-reloading
Am using vue.js V2
-17942164 0Suppose your dataObj contains a unique ID field, then any set data structure would be fine for your job. The immutable data structures are primarily used for functional style code or persistency. If you don't need these two, you can use HashSet<T> or SortedSet<T> in the .Net collection library.
Some stream specific optimization may be useful, e.g., keeping a fixed-size Queue<T>for the most recent data objects in the stream and store older objects in the more heavy weight set. I would suggest a benchmarking before switching to such hybrid data structure solutions.
Edit:
After reading your requirements more carefully, I found that what you want is a queue with user-accessible indexing or backward enumerator. Under this data structure, your feature extraction operations (e.g. average/sum, etc) cost O(n). If you want to do some of the operations in O(log n), you can use more advanced data structures, e.g. interval trees or skip lists. However, you will have to implement these data structures yourself as you need to store meta information in the tree nodes which are behind collection API.
-40848364 0 JSP to display ksh script responseI have several servers. And on each of the servers, I have a shell script to verify the FileSystem, and some info of some files I parse. This script renders information to the console for example
Server 1 fs /usr/user1 free 10 Gb
File 100 Processed, File 200 Processed,
etc..
The script takes about 1 minute to execute completely.
I already have a jboss server with a webapp with some servlets. I would like to create a jsp, and a servlet to run these commands on 4 different servers and display the results.
Ajax maybe??
Thanks in advance
-30315449 0https://css-tricks.com/fluid-width-equal-height-columns/
I recommend seeing if any of these tricks work for you.
-30477337 0 liquibase database build from scratchWhen I run liquibase update from scratch, it takes a while as the process fires each changelog one by one. Sometimes my own database changes diverge enough that its easiest to rebuild the database if I want to start again for example.
The rebuild would be quickest if I did it from a mysql dump of the result of liquibase at a certain point in the changelogs, and I ignored the changelogs from there previously. So I would delete everything in changelog master except my master build dump changelog, which would be the entire database, and I keep hold of the actual changelogs for version control reasons.
Is there a proper/ordained/safe way to do this from liquibase?
-19169115 0 Phonegap: Keyboard changes window height in iOS 7In iOS 6 everything works fine. The keyboard opens and moves the input into view. When the keyboard closes everything goes back where it should.
In iOS 7 the keyboard opens fine and the input remains in view. When the keyboard is closed the whole bottom half of the app is gone, though. I've tracked the issue down to the height of the window changing when the keyboard is opened, and not changing back when it's closed.
Right before the keyboard is opened the window height is 568 according to $(window).height() and after it's opened and after it's closed it is 828. The height of the document also changes accordingly.
I've attempted preventing the window from resizing with:
$(window).resize(function(e) { e.preventDefault(); e.stopPropagation(); window.resizeTo(320,480); return false; }); I've also attempted to set the size back after the keyboard closes with no success.
I'm using phonegap 2.7 and have KeyboardShrinksView set to true.
-7710543 0 How to read mbox email messages using mstorI am using mstor to read the mbox email messages, but i am not able to connect to the store using the urlName name which i m passing, by default its connecting to other location on my macbine.Do i need to create the store using mstor JCR before proceed to connect to the store?
Session session = Session.getDefaultInstance(new Properties()); Store store = session.getStore(new URLName("mstor:C:/mailbox/MyStore/Inbox")); store.connect(); Folder inbox = store.getDefaultFolder().getFolder("inbox"); inbox.open(Folder.READ_ONLY); Message m = inbox.getMessage(0); Any suggetions are helpful
Thanks in advance..
-29133925 0 Declaring an extern variable in a header fileI have declared an extern global variable inside my main.h header file like this:
extern int variable; Then, I defined the same global variable inside my main.c file like this:
int variable = 16; The thing is that I am using another file called test.c, and I have included main.h header included inside. But I cannot gain access the the "16" value that I defined the extern with inside main.c. When I call "variable" inside test.c, the value of "variable" is "0". Should not any .c file that includes my main.h header have access to the "16" value since I have already defined my "variable" inside main.c???
Thanks
-11944486 0 multicast socket - will not work when computer wakes up from sleepHi guys I have a multicast socket that is receiving packets and is working fine.
I had an issue though where when my computer wakes up from sleep the multicast socket does not work. Continually timing out:
MulticastSocket socket; \\initialise socket.. while (running) { try { synchronized (syncRoot) { socket.setSoTimeout(WAIT_TIME); socket.receive(recv); //Do Something... } } catch (SocketTimeoutException e) { } Currently when my computer wakes up from windows sleep mode it continually throws a socket exception when I no their are packets being sent. I have checked variables socket.isBound(), socket.isClosed(), socket.isConnected() and they have not changed from when it was working. Am I missing a variable? Even when the socket is working it returns isConnected() = false, isBound() = true, isClosed() = false.
Do I need to do something like count the number of SocketTimeoutExceptions if i get 10 then reinitialise my multicast socket?
-33645856 0Instead of doing {{html_entity_decode($post->content)}}, try this instead:
{!! $post->content !!} More info here https://laravel-news.com/2014/09/laravel-5-0-blade-changes/
-38548316 0 how do i add a side bar and center page with out them merging with the nav barI have tried adding a center page and side bars to my site but the only problem is the div tags merge and the backround color of the nav bar takes over the side bars even if the style code is separated heres an example
<!DOCTYPE html> <style> body {margin:0;} ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; border: solid; background-color: #000000; width: 100%; display:inline-block; } li { float: left; } .dropbtn { background-color: #0E8E0A; color: white; padding: 19px; font-size: 16px; border: none; overflow:hidden; cursor: pointer; } .dropbtnR { background-color: #15428A; color: white; padding: 19px; font-size: 16px; border: none; overflow:hidden; cursor: pointer; } .dropdown { display: inline-block; } .dropdown-content { display: none; position: absolute; background-color: #f9f9f9; min-width: 100px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); } .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; } .dropdown-content a:hover {background-color: #f1f1f1} .dropdown:hover .dropdown-content { display: block; } span { } </style> <!-- saved from url=(0039)http://www.theamannetwork.net/beta.html --> <html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <style> .float-left-area { width: 70%; float: left; } .float-right-area { width: 30%; float: left; } .inner-left { padding: 5px 5px 5px 5px; margin-right: 10px; border: #999999 1px solid; min-height: 60px; } .inner-right { font-size: 11px; padding: 5px 5px 5px 5px; border: #999999 1px solid; min-height: 60px; } .clear-floated { clear: both; height: 1px; font-size: 1px; line-height: 1px; padding: 0; margin: 0; } </style> < </head> <body> <ul> <br> <div class="dropdown" style="float:left;"> <button class="dropbtn">≡</button> <div class="dropdown-content" style="left:0;"> <a href="http://www.theamannetwork.net/beta.html#">the </a> <a href="http://www.theamannetwork.net/beta.html#">cake </a> <a href="http://www.theamannetwork.net/beta.html#">is a lie</a> </div> </div> </br> <div class="dropdown-content"> <a href="http://www.theamannetwork.net/beta.html#"><img src="./beta_files/Twitter.png"> </a> <a href="http://www.theamannetwork.net/beta.html#">random link </a> <a href="http://www.theamannetwork.net/beta.html#">SOMTHING IDK </a> </div> </div> <center><a class="navbar-brand" href="http://www.theamannetwork.net/beta.html#"><img src="./beta_files/banner.png" alt=""></a></center> <div class="float-left-area"> <div class="inner-left"> some random content </div> </div> <div class="float-right-area"> <div class="inner-right"> some random content </div> </div> <div class="clear-floated"></div> </ul></body></html> how do I go about adding a center page and side bars with out merging
-17866798 0 How to keep decimal rounded to two places?So All of my decimals are rounded to two places. However when I click on "keyboard or mouse" image the decimal place is roughly ten digits long( for example:36.900000000000006). How do I stop this. I've tried using ".toFixed(), and .toPrecision().
here is a link to the page... much easier to do this than create a fiddle.
http://www.ootpik.info/lauren/ootpik5/gethardware.html
I've added a fiddle: http://jsfiddle.net/lolsen7/8uwGH/3/
script
$(document).ready(function() { $(".part,.extra").mouseover(function() { if(this.className !== 'part selected') { $(this).attr('src', 'images/placeholder/get_hardware/' + this.id + '.png'); } $(this).mouseout(function(){ if(this.className !== 'part selected') { $(this).attr('src', 'images/placeholder/get_hardware/' + this.id + '_grey.png'); } }); }); var list = document.getElementById("list"); var summaryTotal = document.getElementById("summaryTotal"); var touchtotal = 13.89; var minitotal = 19.47; var constant = touchtotal + minitotal; $('#finaltotal').text(constant); //station one var keyboard2 = 59; var mouse2 = 59; var printer = 345; var scale2 = 530; var display = 175; var single = 132; var multi = 260; var scannerTotal = 0; var cash = 100; var storage = 125; var registerTotal = 0; //extras var ipad = 349; var ipadTotal = 0; var mobilePrinter = 570; var mobileTotal = 0; var printer2 = 345; var printer2Total = 0; $(".part").click(function(){ var name = this.id; var liname = this.alt; var total = parseFloat((eval(name) * 1.2) /40); if(this.className != 'part selected') { $(this).attr('src','images/placeholder/get_hardware/' + name + '.png'); if(name !== 'multiBar' && name !== 'singleBar' && name !== 'storageDrawer' && name !== 'cashDrawer' ) { //generate list items var li = document.createElement("li"); li.setAttribute("id",name + "_li"); li.appendChild(document.createTextNode(liname)); list.appendChild(li); //touchscreen and mac mini pricing constant = constant + total; $('#finaltotal').text(constant); } //Scanners if clicked on else if(name == "multiBar" || name == "singleBar"){ $(".tooltip").show(); $("input").change(function(e){ if($(this).attr("checked", "true")) { if(this.value == "one") { // hide and show images based on radio selection $('#singleBar').attr('src','images/placeholder/get_hardware/singleBar.png'); $('#singleBar').show(); $('#singleBar').toggleClass('selected'); $('#multiBar').hide(); //list item if($('#single_li').length > 0) { $('#single_li').remove(); } if($('#multi_li').length > 0) { $('#multi_li').remove(); } li = document.createElement("li"); li.setAttribute("id","single_li"); li.appendChild(document.createTextNode("Single-line Barcode Scanner")); list.appendChild(li); //pricing if(scannerTotal !== 0) { constant = constant - scannerTotal; } scannerTotal = (single * 1.2) /40; constant = constant + scannerTotal; $('#finaltotal').text(constant); }else if(this.value == "two") { //hide and show images based on radio selection $('#multiBar').attr('src','images/placeholder/get_hardware/multiBar.png'); $('#multiBar').show(); $('#singleBar').hide(); //list item if($('#multi_li').length > 0){ $('#multi_li').remove(); } if($('#single_li').length > 0){ $('#single_li').remove(); } li = document.createElement("li"); li.setAttribute("id","multi_li"); li.appendChild(document.createTextNode("Multi-line Barcode Scanner")); list.appendChild(li); if(scannerTotal !== 0){ constant = constant - scannerTotal; } scannerTotal = (multi * 1.2) /40; constant = constant + scannerTotal; $('#finaltotal').text(constant); } } }); } //if register is clicke on else if(name =="storageDrawer" || name == "cashDrawer"){ $('.tooltip2').show(); $('input').change(function(){ if($(this).attr("checked","true")) { if(this.value == "three") { //hide and show images based on radio button selection $('#cashDrawer').attr('src','images/placeholder/get_hardware/cashDrawer.png'); $('#cashDrawer').show(); $("#storageDrawer").hide(); //list items if($('#cash_li').length > 0){ $('#cash_li').remove(); } if($('#storage_li').length > 0){ $('#storage_li').remove(); } li = document.createElement("li"); li.setAttribute('id','cash_li'); li.appendChild(document.createTextNode("Cash Drawer")); list.appendChild(li); //pricing if(registerTotal !== 0){ constant = constant - registerTotal; } registerTotal = (cash * 1.2)/40; constant = constant + registerTotal; $('#finaltotal').text(constant); }else if(this.value == "four") { $('#storageDrawer').attr('src','images/placeholder/get_hardware/storageDrawer.png'); $('#storageDrawer').show(); $('#cashDrawer').hide(); //list items if($('#storage_li').length > 0){ $('#storage_li').remove(); } if($('#cash_li').length > 0){ $('#cash_li').remove(); } li = document.createElement('li'); li.setAttribute('id','storage_li'); li.appendChild(document.createTextNode("Premium Cash Drawer")); list.appendChild(li); //pricing if(registerTotal !== 0){ constant = constant - registerTotal; } registerTotal = (storage * 1.2)/40; constant = constant + registerTotal; $('#finaltotal').text(constant); } } }); } $(this).toggleClass('selected'); } else if (this.className == 'part selected') { $(this).attr('src','images/placeholder/get_hardware/' + name + '_grey.png'); if(name !== 'multiBar' && name !== 'singleBar' && name !== 'storageDrawer' && name !== 'cashDrawer') { constant = constant - total; $('#finaltotal').text(constant); $("#" + name + "_li").remove(); } //Scanners else if(name == 'multiBar' || name == 'singleBar') { //Hides Tooltip when de-selecting item $(".tooltip").hide(); // removes pricing console.log(scannerTotal); constant = constant - scannerTotal; scannerTotal = 0; $('#finaltotal').text(constant); //Removes any List items if($('#multi_li').length > 0) { $('#multi_li').remove(); } if($('#single_li').length > 0) { $('#single_li').remove(); } //Sets Inputs to deselected $("input[name='group1']").attr("checked",false); } //cash drawers || registers else if(name == 'storageDrawer' || name == 'cashDrawer') { $('.tooltip2').hide(); //removes pricing console.log(registerTotal); constant = constant - registerTotal; registerTotal = 0; $('#finaltotal').text(constant); //remove any list items if($('#storage_li').length > 0) { $('#storage_li').remove(); } if($('#cash_li').length > 0) { $('#cash_li').remove(); } //Sets Inputs to deselected $("input[name='group2']").attr("checked",false); } $(this).toggleClass('selected'); } }); $(".numbers-row").append('<div class="inc buttons">+</div><div class="dec buttons">-</div>'); $(".buttons").on("click", function() { var $buttons = $(this); var oldValue = $buttons.parent().find("input").val(); if ($buttons.text() == "+") { var newVal = parseFloat(oldValue) + 1; if(newVal > 2 ){ return; } } else { // Don't allow decrementing below zero if (oldValue > 0) { var newVal = parseFloat(oldValue) - 1; } else { newVal = 0; } } $buttons.parent().find("input").val(newVal); if($buttons.parent().attr('class') == 'numbers-row ipad'){ if($('#ipad_mini_extra').length > 0){ $('#list').children('#ipad_mini_extra').remove(); //remove pricing if(newVal == 0){ constant = constant - ipadTotal; console.log(ipadTotal); $('#finaltotal').text(constant); } } if(newVal !== 0){ $('#ipad').attr('src',"images/placeholder/get_hardware/ipad.png"); $('#list').append('<li id="ipad_mini_extra">' + newVal + ' iPad mini(s) </li>'); //add pricing if(ipadTotal !== 0){ constant = constant - ipadTotal; } if(newVal == 1){ ipadTotal = (ipad * 1.2) /40; console.log(ipadTotal); constant = constant + ipadTotal; $('#finaltotal').text(constant); } if(newVal == 2){ ipadTotal = ((ipad * 2) * 1.2)/40; console.log(ipadTotal) constant =constant + ipadTotal; $('#finaltotal').text(constant); } } else{ $('#ipad').attr('src',"images/placeholder/get_hardware/ipad_grey.png"); } } if($buttons.parent().attr('class') == 'numbers-row mobile') { if($('#mobile_extra').length > 0) { $('#list').children('#mobile_extra').remove(); //remove pricing if(newVal == 0){ constant = constant - mobileTotal; console.log(mobileTotal); $('#finaltotal').text(constant); } } if(newVal !== 0) { $('#mobilePrinter').attr('src',"images/placeholder/get_hardware/mobilePrinter.png"); $('#list').append('<li id="mobile_extra">' + newVal + ' Mobile Printer(s) </li>'); //add pricing if(mobileTotal !== 0){ constant = constant - mobileTotal; } if(newVal == 1){ mobileTotal = (mobilePrinter * 1.2) /40; console.log(mobileTotal); constant = constant + mobileTotal; $('#finaltotal').text(constant); } if(newVal == 2){ mobileTotal = ((mobilePrinter * 2) * 1.2)/40; console.log(mobileTotal) constant =constant + mobileTotal; $('#finaltotal').text(constant); } } else { $('#mobilePrinter').attr('src',"images/placeholder/get_hardware/mobilePrinter_grey.png"); } } if($buttons.parent().attr('class') == 'numbers-row printer2') { if($('#printer2_extra').length > 0) { $('#list').children('#printer2_extra').remove(); //remove pricing if(newVal == 0){ constant = constant - printer2Total; console.log(printer2Total); $('#finaltotal').text(constant); } } if(newVal !== 0) { $('#printer2').attr('src',"images/placeholder/get_hardware/printer2.png"); $('#list').append('<li id="printer2_extra"> ' + newVal + ' Kitchen/Bar/Expo Printer(s) </li>'); //add pricing if(printer2Total !== 0){ constant = constant - printer2Total; } if(newVal == 1){ printer2Total = (printer2 * 1.2) /40; console.log(printer2Total); constant = constant + printer2Total; $('#finaltotal').text(constant); } if(newVal == 2){ printer2Total = ((printer2 * 2) * 1.2)/40; console.log(printer2Total) constant =constant + printer2Total; $('#finaltotal').text(constant); } } else { $('#printer2').attr('src',"images/placeholder/get_hardware/printer2_grey.png"); } } }); });
-28051711 0 How do I horizontally center this in Android (RelativeLayout)? I have the following code:
<TextView android:id="@+id/exercise_name_label" android:layout_width="match_parent" android:layout_height="32dp" android:text="Curls" android:gravity="bottom" android:layout_centerHorizontal="true" /> And I want the text to be aligned at the bottom of the 32dp and center horizontally..currently it's not centering horizontally:
I looked through the docs, and couldn't find a clear answer
Say I have a sparse index on [a,b,c]
Will documents with "a" "b" fields but not "c" be inserted to the index?
Is having the shard key indexed obligatory in the latest mongodb version ?
If so, is it possible to shard on [a] using the above compound sparse index? (say a,b will always exist)
I have a page, that lists a collection, that can be filtered. As there are some fancy effects (hover dimming) on these items, they have to be applied once the page has loaded.
This works fine, but when I select a criteria that hides an item, and then make it reappear by deleting that filter, these effects are no longer applied to these items.
I have tried to create a template.rendered function, but that only works on the first page load.
I also thought that adding a 'hover #mydiv: function () {...}' inside the template.events section could help, but that still doesn't work.
I have even tried to listen to the changes made in the drop-down ('change #myselect': function () {...}) where the filters can be applied, but that's not working either.
I also tried to tie it to a dependency, that is submitted when the criteria is selected, that has also failed.
Any suggestions what else should I try?
Thanks, Alex
Edit 1:
This is how I treat the filters:
in Template.search.events:
'change #search-skills-select': function () { Session.set('searchFilter', $('#search-skills-select').val()); } This then goes to:
/* This is of course properly handled for nulls, undefineds, etc. */ var searchFilterString = Session.get('searchFilter'); Profiles.find({profileAttributes: { $all: searchFilterString } });
-27054474 0 The issue was resolved when the project was migrated onto another machine. Apparently the error had nothing to with incorrectness related to RMI. Although, the cause of the error and why it didn't resolve even after re-building the project is still unknown.
-40599246 0 ArrayList not updating after using .clear()I'm new to Android development, so please bear with me.
I have a custom ArrayAdapter which I want to update by swiping down to refresh.
I understand that in order to do this I need to:
After I clear the ArrayList, call getAbsentTeachers() and notifyDataSetChanged() the ArrayList appears to remain empty even though getAbsentTeachers() is beeing called. I know this because nothing is displayed in my ListView.
getAbsentTeachers() populates the ArrayList fine when my app is first launched however it doesn't seem to work when I call it again to update the ArrayList.
Any ideas as to why the array is not beeing updated?
MainActivity.java: package uk.co.bobsmith.drawview.drawviewtest;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private ArrayList<Absent> absences = new ArrayList<>(); private SwipeRefreshLayout swipeContainer; @Override protected void onCreate(Bundle savedInstanceState) { //---------------------INITIALISING PARSE------------------------------- Parse.enableLocalDatastore(this); // Add your initialization code here Parse.initialize(new Parse.Configuration.Builder(getApplicationContext()) //Information obscured for privacy - tested and working though. .applicationId("") .clientKey(null) .server("") .build() ); ParseUser.enableAutomaticUser(); ParseACL defaultACL = new ParseACL(); // Optionally enable public read access. // defaultACL.setPublicReadAccess(true); ParseACL.setDefaultACL(defaultACL, true); ParseInstallation.getCurrentInstallation().saveInBackground(); ParsePush.subscribeInBackground("Absent"); //-----------------------CREATE ADAPTER OBJECT-------------------------------- getAbsentTeachers(); final ListView lv = (ListView)findViewById(R.id.listView); final ArrayAdapter<Absent> adapter = new absenceArrayAdapter(this, 0, absences); lv.setAdapter(adapter); swipeContainer = (SwipeRefreshLayout) findViewById(R.id.swipeContainer); // Setup refresh listener which triggers new data loading swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { // Code to refresh the list. absences.clear(); getAbsentTeachers(); adapter.notifyDataSetChanged(); swipeContainer.setRefreshing(false); // Call swipeContainer.setRefreshing(false) when finished. } }); } // Populates absences ArrayList with absence data public void getAbsentTeachers() { ParseQuery<ParseObject> query = ParseQuery.getQuery("Absences"); query.findInBackground(new FindCallback<ParseObject>() { @Override public void done(List<ParseObject> objects, ParseException e) { if(e == null){ for(ParseObject object : objects){ String name = String.valueOf(object.get("name")); Log.i("Name", name); String desc = String.valueOf(object.get("description")); Log.i("Description", desc); absences.add(new Absent(name, desc, "employees")); } } else { Log.i("Get data from parse", "There was an error getting data!"); e.printStackTrace(); } } }); } //custom ArrayAdapter class absenceArrayAdapter extends ArrayAdapter<Absent> { private Context context; private List<Absent> absencesList; public absenceArrayAdapter(Context context, int resource, ArrayList<Absent> objects) { super(context, resource, objects); this.context = context; this.absencesList = objects; } public View getView(int position, View convertView, ViewGroup parent) { //get the property we are displaying Absent teacher = absencesList.get(position); //get the inflater and inflate the XML layout for each item LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.custom_listview, null); TextView name = (TextView) view.findViewById(R.id.name); TextView description = (TextView) view.findViewById(R.id.description); ImageView teacherImage = (ImageView) view.findViewById(R.id.imageView); String teacherName = teacher.getTeacherName(); name.setText(teacherName); int descriptionLength = teacher.getDescription().length(); if(descriptionLength >= 75){ String descriptionTrim = teacher.getDescription().substring(0, 75) + "..."; description.setText(descriptionTrim); }else{ description.setText(teacher.getDescription()); } return view; } } }
-18509625 0 You can do this without LINQ, but I want to use LINQ here:
public IEnumerable<Control> GetControls(Control c){ return new []{c}.Concat(c.Controls.OfType<Control>() .SelectMany(x => GetControls(x))); } foreach(Control c in GetControls(splitContainer.Panel2).Where(x=>x is Label || x is Button)) MessageBox.Show("Name: " + c.Name + " Back Color: " + c.BackColor);
-19934143 0 regarding pointer type: the idea here is that in order to reduce both loop and copy overhead, you want to copy using the largest data "chunks" (say 32bit) possible. So you try to copy as much as possible using 32bit words. The remainder then needs to be copied in smaller 8bit "chunks". For example, if you want to copy 13 bytes, you would do 3 iterations copying 32bit word + 1 iteration copying a single byte. This is preferable to doing 13 iterations of single byte copy. You could convert to uint32_t*, but then you'll have to convert back to uint8_t* to do the remainder.
Regarding the second issue - this implementation will not work properly in case the destination address overlapps the source buffer. Assuming you want to support this kind of memcpy as well - it is a bug. This is a popular interview question pitfall ;).
-32048928 0Use the while statement:
while($row = $result->fetch_assoc()) { echo "First name:" . $row['fname']; echo " last name:" . $row['lname']; echo " Email:" . $row['email']; echo " Website:" . $row['website']; echo " comment:" . $row['comment']; }
-40954313 0 This will not work as:
typeof null === 'object'; So it will always return an object and hence your code will not work.
Rather you can try:
if (myNull == null){ // your code here. } Also can try as suggested by Scott, but the if else would be the other way round:
if (myNull){}
-9351599 0 According to http://ruby.about.com/od/rubyfeatures/a/envvar.htm, you can just write:
ENV['SOME_VAR'] = 'some_value'
-28013340 0 Size UILabel in UIPickerView to fit I want to make the text size in the pickerView to become smaller if the text does not fit in the label. For example, whenever the text shows like this "This is a test for somebo..." I want it to automatically size itself to a smaller size so it should fit. Here is the code I'm using:
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view { UILabel *lView = (UILabel *)view; if (!tView) { tView = [[UILabel alloc] init]; [tView setFont:[UIFont systemFontOfSize:15]]; tView.numberOfLines = [categorie count]; } tView.text = [categorie objectAtIndex:row]; return tView; } I tried to set the number of lines to 0 but that didn't solve my issue. I then tried to make the label sizeToFit, and that didn't work either.
I also tried making the label's frame height, taller, so it would be multiple lines, with didn't help either.
What did I get wrong?
-35503164 0 Fiori Launchpad : could not run custom App -Found negative cachei deployed an application on SAPUI5 Repository, when i added it to Fiori launchpad the app could not start and it's giving me the following error while debugging :
Uncaught Error: found in negative cache: 'com/emi/Component.js' from sap/bc/ui5_ui5/sap/zstatic/Component.js: 404 - NOT FOUND com.emi is my sapui5 Component specified in LPD_CUST
zstatic is the name of my app
Does anyone have any information about the cause of this ? thank you
-8241520 0 android play wave stream through tcp socketI don't know how to play live wave audio stream through socket. Now I have got the socket audio stream. the stream format :
wav format header +pcm data wav format header +pcm data wav format header +pcm data So how do i parse the live audio stream to play in the AudioTrack class in android. Thanks. Here is my code :
private void PlayAudio(int mode) { if(AudioTrack.MODE_STATIC != mode && AudioTrack.MODE_STREAM != mode) throw new InvalidParameterException(); long bytesWritten = 0; int bytesRead = 0; int bufferSize = 0; byte[] buffer; AudioTrack track; Socket socket=null; DataInputStream dIn=null; bufferSize = 55584; // i donnt know how much the buffer size should be. 55584 is the size that i got first from the socket stream. maybe the buffer size is setted wrong. //sample rate 16khz,channel: mono sample bits:16 bits channel:1 bufferSize = AudioTrack.getMinBufferSize(16000, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT); buffer = new byte[bufferSize]; track = new AudioTrack(AudioManager.STREAM_MUSIC, 16000, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize, mode); // in stream mode, // 1. start track playback // 2. write data to track if(AudioTrack.MODE_STREAM == mode) track.play(); try { socket = new Socket("192.168.11.123", 8081); dIn = new DataInputStream(socket.getInputStream()); // dIn.skipBytes(44); } catch (Exception e) { e.printStackTrace(); } try { do { long t0 = SystemClock.elapsedRealtime(); try { bytesRead = dIn.read(buffer, 0, buffer.length); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NullPointerException e) { // TODO Auto-generated catch block e.printStackTrace(); } bytesWritten += track.write(buffer, 0, bytesRead); Log.e("debug", "WritesBytes "+bytesRead); } while (dIn.read() != -1); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } I got mute when i running an activity, but i can hear some music intermittently in debug mode but it is noisy. Could you please help me ? the server send the stream 100ms interval: audio format : //sample rate 16khz,channel: mono sample bits:16 bits channel:1
-18598668 0 Specifying a subdomain in the route definition in ExpressI'm new to ExpressJS and NodeJS in general, so I need directions on how to achieve this effect:
app.get('/', 'sub1.domain.com', function(req, res) { res.send("this is sub1 response!"); }); app.get('/', 'sub2.domain.com', function(req, res) { res.send("this is sub2 response!"); } So that when I request sub1.domain.com the first handler reacts and on sub2.domain.com I get response from second handler. I've read some questions on SO about using vhost for this purpose, but I'd be more happy if what I described above worked rather than creating multiple server instances like in vhost.
As documented, the item's transformations are mathematically applied in a certain order - this is the order you'd be multiplying the transform matrices in and is, conceptually, the reverse of the order you'd normally think of.
transform is applied. The origin point must be included in the transform itself, by applying translations during the transform.transformations are applied - each of them can specify its own center.rotation then scale are applied, both relative to transformOriginPoint.When you set transform to scaling, and set rotation, the rotation is performed before scaling. The scaling applies to the rotated result - it simply stretches the rotated version horizontally in your case.
You need to somehow enforce the reverse order of operations. The only two ways to do that are:
Stack the transforms in correct order and pass them to transform, or.
Pass a list of correct transformations to transformations.
I'll demonstrate how to do it either way, in an interactive fashion where you can adjust the transform parameters using sliders.
To obtain the correct result using transform:
QGraphicsItem * item = ....; QTransform t; QPointF xlate = item->boundingRect().center(); t.translate(xlate.x(), xlate.y()); t.rotate(angle); t.scale(xScale, yScale); t.translate(-xlate.x(), -xlate.y()); item->setTransform(t); To obtain the correct result using transformations:
QGraphicsItem * item = ....; QGraphicsRotation rot; QGraphicsScale scale; auto center = item->boundingRect().center(); rot.setOrigin(QVector3D(center)); scale.setOrigin(QVector3D(center())); item->setTransformations(QList<QGraphicsTransform*>() << &rot << &scale); Finally, the example:

#include <QtWidgets> struct Controller { public: QSlider angle, xScale, yScale; Controller(QGridLayout & grid, int col) { angle.setRange(-180, 180); xScale.setRange(1, 10); yScale.setRange(1, 10); grid.addWidget(&angle, 0, col + 0); grid.addWidget(&xScale, 0, col + 1); grid.addWidget(&yScale, 0, col + 2); } template <typename F> void connect(F f) { connect(f, f, std::move(f)); } template <typename Fa, typename Fx, typename Fy> void connect(Fa && a, Fx && x, Fy && y) { QObject::connect(&angle, &QSlider::valueChanged, std::move(a)); QObject::connect(&xScale, &QSlider::valueChanged, std::move(x)); QObject::connect(&yScale, &QSlider::valueChanged, std::move(y)); } QTransform xform(QPointF xlate) { QTransform t; t.translate(xlate.x(), xlate.y()); t.rotate(angle.value()); t.scale(xScale.value(), yScale.value()); t.translate(-xlate.x(), -xlate.y()); return t; } }; int main(int argc, char **argv) { auto text = QStringLiteral("Hello, World!"); QApplication app(argc, argv); QGraphicsScene scene; QWidget w; QGridLayout layout(&w); QGraphicsView view(&scene); Controller left(layout, 0), right(layout, 4); layout.addWidget(&view, 0, 3); auto ref = new QGraphicsTextItem(text); // a reference, not resized ref->setDefaultTextColor(Qt::red); ref->setTransformOriginPoint(ref->boundingRect().center()); ref->setRotation(45); scene.addItem(ref); auto leftItem = new QGraphicsTextItem(text); // controlled from the left leftItem->setDefaultTextColor(Qt::green); scene.addItem(leftItem); auto rightItem = new QGraphicsTextItem(text); // controlled from the right rightItem->setDefaultTextColor(Qt::blue); scene.addItem(rightItem); QGraphicsRotation rot; QGraphicsScale scale; rightItem->setTransformations(QList<QGraphicsTransform*>() << &rot << &scale); rot.setOrigin(QVector3D(rightItem->boundingRect().center())); scale.setOrigin(QVector3D(rightItem->boundingRect().center())); left.connect([leftItem, &left]{ leftItem->setTransform(left.xform(leftItem->boundingRect().center()));}); right.connect([&rot](int a){ rot.setAngle(a); }, [&scale](int s){ scale.setXScale(s); }, [&scale](int s){ scale.setYScale(s); }); right.angle.setValue(45); right.xScale.setValue(3); right.yScale.setValue(1); view.ensureVisible(scene.sceneRect()); w.show(); return app.exec(); }
-31465860 0 I think teamnorge is on the right track His code won't work as posted, though, since the array isn't mutable.
Make your property a mutable array. Have the base class create it it init's init method:
In your base class header:
@property (nonatomic, retain) NSMutableArray *ignoreProperties; Then in the init for your base class:
-(instanceType) init; { self = [super init]; if (!self) return nil; self.ignoreProperties = [@[@"property1"] mutableCopy]; } And in the init for your subclass:
-(instanceType) init; { self = [super init]; if (!self) return nil; [self.ignoreProperties addObject: @"property2"]; //or to add multiple objects... NSArray *newProperties = @[@"property2", @"property3"]; [self.ignoreProperties addObjectsFromArray: newProperties]; } For efficiency's sake, it might be better to make the array immutable and have the subclass's init method replace it with a an array created using arrayByAddingObject or arrayByAddingObjectsFromArray. (Immutable objects are less costly for the system than their mutable forms. In this case the array of properties will only be created once at initialization of your class, and then persist for it's lifetime.)
setInterval(function(){ object.style.backgroundColor=bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)]; },5000);
-2461311 0let Tlist_WinWidth = somenumber
-3109928 0 StringBuffer has a reverse: http://java.sun.com/j2se/1.4.2/docs/api/java/lang/StringBuffer.html#reverse()
BTW, I assume you meant O(n) because O(1) (as other people have mentioned) is obviously impossible.
-13897153 0Where you have:
<Directory /home/bitnami/public_html/http/flasktest1> WSGIProcessGroup flaskapp WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all </Directory> it should be:
<Directory /home/bitnami/public_html/http> WSGIProcessGroup flaskapp WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all </Directory> as you are neither running your app in daemon mode or in the main interpreter because of the directives being in the wrong context.
That Directory directive then conflicts with one for same directory above so merge them.
If using mod_wsgi 3.0 or later count instead perhaps drop that second Directory block and use:
WSGIDaemonProcess flaskapp threads=5 WSGIScriptAlias /flasktest1 /home/bitnami/public_html/wsgi/flasktest1.wsgi process-group=flaskapp application-group=%{GLOBAL} Note that processes=1 has been dropped as that is the default and setting it implies other things you likely don't want. You also don't need to set user/group as it will automatically run as the Apache user anyway.
-17006619 0The type inference is just a shortcut for an unnecessarily long way of instantiating paremeterized types. Generics are still implemented by type-erasure, so your bytecode will only have the raw types.
-27259809 0First of all don't add the validator (or anything else for that matter) into vendor namespaces. Instead put it somewhere within your application code. Don't know how your app is structured, but lets say ./module/YourModule/src/YourModule/Validator/ZendValidatePesel.
Then reference your validator class with a full, qualified name, so following my guess it'd be something like:
'validators' => array( array( 'name' => 'YourModule\Validator\ZendValidatePesel', 'options' => array( // ... ), ), As far as I know that will directly instantiate the validator for you. Not-so-fun-fact: even if you'd register your validator there under the same name as the fqcn, it won't go through the ValidatorPluginManager -- something that I hope will be, or already is fixed in the framework (if it is somebody let me know, because it'd love to have validators with dependencies at last).
We're doing this:
$(document).on("pagecontainershow", function() { var activePage = $.mobile.pageContainer.pagecontainer("getActivePage"); var activePageId = activePage[0].id; if(activePageId != 'splashPage') { //fix rotation splash flash bug $("#splashPage").hide(); } else { $("#splashPage").show(); } switch(activePageId) { case 'loginPage': loginPageShow(); break; case 'notificationPage': notificationPageShow(); break; case 'postPage': postPageShow(); break; case 'profilePage': profilePageShow(); break; case 'splashPage': splashPageShow(); break; case 'timelinePage': timelinePageShow(); break; default: break; } }); And navigation works like this:
$.mobile.loading('hide'); $(":mobile-pagecontainer").pagecontainer("change", "#timelinePage", { transition: 'none' });
-15606436 0 Here is a very basic attempt in Python:
import pylab as pl data = pl.array([[1,2],[2,3],[1,3],[2,1],[5,3],[3,2],[3,2],[1,1]]) first = data[:,0] second = data[:,1] xs = [] ys = [] for r in data: ys += list(r) ys.append(None) xs += [1.3,1.7] xs.append(None) pl.plot([1.3]*len(first),first,'o',[1.7]*len(second),second,'o',xs,ys) pl.boxplot(data) pl.ylim([min(min(first),min(second))-.5,max(max(first),max(second))+.5]) labels = ("first", "second") pl.xticks([1,2],labels) pl.show() will result in: 
Issue was with JTDS driver as soon as I switched to JConnect driver everything began to work as expected.
-37130139 0A lot of misconception here.
blob is not a Blob, but a string, the url of .file-preview-image.onload callback of the FileReader, you are just checking if the result is equal to an undefined variable dataURI. That won't do anything. console.log the call to readAsDataURL which will be undefined since this method is asynchronous (you have to call console.log in the callback). But since I guess that what you have is an object url (blob://), then your solution is either to get the real Blob object and pass it to a FileReader, or to draw this image on a canvas, and then call its toDataURL method to get a base64 encoded version.
If you can get the blob :
var dataURI; var reader = new FileReader(); reader.onload = function(){ // here you'll call what to do with the base64 string result dataURI = this.result; console.log(dataURI); }; reader.readAsDataURL(blob); otherwise :
var dataURI; var img = document.querySelector(".file-preview-image"); var canvas = document.createElement('canvas'); canvas.width = img.width; canvas.height = img.height; canvas.getContext('2d').drawImage(img, 0,0); dataURI = canvas.toDataURL(); But note that for the later, you'll have to wait that your image actually has loaded before being able to draw it on the canvas.
Also, by default, it will convert your image to a png version. You can also pass image/jpegas the first parameter of toDataURL('image/jpeg') if the original image is in JPEG format.
If the image is an svg, then there would be an other solution using the <object> element, but except if you really need it, I'll leave it for an other answer.
I have a storm topology that subscribes events from Kafaka queue. The topology works fine while the number of workers config.setNumWorkers is set to 1. When I update the number of workers to more than one or 2, the KafkaSpout fails to acknowledge the messages while looking at storm UI. What might be the possible cause, I am not able to figure out, the exactness of problem.
I have a 3 node cluster running one nimbus and 2 supervisors.
-16418755 0The entire difference is like you said, in texture caching. So choosing between either of these methods depends on whether or not you will want to exploit texture caching in your visualization. Lets look at some common cases:
a) If you want to calculate how a surface is deformed (for example the surface of water, or maybe some elastic deformation) and you need to know the new vertices for the surface's polygonal mesh then you would typically use Buffers (Number one), except you wouldn't need to copy to an OpenGL texture here. In fact there would be no copying involved here, you would just reference the buffer in CUDA and use it as a gl buffer.
b) If you have a particle simulation and need to know the updated particle's position, you would also just use a buffer as in the above case.
c) If you have a finite element grid simulation, where each fixed volume cell in space would gain a new value and you need to visualize it via volume rendering or isosurface, here you would want to use a texture object (2D or 3D depending on the dimensionality of your simulation), because when you're casting rays, or even generating streamlines you will almost always be needing to immediately have the neighboring texels cached. And you can avoid doing any copying here, as in the above method you could also directly reference some CUDA texture memory (cudaArray) from OpenGL. You would use these calls to do that:
cudaGraphicsGLRegisterImage( &myCudaGraphicsResource, textureNameFromGL, GL_TEXTURE_3D,...) ... cudaGraphicsMapResources(1, myCudaGraphicsResource) cudaGraphicsSubResourceGetMappedArray(&mycudaArray, myCudaGraphicsResource, 0, 0) cudaGraphicsUnMapResources(1, myCudaGraphicsResource) and so this texture data in CUDA can be referenced by mycudaArray while this same memory in OpenGL can referenced by textureNameFromGL.
Copying from a buffer into a texture is a bad idea because if you need this data for texture caching you will be doing the additional copy. This was more popular in the earlier versions of CUDA before texture interop was supported
You could also use textures in the a) and b) use cases as well. With some hardware it might even work faster, but this is very hardware dependent. Keep in mind also that texture reading also applies minification and magnification filters which is extra work if all you're looking for is an exact value stored in a buffer.
For sharing textures resources with CUDA and OpenGL please refer to this sample
https://github.com/nvpro-samples/gl_cuda_interop_pingpong_st
-10604065 0 How do you replace multiple instances of '+' in a string in JavaScript?I have a URL that I need to manipulate. I cant seem to replace all the '+' within a query string with whitespace.
var url = window.location.replace(/+/g, ' '); What am I doing wrong here?
Or is there a better method?
-24652309 0The function OnePlusNumber(x); return a Integer.
Replace it with x = OnePlusNumber(x);
I am writing unit tests for my angular 2 component with Jasmine framework and somehow Jasmine always skips my spec if I include directives not from the angular original module (in my case the test only works with directives for example from angular/core and angular/common). This is my app component:
import {Component, Input, OnInit} from '@angular/core'; import {NgStyle} from '@angular/common'; import { CollapseDirective } from 'ng2-bootstrap/components/collapse'; import {MdButton} from '@angular2-material/button'; import { MdDataTable } from 'ng2-material'; import { EntityFilterPipe } from './entity-filter.pipe'; import { NgFor } from '@angular/common'; @Component({ selector: 'test', templateUrl: 'app/entity.html', pipes: [EntityFilterPipe], directives: [NgStyle, NgFor, CollapseDirective] }) export class EntityTestComponent implements OnInit { public title = 'Entities'; @Input() name:string; showSearch: boolean = true; listFilter:string; toggleSearch(): void { this.showSearch = !this.showSearch; } ngOnInit() { console.log("printed"); } } And this is my spec:
import {describe, it, beforeEach, inject, expect, beforeEachProviders } from '@angular/core/testing'; import { ComponentFixture, TestComponentBuilder } from '@angular/compiler/testing'; import { EntityTestComponent } from './entity-test.component'; export function main() { describe('Entity component', () => { let tcb: TestComponentBuilder; beforeEachProviders(() => [TestComponentBuilder, EntityTestComponent]); beforeEach(inject([TestComponentBuilder], (_tcb: TestComponentBuilder) => { tcb = _tcb })); it('should display no item found when item is not on the list', done => { //expect(true).toBe(true); tcb.createAsync(EntityTestComponent).then(fixture => { let property = fixture.componentInstance; expect(property.showSearch).toBe(true); done(); }) .catch(e => done.fail(e)); }); The spec is run if I only include NgStyle and NgFor in my list directives. When I tried including anything from different libraries, such as CollapseDirective or MdDataTable, the spec is skipped -- jasmine test does not show success or failure. Any suggestion is much appreciated! Thanks
-23405271 0 Change the PegMan position on a Google mapI've succeeded in moving all other controls on a Google map with the following small screen css:
div.gmnoprint, div.gmnoprint:nth-child(8) > div:nth-child(2) > div:nth-child(4) > img:nth-child(1) { padding-top: 130px; } This is needed to move the map controls below a logo on a mobile/small screen version of a site. The pan, zoom and map type controls all move correctly but the Peg Man stays in its original position which is behind the site logo (which I can't move easily).
The element identifier used in the above css is what the Firefox inspector claims is the Peg Man image but I've also tried removing weekend from the end of that identifier to modify the div tags rather than the image - the Peg Man just won't move!
You can see the problem at http://www.BlueBadgeParking.com on device with a screen size of less than 400px.
-36344126 0 Cleaning a segmented image in OpencvI have this original:
After segmentation I obtained this image:
As you can see it is still not perfectly segmented. Any suggestions on how to further "clean" this segmented image? Here is my code:
using namespace cv; using namespace std; Mat COLOR_MAX(Scalar(65, 255, 255)); Mat COLOR_MIN(Scalar(15, 45, 45)); int main(int argc, char** argv){ Mat src,src2,hsv_img,mask,gray_img,initial_thresh,second_thresh,add_res,and_thresh,xor_thresh,result_thresh,rr_thresh,final_thresh; // Load source Image src = imread("banana2.jpg"); src2 = imread("Balanced_Image1.jpg"); imshow("Original Image", src); cvtColor(src,hsv_img,CV_BGR2HSV); imshow("HSV Image",hsv_img); //imwrite("HSV Image.jpg", hsv_img); inRange(hsv_img,COLOR_MIN,COLOR_MAX, mask); imshow("Mask Image",mask); cvtColor(src,gray_img,CV_BGR2GRAY); adaptiveThreshold(gray_img, initial_thresh, 255,ADAPTIVE_THRESH_GAUSSIAN_C, CV_THRESH_BINARY_INV,257,2); imshow("AdaptiveThresh Image", initial_thresh); add(mask,initial_thresh,add_res); erode(add_res, add_res, Mat(), Point(-1, -1), 1); dilate(add_res, add_res, Mat(), Point(-1, -1), 5); imshow("Bitwise Res",add_res); threshold(gray_img,second_thresh,150,255,CV_THRESH_BINARY_INV | CV_THRESH_OTSU); imshow("TreshImge", second_thresh); bitwise_and(add_res,second_thresh,and_thresh); imshow("andthresh",and_thresh); bitwise_xor(add_res, second_thresh, xor_thresh); imshow("xorthresh",xor_thresh); bitwise_or(and_thresh,xor_thresh,result_thresh); imshow("Result image", result_thresh); bitwise_and(add_res,result_thresh,final_thresh); imshow("Final Thresh",final_thresh); erode(final_thresh, final_thresh, Mat(), Point(-1,-1),6); bitwise_or(src,src,rr_thresh,final_thresh); imshow("Segmented Image", rr_thresh); imwrite("Segmented Image.jpg", rr_thresh); waitKey(0); return 1; }`
-7169872 0 You override the global language setting in your user defaults by calling
[[NSUserDefaults standardUserDefaults] setObject:@"YOURCOUNTRY" forKey:@"AppleLanguages"]; However by doing this your user will have to restart the application unless you call this in the main() method before UIApplicationMain() is called
Edit: look here for an example on how to do this.
-35755334 0 Android Gridview with ImageButtons and TextViews. Items in gridview not lining upI've got a view that has a GridView with Image Buttons and Textviews but whenever the textviews that are multi line the items are not lining up as shown below. I could set the TextView as
android:singleLine="true" But I prefer not to.
GridView code :
<GridView android:id="@+id/gridview" android:layout_width="fill_parent" android:layout_height="match_parent" android:columnWidth="90dp" android:numColumns="auto_fit" android:layout_marginRight="10dp" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:layout_marginBottom="10dp" android:verticalSpacing="10dp" android:horizontalSpacing="10dp" android:stretchMode="columnWidth" android:gravity="center" android:layout_weight="1" /> Template for ImageButton and TextView called by BaseAdapter :
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="10dp" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:layout_marginBottom="10dp" android:id="@+id/MainMenuImageButton" android:layout_alignParentRight="true" android:scaleType="fitCenter" /> <TextView android:id="@+id/MainMenuTextView" android:layout_width="match_parent" android:layout_height="wrap_content" android:fontFamily="trebuchet" android:layout_marginLeft="10dp" android:textColor="@android:color/black" android:singleLine="true" android:textSize="15sp" android:textStyle="bold" /> </LinearLayout> If you have a suggestion I'd appreciate it. Thank you.
-35758255 0 Creating a JSONPATH Query TalendI am using CurrencyLayer to convert the following format in Talend. This is what the format looks like:
{ "success":true, "terms":"https:\/\/currencylayer.com\/terms", "privacy":"https:\/\/currencylayer.com\/privacy", "timestamp":1456950010, "source":"GBP", "quotes":{ "GBPUSD":1.406921, "GBPCAD":1.889923 } } { "success":true, "terms":"https:\/\/currencylayer.com\/terms", "privacy":"https:\/\/currencylayer.com\/privacy", "timestamp":1456950010, "source":"EUR", "quotes":{ "EURUSD":1.08665, "EURCAD":1.459701 } } { "success":true, "terms":"https:\/\/currencylayer.com\/terms", "privacy":"https:\/\/currencylayer.com\/privacy", "timestamp":1456950010, "source":"USD", "quotes":{ "USDCAD":1.343305 } } { "success":true, "terms":"https:\/\/currencylayer.com\/terms", "privacy":"https:\/\/currencylayer.com\/privacy", "timestamp":1456950010, "source":"CAD", "quotes":{ "CADUSD":0.744433 } } Each will be a seperate API call.
My database format looks like the following: CurrFrom, CurrTo, Rate, Date.
Within Talend, I have created the FileInput using this URl and I can parse the timestamp, source. But how would I get the USD, CAD, and their respective rates and how would that be mapped to input into the database itself.
help would be appreciated.
-32135853 0Try this:
<field name="organization_type_id" domain="[('id', 'in', parent_id.organization_type_id.allowed_children_ids.ids)]" /> While allowed_children_ids is a set of records, allowed_children_ids.ids is a list of ids of those records.
You can also approach this from the other side. This should work and be event faster:
<field name="organization_type_id" domain="[('allowed_parent_type_ids', '=', parent_id.organization_type_id)]" />
-24581082 0 I am using Android Studio 0.8.1. I have a project's gradle file like below:
android { compileSdkVersion 19 buildToolsVersion "20.0.0" defaultConfig { applicationId "com.omersonmez.widgets.hotspot" minSdkVersion 15 targetSdkVersion 19 versionCode 1 versionName "1.0" } buildTypes { release { runProguard false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } My emulator was android 4.0. So i modified my emulator and made api level 4.0.3(apilevel 15). It worked.
-27255894 0Basically, your regular expression is recursive. Removing the final .+ solves the issue. Here is a good article on avoiding it in the future. Why does .NET hang? Probably because it will never abort the search. Perhaps the JavaScript parser you used aborts if it detects too many steps or goes too deep into recursive searches.
See the first input field for full width:
<form method="post" class="mobile-login-form _5spm" id="u_0_0" novalidate="1" data-autoid="autoid_1"><input name="lsd" value="AVpe_Wp1" autocomplete="off" type="hidden"><input name="charset_test" value="€,´,€,´,水,Д,Є" type="hidden"><input name="version" value="1" type="hidden"><input id="ajax" name="ajax" value="0" type="hidden"><input id="width" name="width" value="0" type="hidden"><input id="pxr" name="pxr" value="0" type="hidden"><input id="gps" name="gps" value="0" type="hidden"><input id="dimensions" name="dimensions" value="0" type="hidden"><input name="m_ts" value="1421117640" type="hidden"><input name="li" value="yIi0VOqdqMbfGzXVr-lypMC-" type="hidden"><div class="_56be _5sob"><div class="_55wo _55x2 _56bf"><input style="width: 100%;" autocorrect="off" autocapitalize="off" class="_56bg _55ws _5ruq" name="email" placeholder="Email Address" type="email"><p><input autocorrect="off" autocapitalize="off" class="_56bg _55ws _5ruq" placeholder="Password" name="pass" id="password" type="password"></p><div class="_55ws"><button type="submit" value="Submit" class="_56bs _56b_ _56bw _56bu" name="login" id="u_0_1" data-sigil="touchable"><span class="_55sr">Submit</span></button></div></div></div><noscript><input type="hidden" name="_fb_noscript" value="true" /></noscript></form> It's this line:
<input style="width: 100%;" autocorrect="off" autocapitalize="off" class="_56bg _55ws _5ruq" name="email" placeholder="Email Address" type="email">
-2345527 0 There's a Python script (referenced here: http://subversion.tigris.org/ds/viewMessage.do?dsForumId=1065&dsMessageId=2369399). I'd either use that, or translate it to .NET if you needed to.
-19360349 0you could try wrapping your message in a <pre>...</pre> tag, so linebreaks get rendered by the browser :-)
That is very strange my opinion to you.
First go to Build(top on the android studio)-> Clean project -> Build APK -> Generate signed APK. If this will not help you than go to. app\build\outputs\apk and delete your apk. and again build signed APK.
-842967 0I have now switched from wsDualHttpBinding to NetTcpBinding and for some reason, everything is working fine.
I have used this article to help me set up hosting on IIS, and thankully everything is working as expected, with callbacks.
-33267366 0Here is my modified mulerequester as per Ryan's suggestion. It uses both connector and selector as Uri params.
<mulerequester:request config-ref="Mule_Requester" resource="wmq://REPLY.QUEUE?connector=wmqConnector&selector=JMSCorrelationID%3D'#[sessionVars.myCorrelationId]'" doc:name="Mule Requester" timeout="120000"/>
-9767753 0 Insert multiple rows into table from a variable in PHP for Mysql & Oracle tables I am fetching data from some tables & storing it in a variable like below-:
$result = mysql_query("SELECT * FROM sample where column=mysql_insert_id()"); while($row=mysql_fetch_array($result)) { $str = "'". $row["name"] . "',". "'" . $row[quantity] . "'," . "'" . $row["id"]; } So in my variable $str, suppose I have following values-:
shirt,10,1,pant,50,2....i.e. it will store values in a comma separated format. Now I want to insert these values in another table say test-:
$qry = "INSERT INTO test(name,quantity,id)values(".$str."); Now I want to store values in test table in two rows like-:
shirt 10 1 pant 50 2 So how to do the same for Mysql & Oracle tables?
Plz help
See my below query-:
$query2 = "SELECT sfoi.name, sfoi.sku, sfoi.qty_ordered, sfoi.price, sfoi.row_total, sfo.base_subtotal, sfo.base_shipping_amount, sfo.base_grand_total, (select mso.order_primary from mysql_sales_order mso where mso.increment_id =sfo.increment_id) FROM sales_flat_order sfo JOIN sales_flat_order_item sfoi ON sfoi.order_id = sfo.entity_id WHERE sfo.increment_id = ". $order_id ; $result_query2 = mysql_query($query2); So for one order id i.e. for one order may contain more than 1 products i.e. many name,sku,quantity ordered etc. So at the time of mysql_fetch_array(), I want all product data in a single variable...my code for fetching is like this-:
while($row = mysql_fetch_array($result_query2)) { $string = "'". $row["name"] . "',". "'" . $row["sku"] . "'," . "'" . $row["qty_ordered"] . "',". "'" . $row["price"] . "'," . "'" . $row["row_total"] . "'," . "'" . $row["base_subtotal"]. "'," . "'" . $row["base_shipping_amount"] . "'," . "'" . $row["base_grand_total"] ."'," . $row["prod_foreign"]; $query3 = "INSERT into mysql_sales_product(name, sku, qty_ordered, price, row_total, base_subtotal,base_shipping_amount,base_grand_total,prod_foreign) VALUES(".$string.")"; } $result_query_product_outbound = mysql_query($query3); Here I want to store result of mysql_ fetch_array in variable in such a way that if there are multiple rows I can still able to pass those rows using variable$string. e.g-:
name sku qty_ordered price row_total subtotal shipping_amnt grand_total prod_foreign nokia nk 2 500 1000 1000 300 1300 11 sansung sam 3 400 1200 1200 500 1700 30 sony sny 4 200 800 800 200 1000 45
-12926976 0 Display the title and year for all of the films that were produced in the same year as any of the SH and CH films Display the title and year for all of the films that were produced in the same year as any of the SH and CH films.
how would I bring up a result table showing the titles of the movies that were also made in same years as the movies from genre column?
table name (movies) year column (YR) genre column (genre) genre (SH) (CH) i really don't know how i would put this all together any help would be appreciated.
-33927174 1 Django reverse url to onetoonefield on successGood day SO!
Recently I've started working on Django, got myself a situation which I can't find the right solution on the web to solve it. So I've got a little question about URL reversing on a success. Currently when an user successfully creates an account, the user gets reversed to a profile based on the user_id which just got created:
class Create(CreateView): form_class = UserCreateForm # inherits from django's UserCreationForm def get_success_url(self): return reverse('users:profile', kwargs={'pk': self.object.pk}) This is working properly. Now I created a profile module with a OneToOneField to the django.auth.models User model. When creating a new account, a signal is send to the create_profile_on_registration method.
@receiver(post_save, sender=User) def create_profile_on_registration(sender, created, instance, **kwargs): ... This is also working properly, a new profile is created on user account registration. Now I would like to reverse the user to the new created profile_id instead of the user_id. However, I cant figure out exactly how to get this properly to work. Can you give me a little push in the right direction on how to approach this issue? I can't match up the right google search words or find any examples which explains or shows how to achieve this properly.
Thanks in advance!
-6019294 0 Loading a cookie and posting data with curlIf I load in a cookie, I am able to get to the page that requires cookies, like this:
$cookie = ".ASPXAUTH=Secret"; curl_setopt($ch, CURLOPT_COOKIE, $cookie); No problem here, I can run curl_exec, and see the page that requires cookies.
If I also want to send some post data, I can do like this:
$data = array( 'index' => "Some data is here" ); $cookie = ".ASPXAUTH=Secret"; curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_COOKIE, $cookie); I have set up a dump script on my local server, to see if it is working. If i send only the cookie, I can see it in the http headers, and if I send only the post data, I can see the post data.
When I send both, I see only the cookie.
Why?
-15175243 0 Grouping elements under a new node in xsltI need to group some elements together and pull them together under a new element.
Below is a sample record, I would like to group together the address information into an additional layer.
Here is the original record -
<Records> <People> <FirstName>John</FirstName> <LastName>Doe</LastName> <Middlename /> <Age>20</Age> <Smoker>Yes</Smoker> <Address1>11 eleven st</Address1> <Address2>app 11</Address2> <City>New York</City> <State>New York</State> <Status>A</Status> </People> </Records> expected Result: I need to group address data under a new element as such -
<Records> <People> <FirstName>John</FirstName> <LastName>Doe</LastName> <Middlename /> <Age>20</Age> <Smoker>Yes</Smoker> <Address> <Address1>11 eleven st</address1> <Address2>app 11</address2> <City>New York</City> <State>New York</State> </Address> <Status>A</Status> </People> </Records> Any help would be great! Thank you
-6520737 0[] notation will make it possible to transmit array data in a form.
Name the checkboxes in the form like this:
<input name="area[]" type="checkbox" value="51-75"> this should build an array of all selected check boxes.
-5801654 0var util = require("util"), http = require("http"); var options = { host: "www.google.com", port: 80, path: "/" }; var content = ""; var req = http.request(options, function(res) { res.setEncoding("utf8"); res.on("data", function (chunk) { content += chunk; }); res.on("end", function () { util.log(content); }); }); req.end();
-24930555 0 I don't understand what exactly you are trying to do. If you want to get an array of pointers from your array of structs, you will need to make a loop. It would look like this (i did not try it)
person * friends_ptrs[NUM_OF_FRIENDS]; for (int i = 0; i < NUM_OF_FRIENDS; i++) friends_ptrs[i] = friends + i;
-24840539 0 if statement to check number of days in a month I am writing a simple program in asp.net mvc5 that will display a calendar. I have an array that stores the months and days 1-31. I would like to use an if statement to check for the month to allow only the appropriate number of days. I am really new to mvc and would appreciate any suggestions on how to accomplish this.
-5358680 0Yes, that is a much more complicated task. You're going to have to store the last modified time into a database (since you're saying users can modify their profile content I'll assume you already have a database). The easiest way to get the last time the user modified their profile depends on your schema.
To put it another way... what the user is actually modifying isn't "profile.php", it's some data that lives elsewhere, e.g. a MySQL database; so the system that's going to know when the user last modified it is that external data source.
-16070455 0Why wouldn't be corrupted? You are opening a document, getting all of the child elements, and writing them to the same document. I am not sure what is that supposed to do.
-22663157 0Overdispersion isn't really a useful concept in the normal model because it is already fitting a variance for the variability at the observation level. So the error message is telling you that you can't have a grouping factor at the observation level. In that sense, yes, you are trying to overfit your model.
In a poisson (or other glm) model, however, it does make sense, because the variability at the observation level is fixed according to whatever the variance term in the glm is, so it does make sense to add an additional variance term to the model to account for any extra variability at the observation level. Hence glmer does not do the same check that lmer does.
This question has been answered already, but I want to point out that form_open() without any arguments would do exactly what you want (creating an action="").
So you can simply use the snippet below:
<?php echo form_open(); ?> Here is a reference from the CodeIgniter's Source:
function form_open($action = '', $attributes = '', $hidden = array())
-22744791 0 if you do not set a stroke-width , defaut value is 1 for 1 pixel:
Try this :
<svg height="30px"><text x="0" y="20" stroke-width="0" stroke="#000000">bla - svg stroke width 0</text></svg> <svg height="30px"><text x="0" y="20" stroke="#000000">bla - svg stroke no width defined</text></svg> <svg height="30px"><text x="0" y="20" stroke-width="1" stroke="#000000">bla - svg stroke width 1</text></svg> <svg height="30px"><text x="0" y="20" stroke-width="2" stroke="#000000">bla - svg stroke width 2</text></svg> text-stroke is actually avalaible in webkit , using vendor prefix. So is text-fill.
In near futur it could be avalaible in other browser too , check it out here : http://caniuse.com/text-stroke
To stroke text in CSS, you need to use multiple text-shadow to increase as much as needed the shadow to turn it into a full strike color .
http://codepen.io/anon/pen/xklIi/
(as bigger is the shadow used for stroke effect, as much it needs to be repeated, redrawn)
/* using CSS3 selector filters older browser, you can reset freely letter-spacing here */ [data-stroke="1"] {/* class can be used */ text-shadow: 0 0 1px red, 0 0 1px red, 0 0 1px red, 0 0 1px red, 0 0 1px red, 0 0 1px red, 0 0 1px red, 0 0 1px red, 0 0 1px red; } [data-stroke="2"] { letter-spacing:2px /* you might need to reset letter-spacing to keep text readable */ text-shadow:/* repeat until sharp enouggh */ 0 0 2px red, 0 0 2px red, 0 0 2px red, 0 0 2px red, 0 0 2px red, 0 0 2px red, 0 0 2px red, 0 0 2px red, 0 0 2px red, 0 0 2px red; } HTML
<p data-stroke="1">bla - text stroke width 1</p> <p data-stroke="2">bla - text stroke width 2</p> <p data-stroke="2sharp">bla - text stroke sharp width 2</p>
-15692565 0 I would suggest to create an Items constructor
Items(string weapon, string armour, int gold); And change your player constructor to
Player(int health, int stamina, int keys, Items items); You can then aggregate Items in Player.
If you look at the source code in http://webtimingdemo.appspot.com/ it runs the code AFTER onload (setTimeout('writeTimings()', 0)), your code runs in $(document).ready() which runs before onload as it runs on DOMContentLoaded in Chrome.
I have put a setTimeout into your code and now it works: See http://jsbin.com/acabo4/8
var performance = window.performance || window.mozPerformance || window.msPerformance || window.webkitPerformance || {}; var timing = performance.timing || {}; function getTiming(timingStr) { if (!timing) return 0; var time = timing[timingStr]; return time; } var loadTime = (new Date().getTime() - getTiming("navigationStart"))/1000; $(document).ready(function() { setTimeout(function(){ var perflist = '<ul id=perflist>'; for(var performer in timing){ var j = getTiming(performer); perflist += '<li>' + performer + ' is: ' + j + '</li>'; } perflist += '</ul>'; $("body").prepend(perflist); $("#adminmenu").prepend("<li>Load time : " + loadTime + " seconds</li>") }, 100); });
-25815603 0 on the first how did you run your App? I noticed that when i run an App in Debugmode, the Debugger eats 50% of the performance of my mobile Device. So if you just run your App the onFinish works much faster.
A second point is to detect the timeout manually in the onTick Method an block the taps after some time with a boolean
private boolean tapBlock = false; private void beginTimer() { new CountDownTimer(10100, 1000) { public void onTick(long millisUntilFinished) { if (!tapBlock) { time.setText("Time: "+millisUntilFinished/1000); if (millisUntilFinished<100) { tapBlock = true; } } } public void onFinish() { time.setText("Timeout!!!"); finalTap++; tapBlock = false; } }.start(); } This is a bit around but its maybe faster and you have to add the "tapBlock" to the update method
-33730659 0With all the hints I found out that DataGridTextColumn is neither part of the visual tree nor of the logical tree. That should be the reason why ElementName and RelativeSource do not work. This answer regarding DataGridTextColumn explains that and gives a possible solution with Source and x:Reference: DataGridTextColumn Visibility Binding
The answer of @Anand Murali works but cannot be applied to Visibility - that was not part of the question because I minimalized that away. So I accept that one and will give more information in this one.
Using x:Reference for Visibility it can turn out like:
<DataGridTextColumn Binding="{Binding Data.OrderNumber}" Header="Order Number" Visibility="{Binding DataContext.ShowColumnOrderNumber, Source={x:Reference LayoutRoot}, Converter={StaticResource BooleanToVisibilityConverter}}" /> But: I my example I use a ControlTemplate and to have x:Reference to work this template must be within a .Resources XAML part in the same file and cannot be in an external ResourceDictionary. In the latter case the reference will not work because it cannot be resolved. (If someone knows a solution to that it would be welcome)
It can happen, that the string has nothing inside, than it is "None" type, so what I can suppose is to check first if your string is not "None"
# Extracting the sites def CiteParser(content): soup = BeautifulSoup(content) #print soup print "---> site #: ",len(soup('cite')) result = [] for cite in soup.find_all('cite'): if cite.string is not None: result.append(cite.string.split('/')) print cite return result
-16611423 0 Send picture from android phone to a local web server I've been searching all over and found a bunch of examples of ways to send a picture to a web server. So far none have quite worked for me. Maybe I started in the wrong end but I've already written the code for the controller which is to take care of the received picture.
I'm using a Tomcat web server and written all the code on the server side with Spring Tool Suite with the MVC Framework. The controller is written like this:
@RequestMapping(value = "/upload", method = RequestMethod.POST) public String handleFormUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) throws IOException { if (!file.isEmpty()) { byte[] bytes = file.getBytes(); // store the bytes somewhere return "redirect:uploadSuccess"; } else { return "redirect:uploadFailure"; } } The .jsp is written like this:
<html> <head> <title>Upload a file please</title> </head> <body> <h1>Please upload a file</h1> <form method="post" action="/form" enctype="multipart/form-data"> <input type="text" name="name"/> <input type="file" name="file"/> <input type="submit"/> </form> </body> So basically what I'd like to know:
How can I write a class/method that sends a picture from my phone to the web server?
I appreciate all the help I can get!
-7029215 0oh, I just got what you mean by total revenue going down, weird...
I suppose total revenue is only shown for the period of time selected, if you view a 30 or 90 days window, total revenue going down means the revenue over that period is lower than it was for the previous same-length period.
Check "pending earning"s to see the all-time total amount on your account.
-7432259 0 VBA Excel VerticalAlignment = xlCenter not workingThe below code selects the sheet but fails to align the cells to center.
wb.Sheets(1).Columns("A:L").Select With Selection .VerticalAlignment = xlCenter End With Thanks!
wb.Sheets(1).Activate wb.Sheets(1).Columns("A:L").Select With Selection .VerticalAlignment = xlCenter End With Selects the entire sheet but it's not changing the vertical alignment to center.
wb.Sheets(1).Columns("A:L").VerticalAlignment = xlCenter Does nothing.
I don't want HorizontalAlignment :)
I found out the column has VerticalAlignment set to xlCenter but the Cells underneath the column do not have VerticalAlignment set to xlCenter.
-2459230 0the solution was in the -validateMenuItem code... I wasnt checking for a return value of null somewhere that method and it was logically returning false.
-11144267 0If you use Three20, you can try this extension:
https://github.com/RIKSOF/three20/tree/development/src/extThree20Facebook
It allows you to use all Graph API features with just a few line of code.
-16750242 0This is because you are effectively only using data1.
The first loop can be expanded to
data1 = read.table('data1_lambda.dat', ...) data2 = read.table('data2_lambda.dat', ...) data3 = read.table('data3_lambda.dat', ...) whereas your second loop is a bit buggy and the cause of the fault. If I expand the loop, what happens is:
plot(data.frame(data1[1], data1[2]), ...) lines(data.frame('data2[1]', 'data2[2]', ...) lines(data.frame('data3[1]', 'data3[2]', ...) i.e. what you think is fetching data2 and data3, you are really only using the strings 'data2' and 'data3' (note the quotation marks).
Without assuming too much of your data and restructuring you entire code, this should do the trick (for the second loop). Since you only have three data-files, looping seems a bit extensive contra the problems they are introducing.
plot(data.frame(data1[1], data1[2]), xlim=c(-0.2, -7), ylim=c(0.31, 0.35), yaxt="n", type="l", xlab="", ylab="",lty="solid", col="red2", lwd=4, axes=TRUE) lines(data.frame(data2[1], data2[2]) ,lty="twodash", col="deepskyblue4", lwd=4) lines(data.frame(data3[1], data3[2]) ,lty="twodash", col="deepskyblue4", lwd=4) If you insist on looping, we could do:
for(i in 1:3){ if(i==1){ plot(data.frame(data1[1], data1[2]), xlim=c(-0.2, -7), ylim=c(0.31, 0.35), yaxt="n", type="l", xlab="", ylab="",lty="solid", col="red2", lwd=4, axes=TRUE) } else { dat <- get(paste('data', i, sep='')) lines(data.frame(dat[1], dat[2]) ,lty="twodash", col="deepskyblue4", lwd=4) } } To further comment your code, in your read.table call, you have two nested paste calls, which in this case is unnecessary.
paste(paste("data", i, sep=""),"_lambda.dat",sep="") # could be done with paste(paste("data", i, "_lambda.dat",sep="")
-18564726 0I have found in the past that there are 3 dlls you need to have the correct version of for debugging .Net.
sos.dll mscorwks.dll mscordacwks.dll
here's how I usually go about getting these dll's http://sjbdeveloper.blogspot.com.au/, although it sounds as though you are using a server based application which means you could possibly just grab them from your production box, assuming you have access to it, or a staging box if you don't.
-18601402 0I suppose you need an ANE - unless Adobe extends flash.notifications one day to support Android too.
-9979801 0I'm betting that you have a one-dimensional array with strings stored in each. So your array actually looks like:
array ( [0] => '...', [1] => '.X.', [2] => '...' ) When this is what you want:
array ( [0] => array ( [0] => '.', [1] => '.', [2] => '.' ), [1] => array ( [0] => '.', [1] => 'X', [2] => '.' ), [2] => array ( [0] => '.', [1] => '.', [2] => '.' ) ) When constructing your 2D array, make sure you explicitly declare each entry in board as an array. So to construct it, your code might look something like this:
board = new Array(); rows = 3; for (var i = 0; i < rows; i++) board[i] = new Array('.', '.', '.');
-30807138 0 The answer is in apple SCNNode documentation. Try using flattenedClone() method instead of clone(). And one more thing, it's not needed any for statement. Here is a little example in Swift:
nodeB = nodeA.flattenedClone() Now, nodeB contains all children nodes of nodeA
-12489854 0 How can I prevent both the keyboard and the menu from being shown together?Here's a screenshot of my application. When the search box is clicked, the soft-keyboard automatically pops up, which is fine, but, if I also press the "Menu" button, the menu appears on top of the soft-keyboard.
How can I show the menu but collapse the SearchView if it is in focus and also hide the soft-keyboard. I probably need to check and do something in the onPrepareOptionsMenu method of my Activity, right?
It doesn't cause any real harm to me but it seems like an ugly implementation to the user when this happens.

The behaviour of this operator is different across various versions of Ruby. You're probably using an older one, in which case this is to be expected.
Here's an excerpt from the docs for Ruby 1.8.7's String class
If passed a single Fixnum, returns the code of the character at that position.
This has been changed and the newer versions of Ruby (1.9.x and above, according to this site ) simply print the character as a String. See the docs for Ruby 2.1.0.
If passed a single index, returns a substring of one character at that index.
Ruby 1.9.3, which I happen to have installed on the machine I'm using displays exactly the same behavior:
"Mwada"[0] => "M" "Mwada"[0].class => String
-33260553 1 Using PyperClip on web app I am using pyperclip.py to grab a list of E-Mail Addresses in my web app using a form so a user can paste it locally via clipboard. It works perfect locally. However, while running it on a server (Linux 14.04 with Apache2) and accessed from a client system through the browser it doesn't copy. How can I get it to copy to the clipboard of the client's system?
Right now I'm just trying to get it to work and as such I'm only using a single line. I'm using pyperclip 1.5.15 with xclip and Python 3.4. The server is running Linux 14.04 and the client has noticed issues on Windows 8 and Windows 10 using Google Chrome and IE. No other os has currently been tested.
pyperclip.copy("HELLO")
-892409 0 You can read a reasonable answer from this implementation found in some webpage
Point * intersection2(Point * _line1, Point * _line2) { Point p1,p2,p3,p4; p1=_line1[0]; p3=_line2[0]; p2=_line1[1]; p4=_line2[1]; // Store the values for fast access and easy // equations-to-code conversion double x1 = p1.x, x2 = p2.x, x3 = p3.x, x4 = p4.x; double y1 = p1.y, y2 = p2.y, y3 = p3.y, y4 = p4.y; double A1 = y2-y1; double B1 = x1-x2; double C1 = (A1*x1)+(B1*y1); double A2 = y4-y3; double B2 = x3-x4; double C2 = A2*x3+B2*y3; double det = A1*B2 - A2*B1; if (det==0){ return NULL; }else{ // Return the point of intersection Point * ret = new CvPoint2D64f (); ret->x = (B2*C1 - B1*C2)/det; ret->y = (A1*C2 - A2*C1)/det; return ret; } }
Reference. C++ Example: Geometry Concepts Line Intersection and its Applications, 2D drawing By lbackstrom from site ucancode
-24266037 0The following code should help. You should split each subject into a separate array within your query. Once your query is complete, you should iterate through the subject array, and then within each staff id.
$subjects = array(); $q = mysql_query("Select staff_id from my_table"); while($row = mysql_fetch_array($q)){ if ($subjects[$row['SUBJECT']] == nil) { $subjects[$row['SUBJECT']] = array(); } array_push($subjects[$row['SUBJECT']], $row['STAFF_ID']); } foreach ($subjects as $key=>$value) { echo $key . '<br>; foreach ($vaue as &$staff) { echo $staff . '<br>'; } }
-40140116 0 Try this : WHERE IV00101.ITEMNMBR = IV00102.ITEMNMBR AND IV00102.ITEMNMBR = ItmPrice.ITEMNMBR group by IV00101.ITEMNMBR ORDER BY IV00101.ITEMNMBR
-23621173 0How about writing 2 servlets, one to take in the image and write it to the database and another one to get the image and pass it back in the response output stream which you can call from the webpage via an ajax call.
-28671966 0Function to get random integers where min, max are inclusive
function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } Function to find Random Value from passed variable plot
function getRandomValue(plot) { var rN1 = getRandomInt(0,plot.length-1); var areaArray= plot[rN1].area.split(","); var rN2 = getRandomInt(0,areaArray.length-1); return areaArray[rN2]; } And use it like
plot = [ { postcode: "MK1", area: "Denbigh, Mount Farm", }, { postcode: "MK2", area: "Brickfields, Central Bletchley, Fenny Stratford, Water Eaton" }, { postcode: "MK3", area: "Church Green, Far Bletchley, Old Bletchley, West Bletchley", }, { postcode: "MK4", area: "Emerson Valley, Furzton, Kingsmead, Shenley Brook End, Snelshall West, Tattenhoe, Tattenhoe Park, Westcroft, Whaddon, Woodhill", }, { postcode: "MK5", area: "Crownhill, Elfield Park, Grange Farm, Oakhill, Knowlhill, Loughton, Medbourne, Shenley Brook End, Shenley Church End, Shenley Lodge, Shenley Wood", } ] console.log(getRandomValue(plot))
-9757195 0 Maybe this one close to your expression will fit your need :
just get rid of chars that your are not interested after your keyword or match the end of string
-5984205 0(?:[a-zA-Z'-]+[^a-zA-Z'-]+){0,5}keyword(?:[^a-zA-Z'-]+|$)(?:[a-zA-Z'-]+[^a-zA-Z'-]*){0,5}
already you can write like this: SampledbDataContext sdc = new SampledbDataContext(Server.MapPath("~/Sampledb.mdf")); or in design.cs file public SampledbDataContext() : base(global::"[write cnn string Here !]", mappingSource) { OnCreated(); }
-13424483 0When you open a MongoDB connection with the native driver, you're actually opening a pool of 5 connections (by default). So it's best to open that pool when your app starts and just leave it open rather than open and close the pool on each request.
You're on the right track with closing out your HTTP response; just call res.end(); when the response is complete (i.e. when item is null in the cursor.each callback).
I think this is a problem and I think if I set it to 1GB it will increase the performance and capability, is that right ?
It will mean the DB will need to stop less often to grow, certainly, and data inserts will occur more frequently. It will reduce the impact of data file growth. However, Microsoft says that autogrow is not intended to manage planned file growth. It's intended to handle unexpected growth. Autogrow is just not designed to work the way you're using it. The design intent is that you know how much data you will be storing and you have planned accordingly and already correctly sized your DB.
This might be somewhat unrealistic given your application, however. If your system is designed to hold all data ever collected indefinitely, your capacity planning is a bit difficult.
This is why it's common practice to differentiate operational data from warehoused data. Your operational data is stored in one database, which you can predict the growth for within a given time frame (usually 1 or more years). After a period of time, older data is archived to data warehouses, which may be very large or single year containers, but since data is inserted here rarely, you know what your capacity is going to be.
If I were you, I would pick a time frame to plan for. Say one month, quarter, or year. Every period of time, manually grow your database large enough so that the free space is what you expect to need to accommodate the coming period. Don't forget to include index space! Use the SSMS reports to help your estimates!
This means you can do your growth during off-hours or maintenance windows and your application is never waiting on the DB to finish growing. I would then set autogrowth to be about 5% of the free space you're planning for. If you underestimate, you'll get an idea by how much when you look at your shrink/grow logs. You can then increase for next month. Eventually, you'll learn what you need on a monthly basis. Just make sure to grow based on free space in the database and not absolute file size.
-36445189 0 libcurl use same user defined port to send periodic requestI am working on a project need to send periodic alive message to https server.
Because of security issue, we need to use minimal number of ports (blocking unused ports as many as we can).
I am using c++ libcurl easy interface to send https request in linux.
I have tried to use the same curl handler object (CURL object) and set CURLOPT_LOCALPORT to a port number. The first request is ok. But in the second, libcurl verbose mode said address already in use. However, when I comment out the port set through CURLOPT_LOCALPORT, it works on second connection also, and by setting VERBOSE to 1, I can see "Re-using existing connection" print out, which is missing in version setting up local port. And I check with linux netstat, find out that it is using the same port. I cannot figure out why setting up local port will make it failed.
And also, I have tried to close the connection using curl_easy_cleanup, but due to tcp time_wait state, we cannot reuse the port in a while, that's not what I want.
Could anyone provide a solution or suggestion to us? Thanks a lot.
Edit My reason using one port is not to keep opening and closing connection too much.
-18434000 0Check your remote "origin" to ensure the URL looks correct:
git remote -v
Next, try listing out the contents of the remote:
git ls-remote origin
If all goes well with the steps above, Git is certainly connecting to the GitHub hosted repository. Try the git push origin fefixex again.
Your code is already working:
for download as cvs add this code block:
Highcharts.getOptions().exporting.buttons.exportButton.menuItems.push({ text: 'Download CSV', onclick: function () { Highcharts.post('http://www.highcharts.com/studies/csv-export/csv.php', { csv: this.getCSV() }); } });
-4699246 0 Your best bet is probably to use shell_exec to cat some of the data from the various /proc/* files that are commonly used on Linux/Unix systems, the key ones probably being:
For example:
echo shell_exec('cat /proc/cpuinfo/');
-38112027 0 As it seems this is a common issue I'll try to provide more information here:
First, make sure you check whatever code you are using on your Analytics. The first answer provided here pasted a code using Google GA.JS code, but many websites today uses the new Analytics.JS code (my case). So my suggestion is to copy your GA code from your website or from your GA panel.
Second, check if your GA code is being passed on your Instant Article RSS feed correctly (i'm assuming you are using Wordpress with some plugin to build a RSS). If you are using the new analytics.js method the code inside your RSS feed (per article) should be like this:
<!-- Adding tracking if defined --> <figure class="op-tracker"> <iframe> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'YOUR_GA_ID', 'auto'); ga('send', 'pageview'); </script> </iframe> </figure> Third, if your articles were already on Facebook Instant Article Production list BEFORE you added the Analytics code, they will NOT update / load the code. The best way to test is to edit any of your articles (a simples change of punctuation is enough) and republish it on your wordpress. Then go to your IA panel on Facebook, Configuration and click to reload / rebuild your RSS. Wait a little then check on the list of I.A that the post will update (you will see the date change), then open it on the edit option and check at the end of the code. Your GA code should be there.
So, if everything is good now, your last step (at least was for me) is to delete all the old Instant Articles on Facebook (I'm assuming you don't have them published yet) and reload the RSS feed on the Configuration area, so it will rebuild your articles with the GA code on them.
Hope this helps.
PS: I'm NOT using the plugin from Automattic to publish IA from WP as it's just garbage. There is one way simpler that work's w/o any trouble: https://wordpress.org/plugins/allfacebook-instant-articles/
-4544504 0You should not rewrite static files. Where are your images/css files located?
A rewrite rule like this will prevent files existing on disk not to be rewritten:
RewriteCond %{REQUEST_FILENAME} !-f # Do not rewrite static files RewriteCond %{REQUEST_FILENAME} !-d # Do not rewrite static directories As for your second question, please clarify, im not sure i understand what you mean.
-25134439 0No , dont do that . loading remote website will not able to intract with your plugins . and the app will get rejected on istore too
-5493291 0You can't directly call click on something in the control. However, you can register some JavaScript into the control and perform the click that way.
See How to inject Javascript in WebBrowser control? for details.
-28469210 0You can use the Windows.Web.Http.HttpClient instead of System.Net.Http.HttpClient, i.e.:
HttpClient _httpClient = new HttpClient(); bool result = _httpClient.DefaultRequestHeaders.TryAppendWithoutValidation("Accept", "vnd.servicehost.v1+json"); var response = await _httpClient.GetAsync(uri);
-834973 0 Help -> About Microsoft Visual Studio
-21450810 0Try to define outputRowId as ParameterDirection.InputOutput
-12990449 0 Binding to DependencyProperty with no resultI have problem with binding to dependency property of my new control.
I decided to write some tests to examine this issue.
Binding from TextBox.Text to another TextBox.Text
XAML code:
<TextBox Name="Test" Text="{Binding ElementName=Test2, Path=Text, UpdateSourceTrigger=PropertyChanged}" /> <TextBox Name="Test2" Grid.Row="2" /> The result is good - when I writing something in first TextBox -> second TextBox is updating (conversely too).

I created new control -> for example "SuperTextBox" with dependency property "SuperValue".
Control XAML code:
<UserControl x:Class="WpfApplication2.SuperTextBox" ... Name="Root"> <TextBox Text="{Binding SuperValue, ElementName=Root, UpdateSourceTrigger=PropertyChanged}" /> </UserControl> Code behind:
public partial class SuperTextBox : UserControl { public SuperTextBox() { InitializeComponent(); } public static readonly DependencyProperty SuperValueProperty = DependencyProperty.Register( "SuperValue", typeof(string), typeof(SuperTextBox), new FrameworkPropertyMetadata(string.Empty) ); public string SuperValue { get { return (string)GetValue(SuperValueProperty); } set { SetValue(SuperValueProperty, value); } } } Ok, and now tests!
Binding from TextBox.Text to SuperTextBox.SuperValue
<TextBox x:Name="Test1" Text="{Binding ElementName=Test2, Path=SuperValue, UpdateSourceTrigger=PropertyChanged}" /> <local:SuperTextBox x:Name="Test2" Grid.Row="2"/> Test is correct too! When I writing something in TextBox, SuperTextBox is updating. When i writing in SuperTextBox, TextBox is updating. All is ok!
Now a problem:
Binding from SuperTextBox.SuperValue to TextBox.Text
<TextBox x:Name="Test1"/> <local:SuperTextBox x:Name="Test2" SuperValue="{Binding ElementName=Test1, Path=Text, UpdateSourceTrigger=PropertyChanged}" Grid.Row="2"/> In this case, when I writing something in SuperTextBox, TextBox is not updating! 
How can I fix this?
PS: Question is very very long, I am sorry for that, but i tried exactly describe my problem.
-29057730 0 Rails-jQuery Why do I have to click twice for jQuery effect to show?I am using Rails 4.1.1 Why do I have to click twice for jQuery effect to show? I have been Googling but I cannot find any solutions, not sure if there's something wrong with my jQuery code or....
When I click "Submit" for the first time, the effect didn't appear but the POST action is already called, when I click for the second time, the effect appeared and the POST action is called.
Please check below my create.js.erb, users_controller.rb, new.html.erb
create.js.erb
function isValidEmailAddress(emailAddress) { var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i); return pattern.test(emailAddress); }; $("form").submit(function( event ) { var email = $("input#user_email").val(); if (email == "") { $("h1").text( "Email cannot be empty" ).show().fadeOut( 3000 ); return; } else if (!isValidEmailAddress(email)) { $("h1").text( "Email address is not valid" ).show().fadeOut( 3000 ); }else { $("h1").text( "Correct email address" ).show(); } event.preventDefault(); }); new.html.erb
<%= form_for @user, remote: true do |f| %> <p> <%= f.text_field :email %> </p> <p> <%= f.submit :Submit %> </p> <% end %> <h1></h1> <% @users.each do |user| %> <tr> <li><%= user.email %></li> </tr> <% end %> users_controller.rb
class UsersController < ApplicationController def new @users = User.all @user = User.new end def create @user = User.new(user_params) respond_to do |format| format.html { redirect_to '/' } format.js end @user.save end private def user_params params.require(:user).permit(:email) end end
-14064579 0 Pagenation problem was solved
.pager ul.yiiPager li.page:after{display: inline-block !important} But still am getting image problem... Help please...
-3123532 0You can in upload script use a temportantly file (in temportantly directory) and if upload was finished you can simple move file to your final location with good filename.
This is a common solution for this problem.
For get temportantly file (enviroment independent) use PHP function:
resource tmpfile ( void ) Documemtation for it you can find at http://pl.php.net/manual/en/function.tmpfile.php This function returning handle to your new clean tempfile.
But if your using this function you must copy file before you close handle to it because this file was removed when you call fclose(handle). To get assurance of file buffer is clean you can at end call fflush(handle).
Or if you don't want use tmpfile(void) function you can do this manualy.
string tempnam ( string $dir, string $prefix ) Prefix is a prefix to your files to easly group her to delete or something. Call this function to get unique file in typed directory, as directory get you temp directory in your enviroment, you can get this by calling:
string sys_get_temp_dir ( void ) Then when you have self tempfile, write to it upload data and close. Copy this file to your final location using:
bool copy ( string $source, string $dest [, resource $context ] ) And delete your tempfile to get clean in your enviroment calling:
bool unlink ( string $filename [, resource $context ] )
-24154162 0 Make sure your Class name field is actually Module.Task, where Module is the name of your app. CoreData classes in Swift are namespaced. Right now, your object is being pulled out of the context as an NSManagedObject, not as a Task, so the as-cast is failing.
-5402066 0It has no effect on other functions. It only has effect if your program uses COM interop.
-35031713 0Have you tried with "before"?
$args = array( 'post_type' => 'epl_registration', 'post_status' => 'publish', 'fields' => 'ids', 'date_query' => array( array( 'column' => 'post_date_gmt', 'before' => '6 hours ago' ) ) ); $the_query = new WP_Query($args);
-23583368 0 First, a capitalization typo:
stage.find // not stage.Find When you use the hashtag (#) within a .find key, KineticJS searches for a node id.
So when you create each path (room) you should assign it a node id (eg "Room1"):
var path = new Kinetic.Path({ id:"Room1", data: c, fill: '#fff', stroke: '#555', strokeWidth: 1 }); Then your .find will succeed:
var room = stage.find("#Room1")[0];
-37806419 0 I have found the solution. The problem is with setting the contentScaleFactor of UIView. By default, it is 2.0 for retina displays. So, it should be set to 1.0. Here is the link for more details: UIView ContentScaleFactor
-37734931 0As far as the rest of your program is aware your wait_queue is just a Collection, it doesn't have get or remove methods.
You're correct in that you don't want to couple your implementation to the variable's type, however you shouldn't use Collection unless you only want to iterate over the contents. Use List, Set, or other collections interfaces to describe collections. These expose the get and remove (in the case of the List) methods you want, and expose the behaviour of the object (but not the implementation - in this case ArrayList). e.g., a List allows duplicates whereas a Set does not.
Here is my xml:
<?xml version="1.0" encoding="utf-8"?> <library xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="library.xsd"> <items> <book asin="0201100886" created="128135928" lastLookupTime="128135928"> <uuid>BA57A934-6CDC-11D9-830B-000393D3DE16</uuid> <title>Compilers</title> <authors> <author>Alfred V. Aho</author> <author>Ravi Sethi</author> <author>Jeffrey D. Ullman</author> </authors> <publisher>Addison Wesley</publisher> <published>1986-01-01</published> <price>102.00</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0122513363" created="128135600" lastLookupTime="128136224"> <uuid>F7468E09-6CDB-11D9-830B-000393D3DE16</uuid> <title>Database Driven Web Sites</title> <authors> <author>Jesse Feiler</author> </authors> <publisher>Morgan Kaufmann</publisher> <published>1998-04-15</published> <edition>Paperback</edition> <price>50.95</price> <purchaseDate>2005-01-22</purchaseDate> <currentValue>35.00</currentValue> <netRating>1.5</netRating> <genres> <genre>Computer Bks - Internet</genre> <genre>Computer Books: Web Programming</genre> <genre>Computer Networks</genre> <genre>Computers</genre> <genre>Database Management - General</genre> <genre>Database management</genre> <genre>Design</genre> <genre>Distributed Databases</genre> <genre>Information Technology</genre> <genre>Internet - Web Site Design</genre> <genre>Networking - General</genre> <genre>Web sites</genre> <genre>Computers / Computer Science</genre> </genres> <upc>608628133638</upc> </book> <book asin="0201441241" created="128136896" lastLookupTime="128136896"> <uuid>FBC45DF4-6CDE-11D9-830B-000393D3DE16</uuid> <title>Introduction to Automata Theory, Languages, and Computation (2nd Edition)</title> <authors> <author>John E. Hopcroft</author> <author>Rajeev Motwani</author> <author>Jeffrey D. Ullman</author> </authors> <publisher>Addison Wesley</publisher> <published>2000-11-14</published> <price>108.20</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0471250600" created="128136896" lastLookupTime="128136896"> <uuid>FBC7CA56-6CDE-11D9-830B-000393D3DE16</uuid> <title>Operating System Concepts</title> <authors> <author>Abraham Silberschatz</author> <author>Greg Gagne</author> <author>Peter Baer Galvin</author> </authors> <publisher>Wiley</publisher> <published>2002-03-08</published> <price>107.95</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0321193628" created="128136896" lastLookupTime="128136896"> <uuid>FBCB3DCF-6CDE-11D9-830B-000393D3DE16</uuid> <title>Concepts of Programming Languages, Sixth Edition</title> <authors> <author>Robert W. Sebesta</author> </authors> <publisher>Addison Wesley</publisher> <published>2003-07-24</published> <price>112.40</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0138613370" created="128136944" lastLookupTime="128136944"> <uuid>19E5E602-6CDF-11D9-830B-000393D3DE16</uuid> <title>First Course in Database Systems, A</title> <authors> <author>Jeffrey D. Ullman</author> <author>Jennifer Widom</author> </authors> <publisher>Prentice Hall</publisher> <published>1997-04-02</published> <edition>Hardcover</edition> <price>67.00</price> <purchaseDate>2005-01-22</purchaseDate> <netRating>3.2</netRating> <genres> <genre>Computer Books: Database</genre> <genre>Computers</genre> <genre>Database Engineering</genre> <genre>Database Management - General</genre> <genre>Database management</genre> </genres> <recommendations> <book asin="0130402648" created="128136952" lastLookupTime="128136952"> <uuid>1C60074A-6CDF-11D9-830B-000393D3DE16</uuid> <title>Database System Implementation</title> <authors> <author>Hector Garcia-Molina</author> <author>Jeffrey D. Ullman</author> <author>Jennifer D. Widom</author> </authors> <publisher>Prentice Hall</publisher> <published>1999-06-11</published> <price>89.00</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0130319953" created="128136952" lastLookupTime="128136952"> <uuid>1C635DB0-6CDF-11D9-830B-000393D3DE16</uuid> <title>Database Systems: The Complete Book</title> <authors> <author>Hector Garcia-Molina</author> <author>Jeffrey D. Ullman</author> <author>Jennifer D. Widom</author> </authors> <publisher>Prentice Hall</publisher> <published>2001-10-02</published> <price>98.00</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0201976994" created="128136952" lastLookupTime="128136952"> <uuid>1C66B7B4-6CDF-11D9-830B-000393D3DE16</uuid> <title>Computer Networking: A Top-Down Approach Featuring the Internet</title> <authors> <author>James F. Kurose</author> <author>Keith W. Ross</author> <author>James Kurose</author> <author>Keith Ross</author> </authors> <publisher>Addison Wesley</publisher> <published>2002-07-17</published> <price>100.00</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0131433512" created="128136952" lastLookupTime="128136952"> <uuid>1C6AC88C-6CDF-11D9-830B-000393D3DE16</uuid> <title>Computer Networks and Internets, Fourth Edition</title> <authors> <author>Douglas E Comer</author> <author>Ralph E. Droms</author> </authors> <publisher>Prentice Hall</publisher> <published>2003-07-28</published> <price>100.00</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0262062178" created="128136952" lastLookupTime="128136952"> <uuid>1C6E712C-6CDF-11D9-830B-000393D3DE16</uuid> <title>Essentials of Programming Languages - 2nd Edition</title> <authors> <author>Daniel P. Friedman</author> <author>Mitchell Wand</author> <author>Christopher T. Haynes</author> </authors> <publisher>The MIT Press</publisher> <published>2001-01-29</published> <price>62.00</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0471250600" created="128136952" lastLookupTime="128136952"> <uuid>1C71B23E-6CDF-11D9-830B-000393D3DE16</uuid> <title>Operating System Concepts</title> <authors> <author>Abraham Silberschatz</author> <author>Greg Gagne</author> <author>Peter Baer Galvin</author> </authors> <publisher>Wiley</publisher> <published>2002-03-08</published> <price>107.95</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0137903952" created="128136952" lastLookupTime="128136952"> <uuid>1C764AD4-6CDF-11D9-830B-000393D3DE16</uuid> <title>Artificial Intelligence: A Modern Approach (2nd Edition)</title> <authors> <author>Stuart J. Russell</author> <author>Peter Norvig</author> </authors> <publisher>Prentice Hall</publisher> <published>2002-12-20</published> <price>93.33</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="155860832X" created="128136952" lastLookupTime="128136952"> <uuid>1C898640-6CDF-11D9-830B-000393D3DE16</uuid> <title>Computer Networks: A Systems Approach, 3rd Edition</title> <authors> <author>Larry L. Peterson</author> <author>Bruce S. Davie</author> </authors> <publisher>Morgan Kaufmann</publisher> <published>2003-05-22</published> <price>89.95</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0130669474" created="128136952" lastLookupTime="128136952"> <uuid>1C8DD37A-6CDF-11D9-830B-000393D3DE16</uuid> <title>SQL Fundamentals (2nd Edition)</title> <authors> <author>John J. Patrick</author> </authors> <publisher>Prentice Hall PTR</publisher> <published>2002-05-07</published> <price>54.99</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0321122267" created="128136952" lastLookupTime="128136952"> <uuid>1C91D772-6CDF-11D9-830B-000393D3DE16</uuid> <title>Fundamentals of Database Systems, Fourth Edition</title> <authors> <author>Ramez Elmasri</author> <author>Shamkant B. Navathe</author> </authors> <publisher>Addison Wesley</publisher> <published>2003-07-23</published> <price>104.20</price> <purchaseDate>2005-01-22</purchaseDate> </book> </recommendations> </book> <book asin="1558604820" created="128136024" lastLookupTime="128136024"> <uuid>F3C7B24F-6CDC-11D9-830B-000393D3DE16</uuid> <title>A Complete Guide to DB2 Universal Database</title> <authors> <author>D. D. Chamberlin</author> <author>Don Chamberlin</author> </authors> <publisher>Morgan Kaufmann</publisher> <published>1998-08-15</published> <edition>Paperback</edition> <price>62.95</price> <purchaseDate>2005-01-22</purchaseDate> <netRating>4.4</netRating> <genres> <genre>Computer Bks - Data Base Management</genre> <genre>Computer Books: Database</genre> <genre>Computers</genre> <genre>Database Management - General</genre> <genre>General</genre> <genre>IBM Database 2</genre> <genre>Information Storage & Retrieval</genre> <genre>Relational Databases</genre> <genre>Computers / Information Storage & Retrieval</genre> </genres> <recommendations> <book asin="0072133449" created="128136024" lastLookupTime="128136024"> <uuid>F6B35F21-6CDC-11D9-830B-000393D3DE16</uuid> <title>DB2: The Complete Reference (Complete Reference Series)</title> <authors> <author>Roman B. Melnyk</author> <author>Paul C. Zikopoulos</author> </authors> <publisher>McGraw-Hill Companies</publisher> <published>2001-10-01</published> <price>59.99</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0130661112" created="128136024" lastLookupTime="128136024"> <uuid>F6B97E54-6CDC-11D9-830B-000393D3DE16</uuid> <title>DB2 UDB v8 Handbook for Windows and UNIX/Linux</title> <authors> <author>Philip K. Gunning</author> </authors> <publisher>Prentice Hall PTR</publisher> <published>2003-08-06</published> <price>59.99</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0131007726" created="128136024" lastLookupTime="128136024"> <uuid>F6BCBB88-6CDC-11D9-830B-000393D3DE16</uuid> <title>DB2 SQL Procedural Language for Linux, Unix and Windows</title> <authors> <author>Paul Yip</author> <author>Drew Bradstock</author> <author>Hana Curtis</author> <author>Michael Gao</author> <author>Zamil Janmohamed</author> <author>Clara Liu</author> <author>Fraser McArthur</author> </authors> <publisher>Prentice Hall PTR</publisher> <published>2002-12-24</published> <price>59.99</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0131424653" created="128136024" lastLookupTime="128136024"> <uuid>F6C0A296-6CDC-11D9-830B-000393D3DE16</uuid> <title>DB2 UDB V8.1 Certification Exam 700 Study Guide</title> <authors> <author>Roger E. Sanders</author> </authors> <publisher>Prentice Hall PTR</publisher> <published>2003-09-17</published> <price>49.99</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0764508415" created="128136024" lastLookupTime="128136024"> <uuid>F6C4058C-6CDC-11D9-830B-000393D3DE16</uuid> <title>DB2 Fundamentals Certification for Dummies</title> <authors> <author>Paul C. Zikopoulos</author> <author>Jennifer Gibbs</author> <author>Roman B. Melnyk</author> </authors> <publisher>For Dummies</publisher> <published>2001-08-01</published> <price>34.99</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0130463612" created="128136024" lastLookupTime="128136024"> <uuid>F6D9A3D8-6CDC-11D9-830B-000393D3DE16</uuid> <title>DB2 Universal Database V8 for Linux, UNIX, and Windows Database Administration Certification Guide (5th Edition)</title> <authors> <author>George Baklarz</author> <author>Bill Wong</author> </authors> <publisher>Prentice Hall PTR</publisher> <published>2003-02-10</published> <price>59.99</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0130463884" created="128136024" lastLookupTime="128136024"> <uuid>F6DDBAB9-6CDC-11D9-830B-000393D3DE16</uuid> <title>Advanced DBA Certification Guide and Reference for DB2 UDB v8 for Linux, Unix and Windows</title> <authors> <author>Dwaine R. Snow</author> <author>Thomas Xuan Phan</author> <author>Dwaine Snow</author> </authors> <publisher>Prentice Hall PTR</publisher> <published>2003-07-07</published> <price>59.99</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="155860443X" created="128136024" lastLookupTime="128136024"> <uuid>F6E1063D-6CDC-11D9-830B-000393D3DE16</uuid> <title>Advanced Database Systems (The Morgan Kaufmann Series in Data Management Systems)</title> <authors> <author>Carlo Zaniolo</author> <author>Stefano Ceri</author> <author>Christos Faloutsos</author> <author>Richard T. Snodgrass</author> <author>V. S. Subrahmanian</author> <author>Roberto Zicari</author> </authors> <publisher>Morgan Kaufmann</publisher> <published>1997-05-01</published> <price>88.95</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0131840487" created="128136024" lastLookupTime="128136024"> <uuid>F6E441CE-6CDC-11D9-830B-000393D3DE16</uuid> <title>DB2 UDB V8.1 Certification Exams 701 and 706 Study Guide</title> <authors> <author>Roger E. Sanders</author> </authors> <publisher>Prentice Hall PTR</publisher> <published>2003-12-12</published> <price>49.99</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0132037955" created="128136024" lastLookupTime="128136024"> <uuid>F6E77C2C-6CDC-11D9-830B-000393D3DE16</uuid> <title>DB2 High Performance Design and Tuning</title> <authors> <author>Richard Yevich</author> <author>Susan Lawson</author> <author>Richard A. Yevich</author> </authors> <publisher>Prentice Hall PTR</publisher> <published>2000-08-24</published> <price>54.99</price> <purchaseDate>2005-01-22</purchaseDate> </book> </recommendations> </book> </items> <borrowers> <borrower id="1"> <name> John Doe </name> <phone> 555-1212 </phone> <borrowed> <book asin="0138613370"/> <book asin="0122513363"/> </borrowed> </borrower> <borrower id="2"> <name> Mary Jane </name> <phone> 555-1213 </phone> <borrowed> <book asin="0201100886"/> <book asin="0122513363"/> </borrowed> </borrower> <borrower id="3"> <name> Bill Jones </name> <phone> 555-1312 </phone> <borrowed /> </borrower> <borrower id="4"> <name> Anne Marie</name> <phone> 555-1314</phone> <borrowed> <book asin="0138613370"/> <book asin="0201100886"/> <book asin="0122513363"/> <book asin="1558604820"/> </borrowed> </borrower>
Here is my XQuery:
xquery version "1.0"; for $library in doc("library.xml")/library for $book in $library/items/book let $borrowed := $library/borrowers/borrower/borrowed/book where not($borrowed[@asin = $book/@asin]) and ($book/authors/author = "Jeffrey D. Ullman") return if($book/authors/author != "Jeffrey D. Ullman") then <librarytitle>{$book/authors/author}</librarytitle> else <librarytitle/> I need to return all authors where Jeff D Ullman is a coauthor but in the list I cant return his name. So i get all books he is an author in and print them out. If his name is there dont print it out. My if then else statement is not working. Any ideas????
-34002792 0You should login your user again and only after that attach the file.I had similar situation when i took a picture using camera. I did this. Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivity(intent); CameraActivity was started and connection was lost, so you need to reconnect if you want to upload the file.
-18872090 0There is a config.inc.php under setup/frames, this is the one you are showing us but it's not the one that contains the configuration. Look at the main directory containing all the db_* and tbl_* scripts. However, phpMyAdmin is able to run without a config.inc.php.
Do you see a login panel with phpMyAdmin logo?
-10784772 0 Drawing a line with a brush in iOSthere are so many posts here, were people ask how to draw lines with a brush in CGContext. The answer always is: Use a pattern. However, I tried this for some hours now and the main problem to me seems to be: It seems like CoreGraphics simply draws the pattern as a fill and then simply clips this pattern with the stroke of the path you specified. This leads to some bad looking tile-borders and it simply doesn't look as someone really draws something by hand. What I want is something were the brush is painted along the path, without any clipping. I basically want to move along the path and simply draw the brush image every x points, in distance, on the path, with the size of the brush. Is this somehow possible with CoreGraphics or is this just something you have to implement on your own?
//EDIT: Sorry, I thought it was clear what I tried by saying, I used a pattern. This is what I did so far:
struct CGPatternCallbacks patternCallback = {0, drawChalkPattern, NULL}; CGAffineTransform patternTransform = CGAffineTransformMakeScale(.25f, .25f); UIImage* brush = [UIImage imageNamed:@"ChalkBrush"]; CGPatternRef pattern = CGPatternCreate(NULL, (CGRect){CGPointZero, brush.size}, patternTransform, brush.size.width, brush.size.height, kCGPatternTilingConstantSpacingMinimalDistortion, true, &patternCallback); CGColorSpaceRef patternSpace = CGColorSpaceCreatePattern(NULL); CGContextSetStrokeColorSpace(context, patternSpace); CGFloat color[4] = {1.0f, 1.0f, 1.0f, 1.0f}; CGContextSetStrokePattern(context, pattern, color); CGContextDrawPath(context, kCGPathStroke); and than this is the patternCallback function:
void drawChalkPattern(void * info, CGContextRef context) { UIImage* pattern = [UIImage imageNamed:@"ChalkBrush"]; CGContextDrawImage(context, (CGRect){CGPointZero, pattern.size}, [pattern CGImage]); } Best regards, Michael
-32674086 0The <html> background is "behind" the <body> background. Try this to see what I mean:
html{ background-color:blue; } body{ background-color:white; max-width:400px; margin:0 auto; }
-1182395 0 As a bug-tracker, I am using Mantis :
There's a demo available, btw.
-11628374 0The reason to use a double here is the attempt to provide enough accuracy.
In detail: The systems interrupt time slices are given by ActualResolution which is returned by NtQueryTimerResolution(). NtQueryTimerResolution is exported by the native Windows NT library NTDLL.DLL. The System time increments are given by TimeIncrement which is returned by GetSystemTimeAdjustment().
These two values are determining the behavior of the system timers. They are integer values and the express 100 ns units. However, this is already insufficient for certain hardware today. On some systems ActualResolution is returned 9766 which would correspond to 0.9766 ms. But in fact these systems are operating at 1024 interrupts per second (tuned by proper setting of the multimedia interface). 1024 interrupts a second will cause the interrupt period to be 0.9765625 ms. This is of too high detail, it reaches into the 100 ps regime and can therefore not be hold in the standard ActualResolution format.
Therefore it has been decided to put such time-parameters into double. But: This does not mean that all of the posible values are supported/used. The granularity given by TimeIncrement will persist, no matter what.
When dealing with timers it is always advisable to look at the granularity of the parameters involved.
So back to your question: Can Interval support values like 5.768585 (ms) ?
No, the system I've taken as an example above cannot.
But it can support 5.859375 (ms)!
Other systems with different hardware may support other numbers.
So the idea of introducing a double here is not such a stupid idea and actually makes sense. Spending another 4 bytes to get things finally right is a good investment.
I've summarized some more details about Windows time matters here.
-7950654 0Try this, while calling your MainMenu activity from Game activity:
Intent intent = new Intent(this, MainMenu.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); this.startActivity(intent); Hope this would help.
-19669246 0In the code you have posted above, there is no retain cycle.
A retain cycle would be self.A = self; or more likely, self.A.someStrongProperty = self.
Edit: In the case you have edited above, assuming self is a view controller, it would not deallocate because of the retain cycle. You should change your someStrongProperty to be a weak property, which will prevent the retain cycle.
well, I've been thinking of making database requests a little faster by keeping the connection to the database open as long as the object is being used. So I was thinking of opening the connection in the constructor of that class. Now the question is, how can I close the connection after I stopped using? I have to call close() somewhere, don't I? I've been reading about the finalize() method, but people seemed to be skeptical about usage of this method anywhere at all. I'd expect it to have something like a destructor, but Java doesn't have that, so?
So could anyone provide me with a solution? Thanks in advance.
-33335890 0Just plot each segment separately. This also allows for more flexibility as you can independently change the colors, add direction arrows, etc, for each connection.
Here, I used a Python dictionary to hold your connectivity info.
import matplotlib.pyplot as plt coords = [(0.0, 0.0), (1.0, 1.0), (1.0, 0.0), (2.0, 1.0), (2.0, 0.0), (3.0, 1.0)] connectivity = {0: (1,2), #coords[0] <--> coords[1], coords[2] 1: (0, 2, 3), #coords[1] <--> coords[0], coords[2], coords[3] 2: (0, 1, 4), #coords[2] <--> coords[0], coords[1], coords[4] 3: (1, 3, 5), #coords[3] <--> coords[1], coords[3], coords[5] 4: (2, 3, 5), #coords[4] <--> coords[2], coords[3], coords[5] 5: (3, 4) #coords[5] <--> coords[3], coords[4] } x, y = zip(*coords) plt.plot(x, y, 'o') # plot the points alone for k, v in connectivity.iteritems(): for i in v: # plot each connections x, y = zip(coords[k], coords[i]) plt.plot(x, y, 'r') plt.show() There are duplicate lines here based on how you presented the connectivity, for example, (0,1) and (1,0). I'm assuming that you'll eventually want to put in the direction, so I left them in.
If you are using .Net 4.5 you can save yourself some key strokes and use the TPL
for (int i = 0; i < count; i++) { Task.Run(() => cl.Print("id","password")); }
-3492763 0 Active Directory User Group Membership I am trying to get a users group membership and limiting the results to those that match a string, ie I am only interested in the users group membership where the group begins with "test-".
The following is what I have been playing around with, even though the user is apart of several groups that match the search string, the If statement is not returning True on any of them.
Private Function GetGroups(ByVal userName As String) As Collection Dim Groups As New Collection Dim intCount As Integer Dim entry As DirectoryEntry = ADEntry() Dim mySearcher As DirectorySearcher = New DirectorySearcher(entry) Dim arrList As New ArrayList() ' Limit the search results to only users mySearcher.Filter = "(&(ObjectClass=User)(CN=" & userName & "))" ' Set the sort order mySearcher.PropertiesToLoad.Add("MemberOf") Dim searchResults As SearchResultCollection = mySearcher.FindAll() MessageBox.Show(searchResults.Count) If searchResults.Count > 0 Then Dim group As New DirectoryEntry(searchResults(0).Path) For Each member As Object In group.Properties("MemberOf") MessageBox.Show("Pre: "+ member) 'This message box returns all the groups the user is apart of. If group.Properties("memberOf").Contains("test-") = True Then MessageBox.Show(member) ' This message box never shows End If Next End If Return Groups End Function Is there any way of applying a search or If statement agains an Object where the constraint is a wildcard?
The groups I am looking for could be one of about 60 (this amount does increase and decrease as staff leave).
I am using VB.NET 2.0.
Thanks,
Matt
-16402013 0 Select all records of a typeI'm trying to get all records of specific type from RavenDB with C#.
When I'm using Lucene:
var serviceTraces = session.Advanced.LuceneQuery<ServiceTrace>("IDLoadDateIndex").Take(50); I'm getting the results in:
serviceTraces.QueryResult.Results
When I'm not using Lucene:
var serviceTraces = session.Query<ServiceTrace>("IDLoadDateIndex").Take(50); I'm not getting any results and an exception is thrown when trying to perform "ToList()" on "serviceTraces" object.
Why is that ?
UPDATE:
ServiceTrace class:
public class ServiceTrace { public ServiceTrace(ServiceDeployment sd) { // TODO: Complete member initialization this.ServiceDeploymentID = sd.Id; } public string Id { get; set; } public string TransactionID { get; set; } public string ParentTransactionID { get; set; } public string RequestID { get; set; } public int ApplicationCode { get; set; } public int InstituteCode { get; set; } public string ServiceDeploymentID { get; set; } public string UserHostAddress { get; set; } public string UserAgent { get; set; } public string Username { get; set; } public DateTime RequestDateTime { get; set; } public DateTime ResponseDateTime { get; set; } public string RequestBody { get; set; } public string ResponseBody { get; set; } public string Key1Value { get; set; } public string Key2Value { get; set; } public string Key3Value { get; set; } public string Key4Value { get; set; } public string Key5Value { get; set; } public int StatusCode { get; set; } public string StatusDescription { get; set; } public string FullExceptionText { get; set; } public DateTime LoadDate { get; set; } public DateTime ActivationDateTime { get; set; } public string HostAddress { get; set; } public string BpmID { get; set; } public DateTime PreProcessDatetime { get; set; } public string DestHostAddress { get; set; } public string ArchivePath { get; set; } public string BTInstanceID { get; set; } public string Temp1 { get; set; } public string ExternalComponentDuration { get; set; } public string SQLIdentity { get; set; } public string ExceptionCode { get; set; } public string CertificateID { get; set; } public string ExternalComponentType { get; set; } public string ActivationID { get; set; } } IDLoadDateIndex:
public class IDLoadDateIndex : AbstractIndexCreationTask<ServiceTrace> { public IDLoadDateIndex() { Map = serviceTrace => from st in serviceTrace select new { LoadDate = st.LoadDate }; Index(x => x.LoadDate, FieldIndexing.Analyzed); } }
-13109827 0 if you have exact the format +Z (YYY) XXX-XX-XX:
var num = input.replace( '/^\+\S+\s\((\d{3})\)\s(\d{3})-(\d{2})-(\d{2})$/', '\1\2\3\4' ); but a more tolerant variant would be
var num = input.replace( '/^(\+\S+|\D/', '' );
-24352732 0 Can not preview the welcome page in laravel 4.2 I have installed laravel 4.2 in http://localhost/laravel/varadha/
According to Quick start guide of laravel if i visit http://localhost/laravel/varadha/, i should get a welcome message. but i am getting this message.
Index of /laravel/varadha Name Last modified Size Description
Parent Directory - CONTRIBUTING.md 22-Jun-2014 20:28 146 app/ 22-Jun-2014 20:28 - artisan 22-Jun-2014 20:28 2.4K bootstrap/ 22-Jun-2014 20:28 - composer.json 22-Jun-2014 20:28 697 composer.lock 22-Jun-2014 20:28 58K laravel-master/ 22-Jun-2014 20:30 - phpunit.xml 22-Jun-2014 20:28 567 public/ 22-Jun-2014 20:28 - server.php 22-Jun-2014 20:28 519 vendor/ 22-Jun-2014 20:29 - I am using wamp server.
PHP 5.4.29.
MYSQl 5.5.8
Apache 2.2.17
-24254845 0Finally, I find there's a lock when compiling prepared statements. I was compiling a new prepared statement whenever a new request come in, after I changed to reuse it I got my app server scale. However, I still don't know why cross-region case can scale.
-4205321 0I had this problem and it took me forever to figure out. The Child table has to allow nulls on it's parent foreign key. NHibernate likes to save the children with NULL in the foreign key column and then go back and update with the correct ParentId.
-27536672 1 A dict-like class that uses transformed keysI'd like a dict-like class that transparently uses transformed keys on lookup, so that I can write
k in d # instead of f(k) in d d[k] # instead of d[f(k)] d.get(k, v) # instead of d.get(f(k), v) etc. (Imagine for example that f does some kind of canonicalization, e.g. f(k) returns k.lower().)
It seems that I can inherit from dict and override individual operations, but not that there is a centralized spot for such transformation that all keys go through. That means I have to override all of __contains__, __getitem__, get, and possibly __missing__, etc. This gets too tedious and error-prone, and not very attractive unless this overhead outweighs that of manually substituting f(k) for every call on a plain dict.
I'm trying to install this package from source on Windows and cannot work out what is going on and what I need to do in order to get this working.
I have the tar-gz file from CRAN, I have R-3.1.2 installed and RTools installed.
When I try to install this package I get the following error:
* installing *source* package 'XML' ... ** package 'XML' successfully unpacked and MD5 sums checked ** libs *** arch - i386 gcc -m32 -I"C:/PROGRA~1/R/R-31~1.2/include" -DNDEBUG -I/include/libxml2 -I/include -D_R_=1 -DUSE_R=1 -DUSE_XML_VERSION_H=1 -DLIBXML -DUSE_EXTERNAL_SUBSET=1 -DROOT_HAS_DTD_NODE=1 -DUMP_WITH_ENCODING=1 -DXML_ELEMENT_ETYPE=1 -DXML_ATTRIBUTE_ATYPE=1 -DLIBXML2=1 -DHAVE_XML_HAS_FEATURE -DLIBXML_STATIC -I"d:/RCompile/CRANpkg/extralibs64/local/include" -O3 -Wall -std=gnu99 -mtune=core2 -c DocParse.c -o DocParse.o In file included from DocParse.c:10:0: DocParse.h:18:27: fatal error: libxml/parser.h: No such file or directory compilation terminated. make: *** [DocParse.o] Error 1 Warning: running command 'make -f "Makevars.win" -f "C:/PROGRA~1/R/R-31~1.2/etc/i386/Makeconf" -f "C:/PROGRA~1/R/R-31~1.2/share/make/winshlib.mk" SHLIB="XML.dll" OBJECTS="DocParse.o EventParse.o ExpatParse.o HTMLParse.o NodeGC.o RSDTD.o RUtils.o Rcatalog.o Utils.o XMLEventParse.o XMLHashTree.o XMLTree.o fixNS.o libxmlFeatures.o schema.o xmlsecurity.o xpath.o"' had status 2 ERROR: compilation failed for package 'XML' Which seems that this is the actual problem:
DocParse.h:18:27: fatal error: libxml/parser.h: No such file or directory compilation terminated. So I've grabbed libxml2 from here:
http://www.zlatkovic.com/libxml.en.html
But I have literally no idea what to do next.
In the source for the libxml2 I can see the parser.h file mentioned in the error but what do I do with it or the library in order to get this install working?
-2185287 0Yes, as long as your controller inherits from Controller (which it must in order to work as an MVC controller), you can use the same syntax without the <%= %>.
Dim url = Url.Action("myAction", "myController", New With { ... }) alternatively if you reference the MVCContrib DLL, you will have access to strongly typed helpers, and be able to do something like:
Dim url = Url.Action(Of myController)(function(a) a.myAction(ID)) my VB coding days are dated, so forgive me if the syntax is a bit fudged
-24746210 0X.each do |key, value| value.class == BigDecimal ? puts value.to_s : puts value end or
X.each { |key, value | value.class == BigDecimal ? puts value.to_s : puts value } Check out the ternary operator.
Edit:
Also in regards to your edited question requesting one string:
new_array = X.map {|object| object.class == BigDecimal ? object.to_s : object } then turn it into a string with new_array.join("")
What you want to do is sort an array, whose elements are hash, based on the hash's "code" value.
entries.sort { |a, b| a["code"] <=> b["code"] } And also, I would suggest you do this in your controller instead of view.
EDIT:
Or you could do sort the tag first, then mapping them into an Array
Ci::Canonical::Language::Tag.sort_by do |a, b| a.code <=> b.code end.map do |tag| { "code" => tag.code, "description" => tag.description, "ordinal" => tag.value, } end
-11526627 0 bounding box of n glyphs, given individual bboxes and advances For specific reasons, I'm implementing my own font rendering, and an algorithm to compute the bounding box of a text by using bounding boxes of single glyphs, together with the respective advance, is needed. For clarification see this illustration:

For every of these N glyphs is given the relative bbox relative to the origin (xmin, xmax, ymin, ymax), and the advance (pseudocode):
int xmin[N], xmax[N], ymin[N], ymax[N], adv[N]; I will give the answer myself if noone bites.
-18946812 0i would like to see the retrieveContent method's code if it's possible and if you are trying to read a url's html content directly then there is a nice example here http://docs.oracle.com/javase/tutorial/networking/urls/readingURL.html
-11559072 0 XamlParseException - Image Pixels Manipulation with WPF C# / KinectI want to use this code to access the image pixels to be used with my Kinect code.. so i can replace the depth bits with the Image bits, so i created a WPF application and As soon as i run my code, i get this exception (it doesnt happen on a Console application) but i need this to run as a WPF application since . . i intend to use it with Kinect
XamlParseException
'The invocation of the constructor on type 'pixelManipulation.MainWindow' that matches the specified binding constraints threw an exception.' Line number '3' and line position '9'.
Here is the code:
public partial class MainWindow : Window { System.Drawing.Bitmap b = new System.Drawing.Bitmap(@"autumn_scene.jpg"); public MainWindow() { InitializeComponent(); doSomethingWithBitmapFast(b); } public static void doSomethingWithBitmapFast(System.Drawing.Bitmap bmp) { Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat); IntPtr ptr = bmpData.Scan0; int bytes = bmpData.Stride * bmp.Height; byte[] rgbValues = new byte[bytes]; System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes); byte red = 0; byte green = 0; byte blue = 0; for (int x = 0; x < bmp.Width; x++) { for (int y = 0; y < bmp.Height; y++) { //See the link above for an explanation //of this calculation (assumes 24bppRgb format) int position = (y * bmpData.Stride) + (x * 3); blue = rgbValues[position]; green = rgbValues[position + 1]; red = rgbValues[position + 2]; Console.WriteLine("Fast: " + red + " " + green + " " + blue); } } bmp.UnlockBits(bmpData); } } }
-15351745 0 Use mouseenter and mouseleave. The problem is that mouseoever/mouseout get triggered when you move between child elements, which you don't want.
http://jsfiddle.net/ExplosionPIlls/qNBEJ/3/
-10217562 0Theres no formal difference between 'Text classification' and 'Sentence classification'. After all, a sentence is a type of text. But generally, when people talk about text classification, IMHO they mean larger units of text such as an essay, review or speech. Classifying a politician's speech into democrat or republican is a lot easier than classifying a tweet. When you have a lot of text per instance, you don't need to squeeze each training instance for all the information it can give you and get pretty good performance out a bag-of-words naive-bayes model.
Basically you might not get the required performance numbers if you throw off-the-shelf weka classifiers at a corpora of sentences. You might have to augment the data in the sentence with POS tags, parse trees, word ordering, ngrams, etc. Also get any related metadata such as creation time, creation location, attributes of sentence author, etc. Obviously all of this depends on what exactly are you trying to classify.. the features that will work out for you need to be intuitively meaningful to the problem at hand.
-8482144 0Like the other answers above, i agree that this is just asking for an injection attack (and probably other types). Some things that you can do to prevent that and enhance security in other ways could be the following:
1 Look for something suspicious with your response handler. Lack of a query variable in the post, for instance, doesn't make sense, so it should just kill the process.
@$_POST["query"] or die('Restricted access'); 2 Use preg_match to sanatize specific fields.
if (!preg_match("/^[a-zA-Z0-9]+$/", $_POST[query])){ die('Restricted access'); } 3 Use more fields, even if they are semi-meaningless and hidden, to add more reasons to kill the process through their absence, or lack of a certain text pattern (optional).
4 You shouldn't send a complete query through the POST at all. Just the elements that are necessary as input from the user. This will let you build the query in PHP and have more control of what actually makes it to the final query. Also the user doesn't need to know your table names
5 Use mysql_real_escape_string on the posted data to turn command characters into literal characters before entering data into a db. This way someone would have a last name of DROP TABLE whatever, instead of actually dropping table whatever.
$firstname = mysql_real_escape_string($_POST[fname]); $lastname = mysql_real_escape_string($_POST[lname]); $email = mysql_real_escape_string($_POST[email]); $sql="INSERT INTO someTable (firstname, lastname, email) VALUES('$firstname','$lastname','$email')"; 6 Last, but not least, be creative, and find more reasons to kill your application, while at the same time giving the same die message on every die statement (once debugging is done). This way if someone is hacking you, you don't give them any feedback that they are getting through some of your obstacles.
There's always room for more security, but this should help a little.
-6038296 0If there's an outside chance that the order of [i] is not in a predictable order, or possibly has gaps, but you need to use it as a key:
public class Thing { int SubjectID { get; set; } int VarNumber { get; set; } string VarName { get; set; } string Title { get; set; } } Dictionary<int, Thing> things = new Dictionary<int, Thing>(); dict.Add(i, thing); Then to find a Thing:
var myThing = things[i];
-31707505 0 Check your php.ini file for date.timezone and make sure its set to
date.timezone = "Europe/Moscow"
Two issues I can see here:
The empty() and remove() methods of jQuery actually do quite a bit of work. See John Resig's JavaScript Function Call Profiling for why.
The other thing is that for large amounts of tabular data you might consider a datagrid library such as the excellent DataTables to load your data on the fly from the server, increasing the number of network calls, but decreasing the size of those calls. I had a very complicated table with 1500 rows that got quite slow, changing to the new AJAX based table made this same data seem rather fast.
You should convert your cert and you can use openssl to achieve the conversion that you are wanting.
For instance:
openssl pkcs12 -export -out cert.pfx -inkey cert.key -in cert.crt
-12636205 0 My solution to this was to add an event handler in the test method, so that when the event is raised, the test method will create a CancelEventAgrs and set its Cancel to True/False.
Public Sub TestingMethod() Dim txt As TextLoader = Nothing AddHandler TextLoader.LoadingDoneEvent, (Sub(e As ComponentModel.CancelEventArgs) e.Cancel = True End Sub) txt = New TextLoader() txt.FireThisEvent() End Sub
-3660512 0 Cross-platform generally refers to a technology which can be used for multiple operating systems. For example, Mono is an open-source implementation of the Common Language Runtime (CLR), which are the underlying libraries required by .NET.
Mono runs on Linux, BSD, Unix, Mac OS X, Solaris and Windows. Mono itself is not an IDE, but several cross-platform IDEs exist as well. The most popular is MonoDevelop.
Several languages are built on top of the .NET framework such as C# and VB.NET. C# is the most popular for cross-platform development.
-13629575 0 How to use SSH with PuTTY using a proxy server?This is a journey that doesn't seem to have an end. Please bear with the story.
I am wanting to write a variety of Perl programs that connect to an SSH server. The server is a Mac, the client is Windows behind an HTTP proxy. PuTTY works perfectly to connect, but executing the Perl scripts isn't ideal, for several reasons.
I want to have an interactive (not with the user, but with the software running on the server) Perl program running on the client and the server, a la how rsync works with the -e option.
First step, how do I connect? I use plink (from PuTTY), which has a variety of useful options... tunneling, running a series of commands, etc. From there, I can easily run commands and scripts on the server and get back the result, process the result, and then do the next command. But this is SLOW because it has to renegotiate the PuTTY/SSH connection each time. Hence the desire for an interactive approach.
When running plink in this manner, I could interact with the plink command, but I'm having trouble with double-piping (input and output, never mind triple-piping to also get STDERR). I tried everything on http://docstore.mik.ua/orelly/perl2/prog/ch16_03.htm and nothing worked. Got various errors, etc.
Next I tried writing my own client/server programs using sockets. Worked pretty well, except for some reason each time I run the SocketServer on the server program and then connect to it (using plink to tunnel localhost to the server's port), the port closes itself off and refuses future connections. So I have to change the port every time, which seems counterproductive (probably an issue with my code, but I don't see it).
The next step was trying Expect.pm. However, that seems to only work under Linux or CYGWIN, which I don't want to get too deep into. This needs to stay native Windows as much as possible.
My latest is looking into Net::SSH::Perl and other SSH modules. I set up a port 22 tunnel with plink and then in CYGWIN I try:
ssh user@localhost I enter my password and all is wonderful! Works like a champ!
So then I try the following program (again, with the port 22 tunnel established)
use Net::SSH::Perl; my $ssh = Net::SSH::Perl->new('localhost'); $ssh->login('<user>','<pass>'); my($stdout, $stderr, $exit) = $ssh->cmd('ls -l'); while (<$stdout>) { print; } (user and pass above are substituted for the real user and pass) I can see the plink tunnel opening the forwarded port, but the program returns
Permission denied at E:\Scripts\ExplorationScripts\NetSSHPerl.pl line 3 So, this is where I am... I have many more SSH Perl modules to try, but I was wondering if anyone else had this situation. I see tons of people using PuTTY and SSH stuff, but none of them are going through a proxy (and thus NEED PuTTY). And I don't have the time or patience to mess with something like corkscrew, so please let's not go down that particular rabbit hole.
I'm open for suggestions...
Thanks.
... continuing the journey... the new thing I've tried, and y'all will probably laugh at this bass-ackward solution... I tunneled port 23 through the Mac to a Windows machine on the same network running Telnet. Then, using Net::Telnet I am able to telnet to the Windows machine. Very awkward. I also wanted to be able to establish the tunnel and then kill it at the end of the program, so I added some oddball stuff. Check it out and PLEASE help me get a better solution to this.
use Net::Telnet; #establish tunnel open my $tunnel,"| plink -L 23:<local IP of windows machine>:23 <server> -pw <pass>"; sleep 7; #Now it's time to do the telnet boogie! my $t=new Net::Telnet ( Timeout=>10, Errmode=>'return',Prompt => '/>$/'); #$t->output_log('telnet.log'); $t->input_log('telneti.log'); $t->open("localhost"); $t->login('<user>','<pass>'); @lines = $t->cmd("dir /b"); print @lines; $t->close(); print $tunnel "exit\n"; close $tunnel; The $tunnel thing is the weirdness. plink will establish a terminal session, so I opened a handle to it's STDIN via the pipe. The -L establishes the tunnel. When I'm done with the telnetting, I print "exit" to plink which exits the bash session. I also use the "sleep 7" to give it enough time to establish the session. Ugh! But it seems to work moderately well.
-38316988 0 Image Processing (need pixel value of an image)I want to make an app, in which I want to take a picture and input x,y axis it will show me corresponding point pixel value from the captured picture .
I don't have any knowledge about image processing well . So, how can I do it ? help me .
-30840009 0 Java javac is not regonized as an internal or external commandI was just starting to learn basic java for I apparently need it to be able to code bukkit plugins for minecraft and I'm stuck on the following issue.
I have made the HelloWorldApp.java in the folder c/test but it wont do want its supposed to do. Any help would be good and please try to dumb down any coding, etc
This is how I invoked it:
C:\Users\Matthew\Desktop>cd C:\test C:\test>javac HelloWorldApp.java 'javac' is not recognized as an internal or external command, operable program or batch file. C:\test>
-13003646 0 You can just use boolean clauses:
(assert (myTemp (one asd) (second jhg)) (myTemp (one asd) (second kjh)) (myTemp (one bvc) (second jhg)) (myTemp (one bvc) (second jhg) (third qwe))) (find-fact ((?p myTemp)) (or (eq ?p:one bvc) (eq ?p:third qwe)) (<Fact-4>) (find-fact ((?p myTemp)) (or (eq ?p:one bvc) (eq ?p:second jhg)) (<Fact-1>) (find-all-fact ((?p myTemp)) (or (eq ?p:one bvc) (eq ?p:second jhg)) (<Fact-1> <Fact-3> <Fact-4>)
-37426564 0 Laravel 5.2 Multi-Auth with API guard uses wrong table I'm trying to get a multi-auth system working where Users can log in via the normal web portal, but a separate database of entities (named "robots" for example) can also log in via an API guard token driver. But no matter what I do, the setup I have is not directing my authentication guard to the correct Robot database and keeps trying to authenticate these requests as Users via tokens (which fails, because users don't have tokens).
Can someone help me find where I've gone wrong?
I've started by putting together a middleware group in Kernel.php:
'api' => [ 'throttle:60,1', 'auth:api', ], This uses settings in config/auth.php
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'token', 'provider' => 'robots', ], ], 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => App\User::class, ], 'robots' => [ 'driver' => 'eloquent', 'model' => App\Models\Robot::class, ], ], The middleware gets called in routes.php
Route::group(['middleware' => 'api'], function () { Route::get('api/request', 'API\RequestController@index'); }); It uses this model:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Contracts\Auth\Authenticatable; class Robots extends Authenticatable { protected $fillable = [ 'serial_number','api_token', ]; protected $guard = 'Robots'; protected $hidden = [ 'api_token', ]; } Any ideas?
Update: on further inspection, it appears that most of the settings in auth.php are not applying properly - is there some way I can force these settings to take effect?
-29038271 0As of right now, you cannot retrieve a permanent access token. You have 2 options that come close.
The first is to request a "refresh" token when using the standard OAuth flow. That's what you're doing by sending "duration" as "permanent" in your code. The refresh token can be used to automatically retrieve new 1 hour access tokens without user intervention; the only manual steps are on the initial retrieval of the refresh token.
The second alternative, which applies only when writing a script for personal use, is to use the password grant type. The steps are described in more detail on reddit's "OAuth Quick Start" wiki page, but I'll summarize here:
https://www.reddit.com/api/v1/access_token with POST parameters grant_type=password&username=<USERNAME>&password=<PASSWORD>. Send your client ID and secret as HTTP basic authentication. <USERNAME> must be registered as a developer of the OAuth 2 client ID you send.So you just want to exclude files containing backup in their names? This should work:
@echo off setlocal enabledelayedexpansion for /r "C:\Users\b00m49\Desktop\LSPTEST" %%a in (K_E*.dwg) do ( set filename=%%a if "!filename:backup=!"=="!filename!" ( rem start /wait "C:\Program Files\Autodesk\Autocad 2013\acad.exe" "%%a" /b "C:\Users\b00m49\Desktop\LSPTEST\expSQM.scr" ) ) pause
-30901183 1 Django @csrf_exempt decorator not working I'm using DJango 1.8 on a linode server, and have the following view:
import json from django.http import HttpResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt def home_view(request): r = { 'response': 'OK', 'data': None } return HttpResponse(json.dumps(r), content_type = "application/json") @csrf_exempt def ping(request): r = { 'response': 'OK', 'data': 'ping' } return HttpResponse(json.dumps(r), content_type = "application/json") My urls look like this:
urlpatterns = [ url(r'^django/admin/', include(admin.site.urls)), url(r'^django/$', home_view), url(r'^django/ping/$', ping), url(r'^django/echo/$', echo), ] If I go to my linode site at http://mylinodesite/django/ping/
I get:
{"data": "ping", "response": "OK"}
Great. If I use jquery and do a
$.get("http://mylinodesite/django/ping/")
I get
No 'Access-Control-Allow-Origin' header is present on the requested resource.
From what I understand the @csrf_exempt is supposed to get rid of the CSRF header stuff. What gives?
-35464022 0dt = as.data.table(DF) # or setDT to convert in place # cumulative mean, but without the date restriction dt[, rawAvgRets := cumsum(Return) / (1:.N), by = Ticker] # find the latest matching date using a rolling merge (assumes sorted dates) # if you run into > vs >= issues, adjust enter or exit date by a day dt[, avgRets := dt[dt, rawAvgRets, roll = TRUE, on = c('Ticker' = 'Ticker', 'Exit Date' = 'Enter Date')]] # Ticker Enter Date Exit Date Return rawAvgRets avgRets # 1: ABC 2005-02-08 2005-03-09 4.669 4.6690000 NA # 2: ABC 2005-02-23 2005-03-23 4.034 4.3515000 NA # 3: ABC 2005-06-07 2005-07-06 3.796 4.1663333 4.3515000 # 4: ABC 2005-06-08 2005-07-07 -4.059 2.1100000 4.3515000 # 5: ABC 2005-08-16 2005-09-14 -11.168 -0.5456000 2.1100000 # 6: ABC 2005-09-07 2005-10-05 -0.496 -0.5373333 2.1100000 # 7: ABC 2005-11-15 2005-12-14 -3.597 -0.9744286 -0.5373333 # 8: ABC 2005-11-17 2005-12-16 3.450 -0.4213750 -0.5373333 # 9: ABC 2005-12-06 2006-01-05 -4.428 -0.8665556 -0.5373333 #10: ABC 2005-12-23 2006-01-25 1.914 -0.5885000 -0.4213750 #11: ABC 2006-02-09 2006-03-10 3.577 -0.2098182 -0.5885000 #12: ABC 2006-02-10 2006-03-13 4.000 0.1410000 -0.5885000 #13: ABC 2006-02-15 2006-03-16 8.451 0.7802308 -0.5885000 #14: ABC 2006-02-22 2006-03-22 5.521 1.1188571 -0.5885000 #15: ABC 2006-05-01 2006-05-30 10.324 1.7325333 1.1188571 #16: XYZ 2005-02-22 2005-03-22 3.104 3.1040000 NA #17: XYZ 2005-02-28 2005-03-29 0.787 1.9455000 NA #18: XYZ 2005-03-01 2005-03-30 -3.407 0.1613333 NA #19: XYZ 2005-03-03 2005-04-01 -1.441 -0.2392500 NA #20: XYZ 2005-03-04 2005-04-04 -4.157 -1.0228000 NA #21: XYZ 2005-03-11 2005-04-11 4.343 -0.1285000 NA #22: XYZ 2005-03-15 2005-04-13 2.827 0.2937143 NA #23: XYZ 2005-04-04 2005-05-02 0.425 0.3101250 -1.0228000 #24: XYZ 2005-04-05 2005-05-03 -1.370 0.1234444 -1.0228000 #25: XYZ 2005-04-15 2005-05-13 -3.175 -0.2064000 0.2937143 #26: XYZ 2005-04-22 2005-05-20 -11.027 -1.1900909 0.2937143 #27: XYZ 2005-04-28 2005-05-26 8.144 -0.4122500 0.2937143 # Ticker Enter Date Exit Date Return rawAvgRets avgRets
-33837904 0 Re-read the $set documentation https://docs.mongodb.org/v3.0/reference/operator/update/set/ It specifically says it will replace what is there. So it doesn't care if a document exists or not that's why it doesn't return the error. you need additional operators to reject the query if it exists and is the same.
edit/update to below comment
You have to trigger the error in order to know if the DB as the collection already and if it's up to date. So an additional operator is required to check if the collection found already has the updated information. MongoDB uses operators represented with $ so $gt or $lt or $nor (greater than , less than, Select everything but this) there's more but i'll let you explore the possibilities. https://docs.mongodb.org/v3.0/reference/operator/query/nor/
this line needs to trigger the error based on your expressions and operators. when you get that working don't just throw the error allow the program to continue to the next because this error isn't meant to break (throw) on that error it's only there to tell you hey the DB has this and it's updated, and on error will let you know nothing was done.
collection.updateOne(query, {"$set": data},{w: "majority"},function (err,result){ console.error(err);console.log(result); });
I was using IntelliJ with JBoss EAP and it failed like your error (Access Denied). So I turned off my virus protection (MSE), problem was solved.
-14368301 0You should have a look at this great module, async which simplifies async tasks like this. You can use queue, simple example:
N = # of simultaneous tasks var q = async.queue(function (task, callback) { somehttprequestfunction(task.url, function(){ callback(); } }, N); q.drain = function() { console.log('all items have been processed'); } for(var i = 0; i < 2000; i++){ q.push({url:"http://somewebsite.com/"+i+"/feed/"}); } It will have a window of ongoing actions and the tasks room will be available for a future task if you only invoke the callback function. Difference is, your code now opens 2000 connections immidiately and obviously the failure rate is high. Limiting it to a reasonable value, 5,10,20 (depends on site and connection) will result in a better sucess rate. If a request fails, you can always try it again, or push the task to another async queue for another trial. The key point is to invoke callback() in queue function, so that a room will be available when it is done.
-33010859 0 Importing data into an existing database in neo4jI am using neo4j-import to import millions of nodes and relationship.
Is there any option to create relationships in to the existing database. I want to import the relationship using neo4j-import because I have millions of relationships.
Your cooperation is truly appreciated! Thanks
-39160621 0 apply css to a html element after finding some specific class name avaialbleI am trying to apply css to a div(.references) after finding a specific class name(.overview) available in anywhere in that document. its not working .references div not inside .overview div
if ($('div').hasClass('overview')) { $('.references').css("display", "none !important"); } Please help
-25318056 0 How do I make SSHJ initiate outbound SFTP on a non-standard port?I'm doing this and it works fine but I'd like to be able to hit an sshd on a port other than 22.
final SSHClient ssh = new SSHClient(); ssh.addHostKeyVerifier( SFTP_KEY_FINGERPRINT ); ssh.connect( SFTP_SERVER_HOSTNAME ); try { ssh.authPassword( SFTP_USER , SFTP_PASSWORD ); final String src = fileToFtp.getFileName().toString(); final SFTPClient sftp = ssh.newSFTPClient(); try { sftp.put(new FileSystemFile(src), "/"); success = true; } finally { sftp.close(); } } finally { ssh.disconnect(); }
-10137380 0 Simply use echo form_dropdown('school', $school_list, set_value('school', @$school->id));
Then you know by the @ that value may be empty sometimes, and it supresses errors if that value is missing.
Doing this will send a NULL value to the 3rd parameter if you have no id, and it will instead select the first <option> by default.
In Visual Studio, it's possible to use internal modules without having to include /// <reference path="..." /> tags.
How can one accomplish the same in WebStorm 10?
Another question, how can I get WebStorm to import the typings to a project? WebStorm 10 puts typings in the cache folder.
-38884806 0The problem is in pyparsing:
The pyparsing module is an alternative approach to creating and executing simple grammars, vs. the traditional lex/yacc approach, or the use of regular expressions. With pyparsing, you don't need to learn a new syntax for defining grammars or matching expressions - the parsing module provides a library of classes that you use to construct the grammar directly in Python.
In order to "construct the grammar directly in Python", pyparsing needs to read the source file (in this case a matplotlib source file) where the grammar is defined. In what would usually just be a bit of harmless extra work, pyparsing is reading not just the matplotlib source file but everything in the stack at the point the grammar is defined, all the way down to the source file where you have your import matplotlib. When it reaches your source file it chokes, because your file indeed is not in UTF-8; 0x96 is the Windows-1252 (and/or Latin-1) encoding for the en dash. This issue (reading too much of the stack) has already been fixed by the author of pyparsing so the fix should be in the next release of pyparsing (probably 2.1.8).
By the way, matplotlib is defining a pyparsing grammar in order to be able to read fontconfig files, which are a way of configuring fonts used mainly on Linux. So on Windows pyparsing is probably not even required to use matplotlib!
-40839068 0This is really surprising to me, is there any internal memory copy that slow down the processing?
ArrayOps.drop internally calls IterableLike.slice, which allocates a builder that produces a new Array for each call:
override def slice(from: Int, until: Int): Repr = { val lo = math.max(from, 0) val hi = math.min(math.max(until, 0), length) val elems = math.max(hi - lo, 0) val b = newBuilder b.sizeHint(elems) var i = lo while (i < hi) { b += self(i) i += 1 } b.result() } You're seeing the cost of the iteration + allocation. You didn't specify how many times this happens and what's the size of the collection, but if it's large this could be time consuming.
One way of optimizing this is to generate a List[String] instead which simply iterates the collection and drops it's head element. Note this will occur an additional traversal of the Array[T] to create the list, so make sure to benchmark this to see you actually gain anything:
val items = s.split(" +").toList val afterDrop = items.drop(2).mkString(" ") Another possibility is to enrich Array[T] to include your own version of mkString which manually populates a StringBuilder:
object RichOps { implicit class RichArray[T](val arr: Array[T]) extends AnyVal { def mkStringWithIndex(start: Int, end: Int, separator: String): String = { var idx = start val stringBuilder = new StringBuilder(end - start) while (idx < end) { stringBuilder.append(arr(idx)) if (idx != end - 1) { stringBuilder.append(separator) } idx += 1 } stringBuilder.toString() } } } And now we have:
object Test { def main(args: Array[String]): Unit = { import RichOps._ val items = "hello everyone and welcome".split(" ") println(items.mkStringWithIndex(2, items.length, " ")) } Yields:
and welcome
-19506163 0 How to correctly chain conditional(?) promises with Q.js I've still not quite got a complete understanding of promises so apologies if this is a simple misunderstanding.
I have a function for deleting an item on a page but I have a specific behaviour depending on the state of the page. Psuedo code-wise it's something like this:
Does the page have changes? If yes - prompt to save changes first If yes - save changes If no - exit function If no - continue Prompt to confirm delete If yes - delete item and reload data If no - exit function Hopefully that makes sense. Essentially if there are changes, the data must be saved first. Then if the data has been saved, or if there were no changes to begin with, prompt the user to confirm deletion. The problem is I'm using durandal and breeze, and I can't seem to chain the promises they return together correctly.
My function currently looks like this, which I know is wrong, but I'm struggling to work out where to fix it.
if (this.hasChanges()) { app.showMessage('Changes must be saved before removing external accounts. Would you like to save your changes now?', 'Unsaved Changes...', ['Yes', 'No']) .then(function (selectedOption) { if (selectedOption === 'Yes') { return this.save(); } else { Q.resolve() } }); } app.showMessage('Are you sure you want to delete this item?', 'Delete?', ['Yes', 'No']) .then(function (selectedOption) { if (selectedOption === 'Yes') { item.entityAspect.setDeleted(); datacontext.saveChanges() .then(function () { logger.logNotificationInfo('Item deleted.', '', router.activeInstruction().config.moduleId); Q.resolve(this.refresh(true)); }.bind(this)); } }.bind(this)); The app.showMessage call from durandal returns a promise, then the this.save returns a promise, and finally the this.refresh also returns a promise.
So I guess I need to check the hasChanges, then if necessary call save, and resolve it. Then after that conditional section has finished resolving, call the second prompt, and then resolve all the promises within that.
I'm sorry I don't think this is super clear, but that's also I think coming from the fact I'm not completely following the chains here.
Any help much appreciated! Thanks.
-11672493 0 SQL-based, FIFO logicI need to build a query that will aggregate the # of units of blood that has been transfused so it can be compared to the # of units of blood that has been cross-matched. Blood (a precious resource) that is cross-matched, but not transfused is wasted.
Providers are supposed to check the system-of-record (Epic) for 'active' cross-match orders before creating new ones. Providers that don't do this are 'penalized' (provider 20). No penalty applies (it seems) for providers that don't transfuse all of the blood that they've cross-matched (provider 10).
Cross-match orders:
|ENC_ID|PROV_ID|ORDER_ID|ORDER_TIME |UNITS| | 1| 10| 100|26-JUL-12 13:00| 4| | 1| 20| 231|26-JUL-12 15:00| 2| Transfusion orders:
|ENC_ID|PROV_ID|ORDER_ID|ORDER_TIME |UNITS| | 1| 10| 500|26-JUL-12 13:05| 1| | 1| 10| 501|26-JUL-12 13:25| 1| | 1| 20| 501|26-JUL-12 15:00| 1| | 1| 20| 501|26-JUL-12 15:21| 2| Rules:
transfusion.END_ID=cross-match.ENC_ID)transfusion.ORDER_TIME >= cross-match.ORDER_TIMEDesired result:
|ENC_ID|PROV_ID|ORDER_ID|ORDER_TIME |CROSS-MATCHED|TRANSFUSED| | 1| 10| 100|26-JUL-12 13:00| 4| 4| | 1| 20| 231|26-JUL-12 15:00| 2| 1| Provider 10 'credited' with Provider 20's transfusions.
Can this logic be implemented without resorting to a procedure?
-37816643 0 Why cursor type adOpenForwardOnly performance is better than adOpenStatic?I am trying to understand the difference between CursorTypeEnum 0 and 3, as described here. Both are static, except type 0 only supports forward iteration.
In my case rs.Open strsql, cn, 0 returns consistently in under 30 seconds, whereas performance of the same query with type 3 cursor fluctuates widely between 3 and 8 minutes.
They both need to lock the underlying tables in order to create static set, so why such dramatic difference?
Disclaimer: I am no expert in VBA or transactional databases. I understand concurrency, algorithmic complexity and data structures.
-2969853 0SharePoint document versioning is internal to the server architecture, and cannot be extended.
-26184925 0 Convert a string key in a JSON object to a child object?I've looped through an document.form.element the names are constructed into an array name like so:
Some of the names of they keys are like so in JSON:
{ data[name]: "foo", data[address]: "baz drive", data[city]: "Dallas", data[state]: "Texas", data[phone]: "555-1212" } Is there a way to convert it to this with Pure JavaScript (and without frameworks like jQuery) without using eval?:
{ data: { name: "foo", address: "baz drive", city: "Dallas", state: "Texas", phone: "555-1212" } } <script type="javascript"> var o = { data[name]: "foo", data[address]: "baz drive", data[city]: "Dallas", data[state]: "Texas", data[phone]: "555-1212" } var temp = []; for (key in o) { temp[JSON.parse(key)] = o; } </script> Fiddle is here: http://jsfiddle.net/chrisjlee/medbzv9a/
Or is this not totally possible?
-14174692 0 setText of a TextView arrayWhat I'm trying to do is have an EditText where people enter their names. As people press the "Add Player" button, the name which they just typed appears below in the list form. So I've created 8 textviews which are initially invisible but as people type the name press the "Add Player" button, the text changes to their names and becomes visible.
So I set up a TextView array of the list of names, which are all text views
TextView[] nameList = new TextView[]{name1, name2, name3, name4, name5, name6, name7, name8}; Later on in the code in the onClick section, I had
for (int i = 0; i < 8; i++) { String name = etName.getText().toString(); nameList[i].setText(name); nameList[i].setVisibility(View.VISIBLE); } However, with this, whenever I press the "add player" button, the app crashes and I get a NullPointerException. How would I solve this?
The problem isn't with the for loop as the app crashed without it. The problem seems to be with the array as if I put
name1.setText(name); name1.setVisibility(View.VISIBLE); the code worked fine.
-21230175 0 Fastest between mat of Vec2 or 2 MatI have a question concerning access speed of OpenCV matrix.
I currently need two channels of unsigned char to contain my data. But at one point i need to split my data to process them separately (which probably results in a matrix copy)
for( auto ptr = ROI.begin<cv::Vec2b>(); ptr!=ROI.end<cv::Vec2b>();ptr++){ //insert values } cv::split(ROI,channels_vector) process(channels_vector[0]); process(channels_vector[1]); more_stuff(ROI); My question is the following : Should I use two different matrix at the beginning to avoid the split or let it like this ? Or as it may depend on my computation what is the difference of cost between two accesses of a matrix and a matrix copy ?
-37570362 0For example you can change
font-size: 40px; to font-size: 2.500em;
There is also a online convertor to check your pixels in em-s
-16272611 0I just added "-с" parameter. It makes Psexec copy executable to remote machine. So it works without access errors.
-15986463 0self.lblQuestionTitle.text = [nextQuestion objectForKey:@"QuestionTitle"];
-26787995 0 Absolutely positioned elements are removed from the normal document flow, so they won't fill up 100% of their parent like regular static block level elements. Instead, they rely on their content width or a specified width. Firefox seems to apply the content width a bit differently than Chrome or IE, which is why it appears cut off.
Not sure of your use-case or what browsers you support, but you have a couple options:
display: table-cell for media body. This has the caveat that your media object basically take up as much room as it can since it behaves like a table cell, which may not be what you're after.Use a centralized logger and disable output when you're taking user input.
-37337203 0update may 27:
we just released an update (version 9.0.1) to fix the incompatibility I mentioned in my first edit.
Please update your dependencies and let us know if this is still an issue.
Thanks!
original answer May 20:
The issue you are experiencing is due to an incompatibility between
play-services / firebase sdk v9.0.0 and com.android.support:appcompat-v7 >= 24
(the version released with android-N sdk)
You should be able to fix it by targeting an earlier version of the support library. Like:
compile 'com.android.support:appcompat-v7:23.4.0'
-14905038 0 If you call System.exit() your code won't execute finally, because that call terminates your JVM.
I am trying to write an x86 emulator in JavaScript for education purposes. I have already written a compiler and at the moment I am trying to write the x86 emulator in JavaScript.
I have however a problem with the DIV instruction. According to http://siyobik.info/index.php?module=x86&id=72 DIV takes a 64bit number as input by interpreting EDX as the higher 32bit and EAX as the lower 32bit. It then divides this number by the DIV parameter and puts the result (if it is not greater than 0xFFFFFFFF) into EAX and the remainder into EDX.
As JavaScript does not support 64bit integer I need to apply some tricks. But so far I did not come up with something useful.
Does someone here have an idea how to implement that correctly with 32bit arithmetic?
-34631211 0<div ><img src="<%=request.getContextPath() %>/images/logo.gif" title="Your Title" /></div>
-20323103 0 When using == or != or > or < if the types of the two expressions are different it will attempt to convert them to string, number, or Boolean etc
use below code to compare
if ( Date.parse ( currentdate) > Date.parse ( enddate) ) { // your code }
-24680396 0 I would up doing this in a snippet instead:
<?php //getgalleryAlbumCover $output = ''; $sql = "select * from modx_gallery_albums mga where mga.id = $id"; $album = $modx->query($sql); if (!is_object($album)) {return;} $data = $album->fetch(PDO::FETCH_ASSOC); // just in case ;) $modx->toPlaceholders($data); $output = $data['cover_filename']; return $output;
-34573051 0 CSS:
h2 { color: blue; background-color: white; text-align: center; } header { background-color: black; width: 100%; height: 100px; } Hope this work :)
-24414708 0 clang: error: linker command failed with exit code 1 with duplicate symbol _TableLookup in database.o and main.oAfter changing the code, I got new error in database_definitions.h header file. The error is near the 'extern const Lookup_Table TableLookup[TABLE_COUNT];' and mentioned the error in the code with comments next to it. I also got warning in 'database.c' file near the return &(TableLookup[index]); in the 'Lookup_Table* GetTableMetadata(char *tableName)' function. The error is pasted in the code next to it. Kindly review and help me in solving in this issue.
**database.c**: const Lookup_Table TableLookup[TABLE_COUNT]= { { .tableName = "Folder_Table", // .tableInitializer = (void*)&InitFolder_Table, .tableMemory = sizeof(Folder_Table), .columns = 5, .columnNames = {"folderID","field1","field2","field3","field4"}, // Fill out field name metadata .columnSize = {SIZE_OF(Folder_Table,folderID), SIZE_OF(Folder_Table,field1), SIZE_OF(Folder_Table,field2), SIZE_OF(Folder_Table,field3), SIZE_OF(Folder_Table,field4)}, .columnType = {TYPE_INT, TYPE_FLOAT, TYPE_INT, TYPE_FLOAT, TYPE_TEXT}, .subTable = {{.tableName = "Item_Table", .pointerOffset = offsetof(Folder_Table,item)}, {.tableName = "nextRow", .pointerOffset = offsetof(Folder_Table, nextRow)}, {.tableName = "lastRow", .pointerOffset = offsetof(Folder_Table, lastRow)}, {.tableName = "\0", .pointerOffset = 0 }}, }, { .tableName = "Item_Table", // .tableInitializer = (void*)&InitItem_Table, .tableMemory = sizeof(Item_Table), .columns = 4, .columnNames = {"ItemID\0","FolderID\0","field1\0","field2\0"}, .columnSize = {SIZE_OF(Item_Table,itemID), SIZE_OF(Item_Table,folderID), SIZE_OF(Item_Table,field1), SIZE_OF(Item_Table,field2)}, .columnType = {TYPE_INT, TYPE_INT, TYPE_TEXT, TYPE_FLOAT}, .subTable = {{.tableName = "nextRow", .pointerOffset = offsetof(Item_Table, nextRow)}, {.tableName = "lastRow", .pointerOffset = offsetof(Item_Table, lastRow)}, {.tableName = "\0", .pointerOffset = 0}}, } }; //==================================================================================== // Struct Table Initializer and metadata functions //==================================================================================== //------------------------------------------------------------------------------------ // Find the memory size of a table specified by name //------------------------------------------------------------------------------------ int GetTableSize(char *tableName) { int index; //// Find function matching function name string for (index=0 ; index < TABLE_COUNT; index++) { if (strcmp(TableLookup[index].tableName, tableName)) { return(TableLookup[index].tableMemory); } } return 1; // Return error, should this be an exception? } //------------------------------------------------------------------------------------ // Return the index of of the table from the table-lookuptable //------------------------------------------------------------------------------------ Lookup_Table* GetTableMetadata(char *tableName) { //// Find function matching function name string for (int index=0; index < TABLE_COUNT; index++) { if (strcmp(TableLookup[index].tableName, tableName)) { `return &(TableLookup[index]);//error: 'Returning 'const Lookup_Table*(aka 'const structLookup_Table') from a function with result type 'Lookup_Table'(aka 'struct Lookup_Table") discards qualifiers`' } } return 0; // Return error } **database.h**: #ifndef database_h #define database_h #include "database_definitions.h" #define ONE_ROW 1 //==================================================================================== // Function Definitions //==================================================================================== int SQLOpen(void); //isc_db_handle SQLGetDatabase(void); Lookup_Table* GetTableMetadata(char *tableName); Sub_Table* GetSubTableMetadata(char *tableName, char *subTableName); #endif **database_definitions.h**: #ifndef database_database_h #define database_database_h extern const Lookup_Table TableLookup [TABLE_COUNT]; //error:unknown type name 'Lookup_Table' //==================================================================================== // SQL Table Metadata Structures //==================================================================================== typedef struct Folder_Table // Table type name gets "_Table" added to the SQLite name { //// Fields // Comments are added to seperate the fields, Relationships, and metadata int folderID; // Fields are added as elements of the type and length listed in SQLite float field1; int field2; float field3; char field4[40]; // string length '40' is queried from SQLite settings for field //// Relationships struct Item_Table *item; // Pointer to the sub-table struct Folder_Table *nextRow; // Linked List Pointer to the next-row struct Folder_Table *lastRow; // Linked List Pointer to the last-row } Folder_Table; typedef struct Item_Table { //// Fields int itemID; int folderID; char field1[32]; float field2; //// Relationships Folder_Table *folder; struct Item_Table *nextRow; struct Item_Table *lastRow; } Item_Table; typedef struct Sub_Table { char tableName [TABLE_NAME_LENGTH]; // Sub-table name int pointerOffset; // Sub-table pointer memory offset in the struct }Sub_Table; typedef struct Lookup_Table { char tableName [TABLE_NAME_LENGTH]; // Stores table name void (*tableInitializer)(void *); // Pointer to the initializer function int tableMemory; // Size of the table memory instance int columns; // Number of columns in the table char columnNames[MAX_COLUMNS][COLUMN_NAME_LENGTH]; // Array of column names int columnSize [MAX_COLUMNS]; // Array of column variable memory sizes int columnType [MAX_COLUMNS]; // Array of column variable types Sub_Table subTable [MAX_SUB_TABLES]; // Stores sub-table pointers }Lookup_Table; #endif **main.c**: #include <stdio.h> #include "database.h" int main(int argc, const char * argv[]) { // SQLOpen(); return 0; }
-4883990 0 By looking at your loops you don't seem that you are visiting any cell more than once. Wouldn't a simple if statement work here ?
if(Cells(i,j).Value = ',') Cells(i,j).Value = '.' Elsif(Cells(i,j).Value = '.') Cells(i,j).Value = ',') End
-39801975 0 One data.table way of indexing a column by number would be to convert to a column name , convert to an R symbol, and evaluate:
mydata[ , eval( as.symbol( names(mydata)[1] ) )] [1] "ID123" "ID22" "AAA" > grep("^ID", mydata[,eval(as.symbol(names(mydata)[1]))]) [1] 1 2 But this is not really an approved path to success because of the DT FAQ #1 as well as the fact that row numbers are not considered as valid targets. The philosophy (as I understand it) is that row numbers are accidental and you should be storing your records with unique identifiers.
-33453542 0If you are using AppCompatActivity then you can directly do the following in your main/parent activity.
int FEATURE_ACTION_BAR_OVERLAY: Flag for requesting an Action Bar that overlays window content.
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); supportRequestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY); setContentView(yourview) } And make sure you do not set any background for the action bar.
Using supportRequestWindowFeature is a convenience for calling getWindow().requestFeature().
Mads, that did just the trick! Thank you so much, I knew there was a very simple solution that I just wasn't seeing. Here is the magical line that converts an XML string to JSON:
String ret = XML.toJSONObject(aStringOfXml).toString();
-17490647 0 Why not simple:
.a { color: red; } .b { color: blue; } .c { color: yellow; } The difference between those two is that first one covers all six types:
.one .a, .one .b, .one .c, .two .a, .two .b, .two .c While the second one only covers 4:
.one .a, .one .b, .two .a, .two .c With respect to your markup - no difference at all, except that the very first case (without .one and .two) will be sliiiiiightly faster.
Also, see this.
-7043639 0 Operator 'op ' cannot be applied to operands of type 'dynamic' and 'lambda expression'I can't seem to apply binary operations to lambda expressions, delegates and method groups.
dynamic MyObject = new MyDynamicClass(); MyObject >>= () => 1 + 1; The second line gives me error: Operator '>>=' cannot be applied to operands of type 'dynamic' and 'lambda expression'
Why?
Isn't the operator functionality determined by my custom TryBinaryOperation override?
You can use Object instant of StudentUnion. Object will accept all classes.
public class CommonComparator implements Comparator<Object> { public int compare(Object s1, Object s2){ .... return result // 1 or 0; } }
-12521983 0 JS Validation if dropdown value selected or not I am trying to write a validation block inside my JS to check if the user has selected a value or not and pop up a message if the value is not selected.
function validate(form) { var success = true; var message = ""; if (form.dropdown.selectedIndex == 0 ) { form.save.disabled=true; if (0 < message.length) { message += "\n"; } message += "dropdown value should be selected."; } if (0 < message.length) { alert(message); success = false; } return success; } When I click on Save button I call this function. I don't see errors in the logs. Can anyone tell me what am I doing wrongly here? Or can you guide me what is the correct method to validate if the user has selected a value before allowing to save?
Thanks!
-23574165 0Putting @j08291's comment into an answer.
You can only have one element with an ID. Change them to classes, and you'll need to do some tree traversing to get the reference to the correct form elements to show and hide http://jsfiddle.net/pcUBr/
Also, your CSS class names (show,hide) aren't very semantic. Try the following
CSS
.question_form { display: none; } .question_form.current { display: inline; } JS
$(".button").click(function(e){ var form = $(e.target).closest('form'); form.toggleClass("current"); form.next().toggleClass("current"); }); HTML
<form class="question_form current" > <img src="image1.png" class="current_image" alt=""> <h3 class="question"> Question 1: </h3> <hr> <input type="radio" name="q1" value="q1-a">Answer 1 <br> <input type="radio" name="q1" value="q1-b">Answer 2 <br> <input type="radio" name="q1" value="q1-c">Answer 3 <br> <br> <input name="button" type="button" class="button" value="Next"> </form>
-2999048 0 I would use php personally. Then you can save which page layout you chose for them as a session var making it easy to load that layout on each page refresh. You would probably also want to save into the database with their username (if they login) and if they visit later show them the same layout.
-25546664 0You can use JQuery to toggle Menu http://jsfiddle.net/bLbdavqu/8/
Just Change the CSS of the ul.
Hide List- $( "#mylist" ).css("display","none");
Show List- $( "#mylist" ).css("display","block");
I have created a component with TFrame as ancestor with the following code:
type TCHAdvFrame = class(TFrame) private { Private declarations } FOnShow : TNotifyEvent; FOnCreate : TNotifyEvent; protected procedure CMShowingChanged(var M: TMessage); message CM_SHOWINGCHANGED; public { Public declarations } constructor Create(AOwner: TComponent) ; override; published property OnShow : TNotifyEvent read FOnShow write FOnShow; property OnCreate : TNotifyEvent read FOnCreate write FOnCreate; end; implementation {$R *.dfm} { TCHAdvFrame } procedure TCHAdvFrame.CMShowingChanged(var M: TMessage); begin inherited; if Assigned(OnShow) then begin ShowMessage('onShow'); OnShow(self); end; end; constructor TCHAdvFrame.Create(AOwner: TComponent); begin ShowMessage('OnCreate1'); inherited ; ShowMessage('OnCreate2'); if Assigned(OnCreate) then begin ShowMessage('OnCreate3'); OnCreate(self); end; I have registered the new component and did some tests. ShowMessage('OnCreate1'); and ShowMessage('OnCreate2'); are correctly executed but not ShowMessage('OnCreate3');
This prevents to add code during the implementation of a new instance of TCHAdvFrame.
Why is it and how can I solve this ?
-23489606 0If you want Monster1 image to come from the array kanaCharacters with the index number from imageDisplay wouldn't you do this?
NSArray *array = [NSArray arrayWithObjects:@"a",@"b",@"c", nil]; //Setup array int imageDisplay = arc4random_uniform([array count]); //Find random int from array count UIImageView *monster1 = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 100, 50)]; //Setup UIImageView monster1.image = [UIImage imageNamed:array[imageDisplay]]; //Display image which is randomly selected from array [self.view addSubview:monster1]; //Add image to view
-22127764 0 in you initializers try doing something like this
#config/initializers/devise.rb #provider1 config.omniauth :facebook, ENV['FACEBOOK_APP_ID'], ENV['FACEBOOK_SECRET'], :site => 'https://graph.facebook.com/', :authorize_path => '/oauth/authorize', :access_token_path => '/oauth/access_token', :scope => 'email, user_birthday, read_stream, read_friendlists, read_insights, read_mailbox, read_requests, xmpp_login, user_online_presence, friends_online_presence, ads_management, create_event, manage_friendlists, manage_notifications, publish_actions, publish_stream, rsvp_event, user_about_me, user_activities, user_birthday, user_checkins, user_education_history, user_events, user_groups, user_hometown, user_interests, user_likes, user_location, user_notes, user_photos, user_questions, user_relationships, user_relationship_details, user_religion_politics, user_status, user_subscriptions, user_videos, user_website, user_work_history' #provider2 config.omniauth :twitter, ENV['TWITTER_KEY'], ENV['TWITTER_SECRET'], :scope => { :secure_image_url => 'true', :image_size => 'original', :authorize_params => { :force_login => 'true' } } #provider3 config.omniauth :google_oauth2, ENV["GOOGLE_KEY"], ENV["GOOGLE_SECRET"]
-27641942 0 This turned out to be a permissions issue on the updated html file. Went to file info and adjusted permissions to match the original html file and it worked.
-35970550 0Try the regex bellow (^|\s)([#][a-zA-Z\d-]+)
Working regex example:
https://regex101.com/r/kJ2qR3/2
-11515001 0 Android CookieSyncManagerAre the cookies kept persistent when we use this? Are the cookies still available even after the phone restarts? I am referring to this link: http://developer.android.com/reference/android/webkit/CookieSyncManager.html
Say we are using DefaultHttpClient, CookieSyncManager would know to grab the cookies or are there other commands then the ones in the link that we will still need to provoke? How do we get the cookies back?
-35399002 0The way you handle the cookies appears to be correct. In terms of the shopping cart you can simply JSON.stringify it.
To save the cart:
$cookies.put("shoppingCart", JSON.stringify($scope.shopping_cart)); To retrieve the cart:
var cartCookie = $cookies.get("shoppingCart"); if (cartCookie) { cartCookie = JSON.parse(cartCookie); }
-25469326 1 Delete "usr/lib/python2.7" byMistake, how to fix it? During editting the Django apps, I deleted the python2.7 folder in "usr/lib/python2.7" by mistake.
After that problem happened, I always got the msg as following when using :
Could not find platform independent libraries <prefix> Could not find platform dependent libraries <exec_prefix> Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>] ImportError: No module named site
--- os is Ubuntu12.04 ----
I have tried to refer to these pages:
and also try to use
sudo apt-get install --reinstall to reinstall the python2.7.8 version
My PYTHONPATH now looks like
PYTHONDIR= usr/local/lib/python2.7,
PYTHONHOME= usr/local/lib/python2.7,
PYTHONPATH=
but I still get "ImportError: No module named site" msg
If I try to type
Import sys I would get the msg "import: unable to open image `sys': @ error/blob.c/OpenBlob/2587."
Many thanks,
-14390146 0You can ask your NSManagedObjectModel by sending versionIdentifiers to the receiver.
- (NSSet *)versionIdentifiers The docu is here
-34136291 0This error was caused by an error with the user permissions for sysadmin.
Adding “NT AUTHORITY\NETWORK SERVICE” as sysadmin in the SQL server instance resolved the issues.
-40078892 0 I am showing aspx page(Add Item form) inside jquery modal, whenever I upload an image the page refreshes and loads as a normal webpageI have 2 files :-
code Inside Items.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Basic.Master" AutoEventWireup="true" CodeBehind="Items.aspx.cs" Inherits="FlowerShopAdminPanel.Items" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="header" runat="server"> <div id="dvGrid" class="container"> <!-- This contains the gridview --> </div> <div id="testing"></div> <script> function openDialog($itemid,$categoryid) { $('#testing').dialog({ modal: true, dialogClass: "no-close", open: function () { $(this).load('AddItem.aspx?itemid=' + $itemid+'&categoryid='+$categoryid); $(".ui-dialog-titlebar-close", ui.dialog | ui).hide(); }, height: 500, width: 500, title: 'Add Item' }); } </script> <style> .image { height: 30vh; } .no-close .ui-dialog-titlebar-close { display: none; } </style> </asp:Content> This loads a form to add item in a jquery modal. we can upload image to that item using a Button . Above function is on another aspx form in which I am
AddItem.aspx
<div> <asp:Label runat="server" Text="Category Name"></asp:Label> <asp:DropDownList runat="server" ID="category_ddl"></asp:DropDownList> </div> <div> <asp:Label runat="server" Text="Item Name"> </asp:Label> <asp:TextBox runat="server" ID="itemname_txt"></asp:TextBox> </div> <div> <asp:Label runat="server" Text="Description"></asp:Label> <asp:TextBox runat="server" TextMode="MultiLine" Rows="5" Columns="50" ID="description_txt"></asp:TextBox> </div> <div> <asp:Label runat="server" Text="Main Image"></asp:Label> <asp:FileUpload runat="server" ID="mainimage_fileupload"/><br /> <asp:Image runat="server" ID="mainimage_img" Visible="false" /> <asp:Button runat="server" ID="fileupload_btn" Text="Upload" OnClick="fileupload_btn_Click" /> <asp:Label runat="server" ID="filename_lbl" Visible="false" ForeColor="Red" Font-Bold="true"></asp:Label> </div> <div> <asp:Label runat="server" Text="Active"> </asp:Label> <asp:CheckBox runat="server" ID="isActive_chk"/> </div> <div> <asp:Button runat="server" ID="addItem_btn" Text="Add Item" OnClick="addItem_btn_Click"/> <asp:Button runat="server" ID="cancel_btn" Text="Cancel" OnClick="cancel_btn_Click"/> </div> </div> </form>
Whenever I upload the image it opens up as a normal aspx page. Basically, Whenever the aspx page is refreshed, it opens up as a normal web page. I always want to open it in the jQuery modal.
Please help in resolving this issue.
Thank you
-36777974 0 android - viewpager OutOfMemoryErrorI have a problem. I want to get image URL from JSON and setting to viewpager. I tried it with drawable folder, but large images are causing problems. If the image would be small, then I would not have a problem. How can I get large images? I benefited from this article : enter link description here
GalleryActivity
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gallery); ViewPager viewPager = (ViewPager)findViewById(R.id.viewpa); GalleryAdapter ga = new GalleryAdapter(this); viewPager.setAdapter(ga); } Gallery Adapter (extending PagerAdapter)
Context context; private int[] GalImages = new int[] { R.drawable.one, R.drawable.two, R.drawable.three }; GalleryAdapter(Context context){ this.context=context; } @Override public int getCount() { return GalImages.length; } @Override public boolean isViewFromObject(View view, Object object) { return view == ((ImageView) object); } @Override public Object instantiateItem(ViewGroup container, int position) { ImageView imageView = new ImageView(context); int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_medium); imageView.setPadding(padding, padding, padding, padding); imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE); imageView.setImageResource(GalImages[position]);// error on this line when large image ((ViewPager) container).addView(imageView, 0); return imageView; } @Override public void destroyItem(ViewGroup container, int position, Object object) { ((ViewPager) container).removeView((ImageView) object); } And logcat outputs
java.lang.OutOfMemoryError at android.graphics.BitmapFactory ...
-34857027 0 How to Fit Image in CircleImage plugin of Xamarin.Forms I am using following code.
<StackLayout BackgroundColor="#303D43" HeightRequest="170" Padding="10" HorizontalOptions="Fill" VerticalOptions="Start"> <StackLayout HeightRequest="120" WidthRequest="120" Padding="0,0,0,10" HorizontalOptions="Fill" VerticalOptions="Fill" > <controls:CircleImage x:Name="profileImage" BorderColor="White" BorderThickness="1" HorizontalOptions="Center" Aspect="AspectFill" WidthRequest="96" HeightRequest="96" > </controls:CircleImage> </StackLayout> <Label x:Name="lblTitle" FontSize="22" TextColor="White" HeightRequest="20" HorizontalOptions="Center" /> </StackLayout> As you can see in case of portrait image , space left at left and right while in case of horizontal image space left at top and bottom. How to fix this. I have tried Aspect="AspectFill" AspectFit and Fill all three enums but no success..
using this Plugin
https://github.com/jamesmontemagno/Xamarin.Plugins/tree/master/ImageCircle
-20128267 0 C++ binary files and iterators: getting away with a 1:1 using ifstreambuf_iterator?This answer points out the fact that C++ is not well suited for the iteration over a binary file, but this is what I need right now, in short I need to operate on files in a "binary" way, yes all files are binary even the .txt ones, but I'm writing something that operates on image files, so I need to read files that are well structured, were the data is arranged in a specific way.
I would like to read the entire file in a data structure such as std::vector<T> so I can almost immediately close the file and work with the content in memory without caring about disk I/O anymore.
Right now, the best way to perform a complete iteration over a file according to the standard library is something along the lines of
std::ifstream ifs(filename, std::ios::binary); for (std::istreambuf_iterator<char, std::char_traits<char> > it(ifs.rdbuf()); it != std::istreambuf_iterator<char, std::char_traits<char> >(); it++) { // do something with *it; } ifs.close(); or use std::copy, but even with std::copy you are always using istreambuf iterators ( so if I understand the C++ documentation correctly, you are basically reading 1 byte at each call with the previous code ).
So the question is: how do I write a custom iterator ? from where I should inherit from ?
I assume that this is also important while writing a file to disk, and I assume that I could use the same iterator class for writing, if I'm wrong please feel free to correct me.
-24908293 0user=bob lastb $user -t $(date -d "$(last $user | head -n 1 | tr -s '[:space:]' '\t' | cut -f 4-7)" +%Y%m%d%H%M%S) More readably
user=bob last_login=$(last $user | head -n 1 | tr -s '[:space:]' '\t' | cut -f 4-7) datetime=$(date -d "$last_login" +%Y%m%d%H%M%S) lastb $user -t $datetime Note that my last output looks a little different from yours, with an extra field: adjust your cut columns accordingly
$ last glennj -n 1 glennj pts/7 :0 Sun Jul 20 19:01 still logged in wtmp begins Fri Jul 4 21:15:28 2014
-13413138 0 Like you said, after navigating away from original page you're losing track of what windows you may have opened.
As far as I can tell, there's no way to "regain" reference to that particular window. You may (using cookies, server side session or whatever) know that window was opened already, but you won't ever have a direct access to it from different page (even on the same domain). This kind of communication between already opened windows may be simulated with help of ajax and server side code, that would serve as agent when sharing some information between two windows. It's not an easy nor clean solution however.
-27031485 0The keydown event supports event bubbling, so you can just add the handler to the container element like
document.querySelectorAll('.container')[0].addEventListener('keydown', function(e) { console.log('keypressed', this, e); //e.target will refer to the actual event target log('down in `' + e.target.innerHTML + '` with keycode: ' + (e.keyCode)) }) function log(msg) { document.querySelector('#log').innerHTML = msg; } <div class='container'> <p tabindex="1">content</p> <p tabindex="1">in enough different elements</p> <p tabindex="1">that making listeners</p> <p tabindex="1">for all of them</p> <p tabindex="1">would be a huge pain</p> </div> <div id="log"></div> For example, the link below triggers something in jQuery but does not go to another page, I used this method a while back ago.
<a class="trigger" href="#"> Click Me </a> Notice theres a just a hash tag there, and usually causes the page to jump when clicked on, right? [I think]. It is only for interactive stuff, doesn't go to another page or anything else. I see a lot of developers do this.
I feel like its the wrong thing to do though. Is there another recommended way to do this without using HTML attributes a way where it is not suppose to be used?
Not using <button> ether because the link would not be a button.
Maybe without a hash?
<a class="trigger"> Click Me </a> & in CSS:
.trigger { cursor: pointer; } So the user still knows its for something that you should click?
-21148955 0Try this code:
# BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond %{THE_REQUEST} \s/+[?\s] RewriteRule /anmelden/ [L,R] RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress
-28585915 0 There are two plugins/listeners that will generate this directly within JMeter UI or write the files to results if you are doing distributed test. Both are from the Extras Set.
Response Times Percentiles
The test I am using is simple and the response time is in ms. Y-axis is milliseconds, and X-Axis is percentage of requests responding in that time.
Response Times Distribution Same concept except Y-Axis is number of requests responding in that bucket, X-Axis the response time in milliseconds. The size of the distribution is configurable.

Plugin installation is described here, it is as simple as copying files into your JMeter installation.
-25767683 0This is a shot in the dark, but try return false after the trigger reset and the alertify success stuff.
I am converting html into pdf. It is working fine. but when i try to save html into any location it gives me error Network path not found. I am having some line of code
#region Trying to convert pdf Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=Panel.pdf"); Response.Cache.SetCacheability(HttpCacheability.NoCache); StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); StringReader sr = new StringReader(htmlStringToConvert); iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 10f, 10f, 100f, 0f); HTMLWorker htmlparser = new HTMLWorker(pdfDoc); PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream); pdfDoc.Open(); htmlparser.Parse(sr); pdfDoc.Close(); Response.Write(pdfDoc); Response.End(); #endregion I am getting error at htmlparser.Parse(sr).
Thanks in advance
-14966810 0Provided that PreCalcCurrentMonth is a Date variable, try something like this (untested):
mySQL = "DELETE * FROM [tblBillingData]" & _ "WHERE (((tblBillingData.[Billing Month]) > " & _ Format(PreCalcCurrentMonth,"\#mm\/dd\/yyyy\#") & _ "));" DoCmd.RunSQL mySQL Format(PreCalcCurrentMonth,"\#mm\/dd\/yyyy\#") ensures that your date is converted to a string in US date format #mm/dd/yyyy#, whatever your regional settings. # is the date separator.
Instead of %ProgramFiles%, isn't there a %Programfiles(x86)% that always goes where you want, regardless of which cmd.exe is running? My XP-64 systems all have that; excuse me for not taking the time to boot up a Vista system.
I am trying establish a connection to my redshift database after following the example provided by AWS https://blogs.aws.amazon.com/bigdata/post/Tx1G8828SPGX3PK/Connecting-R-with-Amazon-Redshift. However, I get errors when trying to establish the connection using their recommended driver. However, when I use the Postgre driver I can establish a connection to the redshift DB.
AWS says their driver is "optimized for performance and memory management", so I would rather use it. Can someone please review my code below, and let me know if they see something wrong? I suspect that I am not setting the URL up correctly, but not sure what I should be using instead? Thanks in advance for any help.
#' This code attempts to establish a connection to redshift database. It #' attempts to establish a connection using the suggested redshift but doesn't #' work. ## Clear up space and set working directory #Clear Variables rm(list=ls(all=TRUE)) gc() ## Libriries for analyis library(RJDBC) library(RPostgreSQL) #Create DBI driver for working with redshift driver directly # download Amazon Redshift JDBC driver download.file('http://s3.amazonaws.com/redshift-downloads/drivers/RedshiftJDBC41-1.1.9.1009.jar', 'RedshiftJDBC41-1.1.9.1009.jar') # connect to Amazon Redshift using specific driver driver_redshift <- JDBC("com.amazon.redshift.jdbc41.Driver", "RedshiftJDBC41-1.1.9.1009.jar", identifier.quote="`") ## Using postgre connection that works #postgre driver driver_postgre <- dbDriver("PostgreSQL") #establish connection conn_postgre <- dbConnect(driver_postgre, host="nhdev.c6htwjfdocsl.us-west-2.redshift.amazonaws.com", port="5439",dbname="dev", user="xxxx", password="xxxx") #list the tables available tables = dbListTables(conn_postgre) ## Use URL option to establish connection like the example on AWS website # url <- "<JDBCURL>:<PORT>/<DBNAME>?user=<USER>&password=<PW> # url <- "jdbc:redshift://demo.ckffhmu2rolb.eu-west-1.redshift.amazonaws.com # :5439/demo?user=XXX&password=XXX" #useses example from AWS instructions #url using my redshift database url <- "jdbc:redshift://nhdev.c6htwjfdocsl.us-west-2.redshift.amazonaws.com :5439/dev?user=xxxx&password=xxxx" #attempt connect but gives an error conn_redshift <- dbConnect(driver_redshift, url) #gives the following error: # Error in .jcall(drv@jdrv, "Ljava/sql/Connection;", "connect", as.character(url)[1], : # java.sql.SQLException: Error message not found: CONN_GENERAL_ERR. Can't find bundle for base name com.amazon.redshift.core.messages, locale en ## Similier to postgre example that works but doesn't work when using redshift specific driver #gives an error saying url is missing, but I am not sure which url to use? conn <- dbConnect(driver_redshift, host="nhdev.c6htwjfdocsl.us-west-2.redshift.amazonaws.com", port="5439",dbname="dev", user="xxxx", password="xxxx") # gives the following error: #Error in .jcall("java/sql/DriverManager", "Ljava/sql/Connection;", "getConnection", : # argument "url" is missing, with no default
-1927735 0 Given that characters can take a variable number of bytes this would be pretty tough to do without converting the bytes to characters with a TextReader.
You could wrap up a TextReader and give it a Seek method that ensures enough characters have been loaded to satisfy each request.
The logical density of the display is given in the DisplayMetrics class, and can be retrieved with,
getResources().getDisplayMetrics().density Thus, to convert dp to px, you would do,
int density = getResources().getDisplayMetrics().density; int px = (int) (dp * density); To convert px to dp, just perform the inverse operation,
int dp = px/density;
-16287730 0 it appears that var is None in what you provided. Everything is correct, but var does not contain a string.
std::cin.ignore(100,'\n'); did the trick.
I have an ajax request that fetches some data and returns a html response that I print out on the page. The problem is that for some reason the html response doesn't get printed, only textual data does. The correct response is being returned as I've checked in the browser console.
Here is the ajax function:
function getRating(work_id, selectorToWriteTo) { $.ajax({ url: '/read/getRatingsForGivenWork', type: 'GET', dataType: 'html', async: true, data: { field1: work_id}, success: function (data) { //your success code $(selectorToWriteTo).html(data); }, error: function (xhr, ajaxOptions, thrownError) { alert("Error: " + thrownError); } }); } function that returns the html data:
public function getRatingsForGivenWork() { $ratings = $this->getModel ( 'read', 'getRatingsForGivenWork', $_GET['field1']); if($ratings !== null) { print "<div class=\"ui small star rating\" data-rating=\"" . $ratings ."\" data-max-rating=\"5\">Leave rating</div>"; } else { print 0; } } Where I invoke the ajax function:
<div class="extra"> <script> document.write(getRating(<?php echo $row['works.work_id']; ?>, '.extra')); </script> </div> Response in Chrome developer tools:

Chrome console:

The right response comes back but it doesn't print the html on the page. Anyone know why this is?
-1060848 0A slightly cleaner format of the above:
private void amount_PaidTextBox_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = !(Char.IsNumber(e.KeyChar) || (e.KeyChar==Keys.Back)); }
-27787123 0 I think you have a problem with quotes in your statement text. Look at this excerpt based on your code when I tested in the Immediate window:
intYear = 2015 ? "WHERE [Market Segment]= 'CMS Part D (CY ' & (intYear) & ')'" WHERE [Market Segment]= 'CMS Part D (CY ' & (intYear) & ')' That can't be right. And when Access tries to execute the query and sees intYear, it interprets that to be a parameter because the db engine knows nothing about a VBA variable named intYear.
I think it should look like this:
? "WHERE [Market Segment]= 'CMS Part D (CY " & (intYear) & ")'" WHERE [Market Segment]= 'CMS Part D (CY 2015)' I encourage you to follow KevenDenen's advice to add Debug.Print strCount2 to the code after it has finished building the strCount2 string. Then you can run the code and view the text of the completed statement in the Immediate window. (You can use Ctrl+g to go to the Immediate window.) It helps tremendously to examine the actual statement your code is asking Access to execute.
No, this is not possible. There is no API to programatically set the user's alarm.
However, you can invoke the clock application to a specific view-state (alarm screen) and allow the user to set the alarm themselves.
Here's how to invoke an app: https://developer.blackberry.com/native/documentation/cascades/device_platform/invocation/sending_invocation.html
Here's the info on how to invoke the alarm clock: https://developer.blackberry.com/native/documentation/cascades/device_platform/invocation/clock.html
-2986624 0Correct, it's still not kosher. It will cause warnings in many browsers about "mixing secure and insecure content."
-28095927 0Concatenate string properly:
Replace this:
var newImage = "<img src='https://api.twilio.com" + data + "/>"; // you're missing to close quote for src here ^^ With this:
var newImage = "<img src='https://api.twilio.com" + data + "' />"; Or switch the quotes:
var newImage = '<img src="https://api.twilio.com' + data + '" />';
-2543904 0 drscheme c# adapter Hi guys i need to integrate drscheme into my c# code for my assignment but i could find any luck on the web. Can anyone help me ? I tried ironscheme but got the following error.
The type or namespace name 'Dynamic' does not exist in the namespace 'System' (are you missing an assembly reference?) C:\Documents and Settings\Administrator\My Documents\Visual Studio 2008\Projects\Integration\Integration\Form1.cs 2 14 Integration
Have tried googling the error message but could find any related stuff.
-1065148 0Rihan is partially correct...
In your Project Property page, Web tab: Enable Edit and Continue
If checked - The Development server will close when the app (not VS) stops.
If unchecked - Development server keeps running
-4901643 0 Animate max-width on img [JQuery]I have tried looking for a solution, but can't find anything good.
I am customizing a blog for a friend of mine. When it loads, I want all the img's in each post to have a max-width and max-height of 150px. When the user pushes the img, the max-values should increase to 500px, which is easy enough. The problem with my code is that I can't get an animation on it, which I want. Any help out there?
var cssObj = {'max-width' : '500px','max-height' : '500px;'} $("img").click(function(){ $(this).css(cssObj); });
-23700348 0 I've created an overly complex solution that allows you to create a helper function to do an inline type of rang value finder. The ranger function takes the cut points you want to split on and then returns a function that will choose the value of the parameter based on which interval it falls. It primarily uses findInterval but unfortunately you inequalities don't exactly line up with how findInterval likes to do them so I had to do some fiddling.
#meta-helper function ranger<-function(rng) { function(x, ...) { dots<-list(...) stopifnot(ncol(dots)==length(rng)+1) m<-findInterval(x, rng)+1 ex<-match(x, rng); if (any(!is.na(ex))) { m[which(ex>1)]<-ex[which(ex>1)] } out<-rep(NA, length(x)) for(i in seq_along(dots)) { out[m==i]<-rep(dots[[i]], length.out=length(x))[m==i] } out; } } #helper function abc<-ranger(c(600,4000)) #implementation 1 x<-c(100,2000,5000) a<-abc(x, 0.01, 0.1, 0.12)*x + abc(x, 0, 118, -162); a; #implementation 2 a<-abc(x, x * 0.01, 118 + (x*0.1), 318 + ((x-4000)*0.12)); a; So while it may not be the best choice in this case, i might be useful if you have a bunch of different ranges or something like that.
-17801465 0 Joomla 3 PHP errors when uploading files through the media managerWhenever I try to upload files I get a blank white screen with the following PHP error:
Notice: Undefined index: CONTENT_LENGTH in /administrator/components/com_media/controllers/file.php on line 61 Notice: Undefined index: CONTENT_LENGTH in /administrator/components/com_media/controllers/file.php on line 62 Notice: Undefined index: CONTENT_LENGTH in /administrator/components/com_media/controllers/file.php on line 63 Notice: Undefined index: CONTENT_LENGTH in /administrator/components/com_media/controllers/file.php on line 64 Warning: Invalid argument supplied for foreach() in /administrator/components/com_media/controllers/file.php on line 72 Warning: Invalid argument supplied for foreach() in /administrator/components/com_media/controllers/file.php on line 109
-930932 0 Returning different data type depending on the data (C++) Is there anyway to do something like this?
(correct pointer datatype) returnPointer(void* ptr, int depth) { if(depth == 8) return (uint8*)ptr; else if (depth == 16) return (uint16*)ptr; else return (uint32*)ptr; } Thanks
-4411861 0You can include newlines in strings by explicitly specifying them:
<string name="hint">Manny, Moe and Jack\nThey know what I\'m after.</string> Newlines in the XML are treated as spaces.
-2013934 0 How to get assembly version of a project in a visual studio 2008 deployment projectI have a deployment project in visual studio 2008 that installs several C# projects. Among other things, I'd like it to write projects assembly version to registry.
Is there a way to automatically find out whats the projects assembly version (written in AssemblyInfo.cs) and write that as value of a registry property?
If not, is there any way to do this better than by hand? It is important that these values are correct because they are used by our updating software.
Thank you.
EDIT: I'm not sure I was completely clear in my question. I don't want to get this number and store it to a string. I want to write it to registry with Deployment Projects Registry Editor (not sure if that's the official name, you can get to it by right clicking the deployment project in solution explorer and navigating to View->Registry)
-14192908 0You can change offset and width of your toolbar, if you want to use customview (initWithCustomView)
[myToolBar setFrame:CGRectMake(-10, 0, [UIScreen mainScreen].bounds.size.width+10, 44)];
-3629215 0 The layer you are looking for is https. Just make sure the requests go over https if the data is sensitive.
-18966534 0Look at the SQL debug output, the regions are being retrieved using separate queries, that's how Cakes ORM currently works.
In your case there's a relatively simple workaround. Just create a proper association on the fly, for example Profile belongsTo Region.
Here's an (untested) example, it adds a belongsTo association with the foreignKey option set to false in order to disable the automatic foreign key generation by the ORM, this is necessary as it would otherwise look for something like Profile.region_id. Note that consequently the contain config has to be changed too!
$this->Profile->bindModel(array( 'belongsTo' => array( 'Region' => array( 'foreignKey' => false, 'conditions' => array('Region.id = Store.region_id') ), ) )); $this->Paginator->settings = array( 'conditions' => array('Profile.job_title_id' => '1'), 'contain' => array('Store', 'Region') ); That should generate a proper query that includes the stores as well as the regions table, making it possible to sort on Region.name. Note that the resulting array will be a little different, Region will not be nested in Store, everything will be placed in the same level, ie:
Array ( [Profile] => Array ( .... ) [Store] => Array ( .... ) [Region] => Array ( .... ) ) Either you modify your view code accordingly, or you transform the retrieved data before passing it to the view. A third option would be to include a nested Region in the contain config, however that would result in additional queries that are totally unnecessary as the data was already fetched with the main query, so I wouldn't recommend that.
try to tweak this
var subquery = DetachedCriteria.For<Event>() .Add(Restrictions.Eq("Success", true)) .Add(Restrictions.EqProperty("User.Id", "u.id")) .AddOrder(Order.Desc("TimeStamp")) .SetProjection(Projections.Property("EventType")) .SetMaxResults(1); session.CreateCriteria<User>("u") .Add(Restrictions.Ge("LastActivityTimeStamp", cutoff)) .Add(Subqueries.Ne(EventType.LogOff, subquery));
-26388576 0 Set the initial values for the select and radio inputs in the controller itself. E.g.
$scope.selectedCES = 'whatever' Note that you'll have to add an ng-model to your radio input too.
To validate when the input is required:
<select ... required="true"> ... </select> <input ... required="true"/> See the angular docs:
https://docs.angularjs.org/api/ng/directive/select
https://docs.angularjs.org/api/ng/directive/input
https://docs.angularjs.org/guide/forms
-15080607 0 Ember Object in path STRING could not be found or was destroyedI have a small application where I'm getting translations json for a locale and updating Ember.STRINGS. Am I doing something wrong?
$.get("http://localhost:8000/translations.json", {locale : locale}, function (data) { Ember.set('STRINGS', data) ; }); In 0.9.5 I was doing
Ember.STRINGS = data
; and it seemed to work. When I changed it to 1.0.0 a lot of things started crashing around. Both of these don't work.
-1812894 0Ember.STRINGS = data ; Ember.set('STRINGS', data) ;
Why do you want to know, what kind of database field you are using? Are you storing information from the form through raw sql? You should have some model, that you are storing information from the form and it will do all the work for you.
Maybe you could show some form code? Right now it's hard to determine, what exactly you are trying to do.
-24946289 0It's not ideal but I compare the page text against following regex since on my setup that text accompanies web page errors:
(?:(access is denied)|(access is forbidden)|(server error)|(not found))
-6932626 0 According to a similar discussion, you can create a UICONTROL pushbutton which has the advantage that it accepts HTML input string. Then using FINDJOBJ, we can fake the look of a clickable hyperlink:
fName = 'C:\path\to\file.pdf'; str = '<html><a href="">Click here for plot documentation</a></html>'; figure('Resize','off', 'MenuBar','none') imshow('coins.png') hButton = uicontrol('Style','pushbutton', 'Position',[320 50 170 20], ... 'String',str, 'Callback',@(o,e)open(fName)); jButton = findjobj(hButton); jButton.setCursor( java.awt.Cursor(java.awt.Cursor.HAND_CURSOR) ); jButton.setContentAreaFilled(0); 
If you want a designed select I'd suggest you use jQuery then find a good plugin for customizing select boxes, try Googling "jquery design select". Have never used a jQuery plugin for this but I know they exist.
Hope this helps!
-1265041 0 Is it necessary to know flash designing for flex3?I am from a programming background ,and newbie to flex3 . i would like to learn flex3 and develop some application using rails and flex3 . Is it necessary to know flash in order to learn flex3 or just learning Action script 3 would do ? .Can anybody tell what are the prerequisites to learn flex3 . Thanks in Advance.
-40810096 0 Adwords not displaying in android appI have added the code for displaying Adwords ad in my android app
MobileAds.initialize(getApplicationContext(),"ca-app-key"); AdView mAdView = (AdView) findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder() .build(); mAdView.loadAd(adRequest); After publishing my app in Android playstore and downloading it from there to check whether ads are appearing, i see no ads.I don't understand what is going wrong here.
-5668411 0Try BlendMode.LAYER, it saved many lives.
-260528 0Don't use the session!!! If the user opens a second tab with a different request the session will be reused and the results will not be the ones that he/she expects. You can use a combination of ViewState and Session but still measure how much you can handle without any sort of caching before you resort to caching.
-6780483 0As a lot of people have suggested, Resource Leaks are fairly easy to cause - like the JDBC examples. Actual Memory leaks are a bit harder - especially if you aren't relying on broken bits of the JVM to do it for you...
The ideas of creating objects that have a very large footprint and then not being able to access them aren't real memory leaks either. If nothing can access it then it will be garbage collected, and if something can access it then it's not a leak...
One way that used to work though - and I don't know if it still does - is to have a three-deep circular chain. As in Object A has a reference to Object B, Object B has a reference to Object C and Object C has a reference to Object A. The GC was clever enough to know that a two deep chain - as in A <--> B - can safely be collected if A and B aren't accessible by anything else, but couldn't handle the three-way chain...
-40567470 1 Split in python and strip whitespaceI am learning Python, and currently working on reading in a file, splitting the lines and then printing specific elements. I am having trouble splitting multiple times though. The file I am working on has many lines that look like this
c0_g1_i1|m.1 gi|74665200|sp|Q9HGP0.1|PVG4_SCHPO 100.00 372 0 0 1 372 1 372 0.0 754 I am trying to split it, first by tab and newline "/t/n", and then split the elements with |, I have tried .split and .strip and am not having much luck. I figured maybe if I just worked on a single line I could get the idea down, and then modify it into a loop that would access the file
blast_out = ("c0_g1_i1|m.1 gi|74665200|sp|Q9HGP0.1|PVG4_SCHPO 100.00 372 0 0 1 372 1 372 0.0 754") fields = blast_out.strip(' \t\r\n').split() subFields = fields.split("|") print(fields) print(subFields) print(fields)
['c0_g1_i1|m.1', 'gi|74665200|sp|Q9HGP0.1|PVG4_SCHPO', '100.00', '372', '0', '0', '1', '372', '1', '372', '0.0', '754'] print(subFields) generates an error
subFields = fields.split('|') AttributeError: 'list' object has no attribute 'split' This is what I did just to try to strip the whitespace and the tabs, then to split on | but it doesn't seem to do anything. Eventually my desired output from this single string would be
c0_g1_i1 m.1 Q9HGP0.1 100.0
-12569923 0 You may try this
var map, locations = [ [43.82846160000000000000, -79.53560419999997000000], [43.65162010000000000000, -79.73558579999997000000], [43.75846240000000000000, -79.22252100000003000000], [43.71773540000000000000, -79.74897190000002000000] ]; var myOptions = { zoom: 6, center: new google.maps.LatLng(locations[0][0], locations[0][1]), mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map($('#map')[0], myOptions); var infowindow = new google.maps.InfoWindow(), marker, i; for (i = 0; i < locations.length; i++) { marker = new google.maps.Marker({ position: new google.maps.LatLng(locations[i][0], locations[i][1]), map: map }); google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() { infowindow.setContent('Current location is: '+ locations[i][0]+', '+locations[i][1]); infowindow.open(map, marker); } })(marker, i)); } DEMO.
-8215683 0 How to inflate a expandable list in Android?i want to inflate a expandable list with some different text and different images on each row if i use albumCovers.get(i) instead of getResources().getDrawable(R.drawable.icon)then it throws an error, any one help us out? thanks ;p.
public class ExpandActivity extends ExpandableListActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Construct Expandable List final String NAME = "name"; final String IMAGE = "image"; final LayoutInflater layoutInflater = (LayoutInflater) this .getSystemService(Context.LAYOUT_INFLATER_SERVICE); final ArrayList<HashMap<String, String>> headerData = new ArrayList<HashMap<String, String>>(); final HashMap<String, String> group1 = new HashMap<String, String>(); group1.put(NAME, "Group 1"); headerData.add(group1); final ArrayList<ArrayList<HashMap<String, Object>>> childData = new ArrayList<ArrayList<HashMap<String, Object>>>(); final ArrayList<HashMap<String, Object>> group1data = new ArrayList<HashMap<String, Object>>(); childData.add(group1data); Resources res = this.getResources(); Drawable photo = (Drawable) res.getDrawable(R.drawable.icon); ArrayList<Drawable> albumCovers = new ArrayList<Drawable>(); albumCovers.add(photo); // Set up some sample data in both groups for (int i = 0; i < 10; ++i) { final HashMap<String, Object> map = new HashMap<String, Object>(); map.put(NAME, "Child " + i); map.put(IMAGE, getResources().getDrawable(R.drawable.icon)); (group1data).add(map); } setListAdapter(new SimpleExpandableListAdapter(this, headerData, android.R.layout.simple_expandable_list_item_1, new String[] { NAME }, // the name of the field data new int[] { android.R.id.text1 }, // the text field to populate // with the field data childData, 0, null, new int[] {}) { @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { final View v = super.getChildView(groupPosition, childPosition, isLastChild, convertView, parent); // Populate your custom view here ((TextView) v.findViewById(R.id.name)) .setText((String) ((Map<String, Object>) getChild( groupPosition, childPosition)).get(NAME)); ((ImageView) v.findViewById(R.id.image)) .setImageDrawable((Drawable) ((Map<String, Object>) getChild( groupPosition, childPosition)).get(IMAGE)); return v; } @Override public View newChildView(boolean isLastChild, ViewGroup parent) { return layoutInflater.inflate( R.layout.expandable_list_item_with_image, null, false); } }); } }
-26455109 0 Thank you for giving you time to answer me Alex D with some information :) It was to long to comment to your answer.
I´m understanding most of those instruction does. I know now that cmp is the big part that I have to watch for.
I think I know some about call stack.
I should know how if else and for in C are translated into assembly.
I´ve been watching in gdb using stepping how it goes through the loops (jumps) and have got to 5 jumps now and stop at the 6th one so I think I´m getting closer.
Think it´s EAX if I´m watching gdb, it´s getting higher with stepping.
Don´t think I could tell that.
Thank you again for giving time to comment back, think it will be much easier when the lights turn on in my head :)
-30324222 0actually the solution is to use custom listviews
http://javatechig.com/xamarin/listview-example-in-xamarin-android
-39417474 0Instead of release() and create() the mediaplayer object every time user clicks the button, try to create() only once. Then inside of onClick(), try seekTo(0) to rewind from the beginning of the media file, then call start() to play again.
-6017219 0Roughly, Magento is creating an order collection for you and attempting to load all the records. This collection has a rule that only allows it to create one order object for each ID, so when your additional object is loaded an exception is thrown.
The left joins could be the issue, but it's hard to say off the bat. Could you post a little detail on how you are making the API call? An incorrect join can often have this problem.
EDIT:
If you're using the default code, my first guess would be that there are erroneous records in the database, or that this is an upgraded Magento system which had a bad upgrade in the past. Try this on a clean copy of your EE version pointing to the same database. If the same problem occurs, you may need to spelunk in the database looking for the reason for the problematic data load. Since you already have the query, you may want to separate out parts of the query to see if some subquery is returning too much data.
-2439684 0Without CTEs you can do:
Select Z.Department, Z.AvgWage From ( Select Department, Avg(Wage) AvgWage From Employees Group By Department ) As Z Where AvgWage = ( Select Max(Z1.AvgWage) From ( Select Department, Avg(Wage) AvgWage From Employees Group By Department ) Z1 ) With CTEs you could do:
With AvgWages As ( Select Department , Avg(Wage) AvgWage , Rank() Over( Order By Avg(Wage) Desc ) WageRank From Employees Group By Department ) Select Department, AvgWage, WageRank From AvgWages Where WageRank = 1
-4118798 0 I know you said there's no dangling extern "C"... But why would that even be an issue given how you are compiling with gcc and not g++??? (Which will, in fact, happily treat smsdk_ext.cpp as a C and NOT C++ file... With all the errors and pain that come from doing so...)
Often you will see such error messages when the wrong include files are tagged extern "C". (Or not properly tagged as the case may be.)
Your error messages also indicate difficulty overloading functions...
platform.h: In function ‘double fsel(double, double, double)’: platform.h:470: error: declaration of C function 'double fsel(double, double, double)' conflicts with platform.h:466: error: previous declaration 'float fsel(float, float, float)' And problems with system (compiler) files.
In file included from /usr/include/sys/signal.h:104, from /usr/include/signal.h:5, from /usr/include/pthread.h:15, from /cygdrive/... /usr/include/cygwin/signal.h:74: error: expected ‘;’ before ‘*’ token /usr/include/cygwin/signal.h:97: error: ‘uid_t’ does not name a type In file included from /usr/include/signal.h:5, from /usr/include/pthread.h:15, from /cygdrive/... /usr/include/sys/signal.h:163: error: ‘pthread_t’ was not declared in this scope /usr/include/sys/signal.h:163: error: expected primary-expression before ‘int’ /usr/include/sys/signal.h:163: error: initializer expression list treated as compound expression So either your compiler installation is really munged OR...
Alternatively, another approach is to start with a minimal Hello World program and see if that compiles. Then build up, including what you need to, until you hit a problem. (Or take the existing software and simplify it down until you find the problem area. Start with one "g++" line, copy the file, and pare it down until the problem goes away. Perhaps you have a #define or typedef that conflicts with something in a system file.)
-8724719 0 Group Multiple Tables in LINQI have a very simple SQL query
Select r.SpaceID,Count(*), SpaceCode from Rider r join Spaces s on r.SpaceID=s.SpaceID Group By r.SpaceID, s.SpaceCode Please note that my group by clause is on multiple tables, i want to do the same in linq, i know how to group single table, but about multiple tables i have no idea.
-19730151 0 Unable to retrieve videos from youtube with youtube-apiI'm developing a GWT application witch reads and displays videos from youtube. With that purpose in mind I started using gwt-youtube-api.
I can display a player and play the video from youtube accordingly but I'm unable to search videos on youtube.
The following code should retrieve the most recent videos from youtube, but it doesn't do anything. After making RPC call I can't see any results for both onSucess and onFailure:
import java.util.List; import com.google.gdata.client.youtube.YouTubeManager; import com.google.gdata.data.youtube.VideoEntry; import com.google.gdata.data.youtube.VideoFeed; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.rpc.AsyncCallback; public class Webmetalmore implements EntryPoint { @Override public void onModuleLoad() { YouTubeManager youTubeManager = new YouTubeManager(); youTubeManager.retrieveMostRecent(new AsyncCallback<VideoFeed>() { @Override public void onSuccess(VideoFeed result) { List<VideoEntry> entries = result.getEntries(); for (VideoEntry entry: entries){ System.out.println(entry.getTitle()); } } @Override public void onFailure(Throwable caught) { GWT.log("Unable to obtain videos from youtube service", caught); } }); } } Any ideas of what I'm doing wrong? Thank you
-15398954 0 Something wrong either with lParam or with WCHAR[]First, this function is called many times. It should be noted that wString[] does contain the character constant '\n'.
void D2DResources::PutToLog(WCHAR wString[]) { int strLen=wcslen(wString); int logLen=wcslen(log); if(strLen+logLen>=MaxLogSize) wcsncpy(log, log, logLen-strLen); wcscat (log, wString); int nLines=0; for(int x=0; x<wcslen(log); x++) { if(log[x]=='\n') { nLines++; if(nLines>5) { log[x]='\0'; } } } SendMessage (m_hWnd, WM_PAINT, NULL, (LPARAM)nLines); } At the end, a WM_PAINT message is sent while nLines should be non-zero since log contains multiples '\n'. My WndProc receives the message and processes it.
case WM_PAINT: { pD2DResources->OnRender((int)lParam); ValidateRect(hWnd, NULL); } break; After which OnRender is called with a (supposedly) non-zero int as an lParam.
void D2DResources::OnRender(int nLogLines) { D2D1_SIZE_F screenSize = pCurrentScreen->GetSize(); D2D1_SIZE_F rTSize = pRT->GetSize(); pRT->BeginDraw(); pRT->DrawBitmap( pCurrentScreen, D2D1::RectF(0.0f, 0.0f, screenSize.width, screenSize.height) ); pRT->DrawText( log, ARRAYSIZE(log) - 1, pTextFormat, D2D1::RectF(0, rTSize.height - ((nLogLines*textSize)+textSize) , rTSize.width, rTSize.height), pWhiteBrush ); pRT->EndDraw(); } For some reason, in the OnRender function, nLogLines' value is 0. What is wrong?
-9229310 0 How to attach the UIProgressView with the HTTPRequest processMy purpose is to show a nice UIProgressView that display the progress of the HTTPRequest to the user (loading). It seems everything is okay, however my UIProgressView well configured and setup in interface builder doesn't show the progress of the request, it doesn't even appear on the screen. Here is my relevant code:
// Start request //..... //Specify the address of the webservice (url) NSURL *url = [NSURL URLWithString:@"http://xxx.xxxxxx.com/xxxxxx/webservices/"]; ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url]; NSString *jsonStringArray=[aMutableArray JSONRepresentation]; [request setPostValue:jsonStringArray forKey:@"liste_des_themes"]; [request setDelegate:self]; [request setUploadProgressDelegate:progress];//when i remove this line, the ProgressVie appear, although not working :( [request startSynchronous]; My UIProgressView is named progress, does anybody know how to make the UIProgressView interact with the HTTPRequest Request? thanx in advance.
A widget is usually a small application with limited functionality. It usually, not always, will have one specific purpose. An app is much broader and is short for application which can encompass any number of things.
-31475613 0Use focus and simplify your css a little to something like this if possible:
.sky-form-orange input:focus { background-color: #f5b093 !important; } <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=10"> <title>Blog – Magma Machine - Graphic and Digital Design</title> <link rel="profile" href="http://gmpg.org/xfn/11"> <link rel="pingback" href="http://www.magmamachine.co.uk/xmlrpc.php"> <script type="text/javascript">document.documentElement.className = document.documentElement.className + ' yes-js js_active js'</script> <style> .wishlist_table .add_to_cart, a.add_to_wishlist.button.alt { border-radius: 16px; -moz-border-radius: 16px; -webkit-border-radius: 16px; } </style> <script type="text/javascript"> var yith_wcwl_plugin_ajax_web_url = 'http://www.magmamachine.co.uk/wp-admin/admin-ajax.php'; </script> <link rel="alternate" type="application/rss+xml" title="Magma Machine » Feed" href="http://www.magmamachine.co.uk/feed/"> <link rel="alternate" type="application/rss+xml" title="Magma Machine » Comments Feed" href="http://www.magmamachine.co.uk/comments/feed/"> <script type="text/javascript"> window._wpemojiSettings = {"baseUrl":"http:\/\/s.w.org\/images\/core\/emoji\/72x72\/","ext":".png","source":{"concatemoji":"http:\/\/www.magmamachine.co.uk\/wp-includes\/js\/wp-emoji-release.min.js?ver=4.2.2"}}; !function(a,b,c){function d(a){var c=b.createElement("canvas"),d=c.getContext&&c.getContext("2d");return d&&d.fillText?(d.textBaseline="top",d.font="600 32px Arial","flag"===a?(d.fillText(String.fromCharCode(55356,56812,55356,56807),0,0),c.toDataURL().length>3e3):(d.fillText(String.fromCharCode(55357,56835),0,0),0!==d.getImageData(16,16,1,1).data[0])):!1}function e(a){var c=b.createElement("script");c.src=a,c.type="text/javascript",b.getElementsByTagName("head")[0].appendChild(c)}var f,g;c.supports={simple:d("simple"),flag:d("flag")},c.DOMReady=!1,c.readyCallback=function(){c.DOMReady=!0},c.supports.simple&&c.supports.flag||(g=function(){c.readyCallback()},b.addEventListener?(b.addEventListener("DOMContentLoaded",g,!1),a.addEventListener("load",g,!1)):(a.attachEvent("onload",g),b.attachEvent("onreadystatechange",function(){"complete"===b.readyState&&c.readyCallback()})),f=c.source||{},f.concatemoji?e(f.concatemoji):f.wpemoji&&f.twemoji&&(e(f.twemoji),e(f.wpemoji)))}(window,document,window._wpemojiSettings); </script><script src="http://www.magmamachine.co.uk/wp-includes/js/wp-emoji-release.min.js?ver=4.2.2" type="text/javascript"></script> <style type="text/css"> img.wp-smiley, img.emoji { display: inline !important; border: none !important; box-shadow: none !important; height: 1em !important; width: 1em !important; margin: 0 .07em !important; vertical-align: -0.1em !important; background: none !important; padding: 0 !important; } </style> <link rel="stylesheet" id="mmpm_mega_main_menu-css" href="http://www.magmamachine.co.uk/wp-content/plugins/mega_main_menu/src/css/cache.skin.css?ver=4.2.2" type="text/css" media="all"> <link rel="stylesheet" id="chimpy-css" href="http://www.magmamachine.co.uk/wp-content/plugins/chimpy/assets/css/style-frontend.css?ver=2.1.3" type="text/css" media="all"> <link rel="stylesheet" id="chimpy-font-awesome-css" href="http://www.magmamachine.co.uk/wp-content/plugins/chimpy/assets/css/font-awesome/css/font-awesome.min.css?ver=4.0.3" type="text/css" media="all"> <link rel="stylesheet" id="chimpy-sky-forms-style-css" href="http://www.magmamachine.co.uk/wp-content/plugins/chimpy/assets/forms/css/sky-forms.css?ver=2.1.3" type="text/css" media="all"> <link rel="stylesheet" id="chimpy-sky-forms-color-schemes-css" href="http://www.magmamachine.co.uk/wp-content/plugins/chimpy/assets/forms/css/sky-forms-color-schemes.css?ver=2.1.3" type="text/css" media="all"> <link rel="stylesheet" id="sb_instagram_styles-css" href="http://www.magmamachine.co.uk/wp-content/plugins/instagram-feed/css/sb-instagram.css?ver=1.3.7" type="text/css" media="all"> <link rel="stylesheet" id="sb_instagram_icons-css" href="//netdna.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css?1&ver=4.2.0" type="text/css" media="all"> <link rel="stylesheet" id="rs-plugin-settings-css" href="http://www.magmamachine.co.uk/wp-content/plugins/revslider/rs-plugin/css/settings.css?ver=4.6.5" type="text/css" media="all"> <style id="rs-plugin-settings-inline-css" type="text/css"> .tp-caption a{color:#ff7302;text-shadow:none;-webkit-transition:all 0.2s ease-out;-moz-transition:all 0.2s ease-out;-o-transition:all 0.2s ease-out;-ms-transition:all 0.2s ease-out}.tp-caption a:hover{color:#ffa902} </style> <link rel="stylesheet" id="woocommerce_prettyPhoto_css-css" href="//www.magmamachine.co.uk/wp-content/plugins/woocommerce/assets/css/prettyPhoto.css?ver=4.2.2" type="text/css" media="all"> <link rel="stylesheet" id="jquery-selectBox-css" href="http://www.magmamachine.co.uk/wp-content/plugins/yith-woocommerce-wishlist/assets/css/jquery.selectBox.css?ver=4.2.2" type="text/css" media="all"> <link rel="stylesheet" id="yith-wcwl-main-css" href="http://www.magmamachine.co.uk/wp-content/plugins/yith-woocommerce-wishlist/assets/css/style.css?ver=4.2.2" type="text/css" media="all"> <link rel="stylesheet" id="yith-wcwl-font-awesome-css" href="http://www.magmamachine.co.uk/wp-content/plugins/yith-woocommerce-wishlist/assets/css/font-awesome.min.css?ver=4.2.2" type="text/css" media="all"> <link rel="stylesheet" id="js_composer_front-css" href="http://www.magmamachine.co.uk/wp-content/plugins/js_composer/assets/css/js_composer.css?ver=4.5.3" type="text/css" media="all"> <link rel="stylesheet" id="magnific-popup-css" href="http://www.magmamachine.co.uk/wp-content/plugins/elite-addons-vc/assets/libs/magnific-popup/magnific-popup.min.css?ver=0.9.9" type="text/css" media="all"> <link rel="stylesheet" id="iv-oswald-webfont-css" href="http://fonts.googleapis.com/css?family=Oswald%3A400%2C700&ver=1" type="text/css" media="all"> <link rel="stylesheet" id="iv-roboto-cond-webfont-css" href="http://fonts.googleapis.com/css?family=Roboto+Condensed%3A400%2C700&ver=1" type="text/css" media="all"> <link rel="stylesheet" id="ivan-font-awesome-css" href="http://www.magmamachine.co.uk/wp-content/themes/october/css/libs/font-awesome-css/font-awesome.min.css?ver=4.1.0" type="text/css" media="all"> <link rel="stylesheet" id="ivan-elegant-icons-css" href="http://www.magmamachine.co.uk/wp-content/themes/october/css/libs/elegant-icons/elegant-icons.min.css?ver=1.0" type="text/css" media="all"> <link rel="stylesheet" id="ivan_owl_carousel-css" href="http://www.magmamachine.co.uk/wp-content/themes/october/css/libs/owl-carousel/owl.carousel.min.css?ver=4.2.2" type="text/css" media="all"> <link rel="stylesheet" id="ivan-theme-styles-css" href="http://www.magmamachine.co.uk/wp-content/themes/october/css/theme-styles.min.css?ver=1" type="text/css" media="all"> <link rel="stylesheet" id="ivan-default-style-css" href="http://www.magmamachine.co.uk/wp-content/themes/october/style.css?ver=4.2.2" type="text/css" media="all"> <!--[if IE]> <link rel='stylesheet' id='ie-ivan-theme-styles-css' href='http://www.magmamachine.co.uk/wp-content/themes/october/css/ie.css' type='text/css' media='all' /> <![endif]--> <link rel="stylesheet" id="redux-google-fonts-iv_aries-css" href="http://fonts.googleapis.com/css?family=Roboto+Condensed%3A400&ver=4.2.2" type="text/css" media="all"> <link rel="stylesheet" id="woocommerce-layout-css" href="http://www.magmamachine.co.uk/wp-content/themes/october/css/woocommerce/css/woocommerce-layout.css?ver=2.3.13" type="text/css" media="all"> <link rel="stylesheet" id="woocommerce-smallscreen-css" href="http://www.magmamachine.co.uk/wp-content/themes/october/css/woocommerce/css/woocommerce-smallscreen.css?ver=2.3.13" type="text/css" media="only screen and (max-width: 768px)"> <link rel="stylesheet" id="woocommerce-general-css" href="http://www.magmamachine.co.uk/wp-content/themes/october/css/woocommerce/css/woocommerce.css?ver=2.3.13" type="text/css" media="all"> <script type="text/javascript" src="http://www.magmamachine.co.uk/wp-includes/js/jquery/jquery.js?ver=1.11.2"></script> <script type="text/javascript" src="http://www.magmamachine.co.uk/wp-includes/js/jquery/jquery-migrate.min.js?ver=1.2.1"></script> <script type="text/javascript" src="http://www.magmamachine.co.uk/wp-content/themes/october/plugins/login-with-ajax/login-with-ajax.js?ver=4.2.2"></script> <script type="text/javascript" src="http://www.magmamachine.co.uk/wp-content/plugins/chimpy/assets/js/chimpy-frontend.js?ver=2.1.3"></script> <script type="text/javascript" src="http://www.magmamachine.co.uk/wp-content/plugins/chimpy/assets/forms/js/jquery.form.min.js?ver=20130711"></script> <script type="text/javascript" src="http://www.magmamachine.co.uk/wp-content/plugins/chimpy/assets/forms/js/jquery.validate.min.js?ver=1.11.0"></script> <script type="text/javascript" src="http://www.magmamachine.co.uk/wp-content/plugins/chimpy/assets/forms/js/jquery.maskedinput.min.js?ver=1.3.1"></script> <script type="text/javascript" src="http://www.magmamachine.co.uk/wp-content/plugins/revslider/rs-plugin/js/jquery.themepunch.tools.min.js?ver=4.6.5"></script> <script type="text/javascript" src="http://www.magmamachine.co.uk/wp-content/plugins/revslider/rs-plugin/js/jquery.themepunch.revolution.min.js?ver=4.6.5"></script> <script type="text/javascript"> /* <![CDATA[ */ var wc_add_to_cart_params = {"ajax_url":"\/wp-admin\/admin-ajax.php","i18n_view_cart":"View Basket","cart_url":"","is_cart":"","cart_redirect_after_add":"no"}; /* ]]> */ </script> <script type="text/javascript" src="//www.magmamachine.co.uk/wp-content/plugins/woocommerce/assets/js/frontend/add-to-cart.min.js?ver=2.3.13"></script> <script type="text/javascript" src="http://www.magmamachine.co.uk/wp-content/plugins/js_composer/assets/js/vendors/woocommerce-add-to-cart.js?ver=4.5.3"></script> <link rel="EditURI" type="application/rsd+xml" title="RSD" href="http://www.magmamachine.co.uk/xmlrpc.php?rsd"> <link rel="wlwmanifest" type="application/wlwmanifest+xml" href="http://www.magmamachine.co.uk/wp-includes/wlwmanifest.xml"> <meta name="generator" content="WordPress 4.2.2"> <meta name="generator" content="WooCommerce 2.3.13"> <script type="text/javascript"> jQuery(document).ready(function() { // CUSTOM AJAX CONTENT LOADING FUNCTION var ajaxRevslider = function(obj) { // obj.type : Post Type // obj.id : ID of Content to Load // obj.aspectratio : The Aspect Ratio of the Container / Media // obj.selector : The Container Selector where the Content of Ajax will be injected. It is done via the Essential Grid on Return of Content var content = ""; data = {}; data.action = 'revslider_ajax_call_front'; data.client_action = 'get_slider_html'; data.token = 'fb1a3202b0'; data.type = obj.type; data.id = obj.id; data.aspectratio = obj.aspectratio; // SYNC AJAX REQUEST jQuery.ajax({ type:"post", url:"http://www.magmamachine.co.uk/wp-admin/admin-ajax.php", dataType: 'json', data:data, async:false, success: function(ret, textStatus, XMLHttpRequest) { if(ret.success == true) content = ret.data; }, error: function(e) { console.log(e); } }); // FIRST RETURN THE CONTENT WHEN IT IS LOADED !! return content; }; // CUSTOM AJAX FUNCTION TO REMOVE THE SLIDER var ajaxRemoveRevslider = function(obj) { return jQuery(obj.selector+" .rev_slider").revkill(); }; // EXTEND THE AJAX CONTENT LOADING TYPES WITH TYPE AND FUNCTION var extendessential = setInterval(function() { if (jQuery.fn.tpessential != undefined) { clearInterval(extendessential); if(typeof(jQuery.fn.tpessential.defaults) !== 'undefined') { jQuery.fn.tpessential.defaults.ajaxTypes.push({type:"revslider",func:ajaxRevslider,killfunc:ajaxRemoveRevslider,openAnimationSpeed:0.3}); // type: Name of the Post to load via Ajax into the Essential Grid Ajax Container // func: the Function Name which is Called once the Item with the Post Type has been clicked // killfunc: function to kill in case the Ajax Window going to be removed (before Remove function ! // openAnimationSpeed: how quick the Ajax Content window should be animated (default is 0.3) } } },30); }); </script> <style type="text/css">.recentcomments a{display:inline !important;padding:0 !important;margin:0 !important;}</style> <meta name="generator" content="Powered by Visual Composer - drag and drop page builder for WordPress."> <!--[if IE 8]><link rel="stylesheet" type="text/css" href="http://www.magmamachine.co.uk/wp-content/plugins/js_composer/assets/css/vc-ie8.css" media="screen"><![endif]--> <!--[if gte IE 9]> <style type="text/css"> ..mega_main_menu, ..mega_main_menu * { filter: none; } </style> <![endif]--> <!-- BEGIN Typekit Fonts for WordPress --> <script type="text/javascript" src="//use.typekit.net/prl6byj.js"></script> <style type="text/css">.tk-proxima-nova{font-family:"proxima-nova",sans-serif;}</style><link rel="stylesheet" href="http://use.typekit.net/c/22bbac/1w;proxima-nova,7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191,gbm:V:i4,gbt:V:i7,gbl:V:n4,gbs:V:n7/d?3bb2a6e53c9684ffdc9a9aff1b5b2a6276adde0ff798449a3bfbdbf9b6f1614fe7f047719e422580edd9d4512a6f131617d729a1e2861c6f1d559f758f16e5f4f033898b8bfbc0aca15c145112888b3d2a478ead4718a4e9956bc4" media="all"><script type="text/javascript">try{Typekit.load();}catch(e){}</script> <!-- END Typekit Fonts for WordPress --> <style type="text/css" title="dynamic-css" class="options-output">.iv-layout.header{margin-top:30px;}#iv-layout-title-wrapper{border-top-width:1px;border-top-color:#f7f7f7;border-bottom-color:#f7f7f7;}#iv-layout-title-wrapper h2{font-family:Roboto Condensed;letter-spacing:-2px;font-weight:400;font-size:50px;}.iv-layout.bottom-footer{background-color:#303030;}</style><style type="text/css"></style><style type="text/css"></style><style type="text/css"></style> <style type="text/css"> </style> <noscript><style> .wpb_animate_when_almost_visible { opacity: 1; }</style></noscript></head> <aside id="chimpy_form-3" class="widget widget_chimpy_form"> <form id="chimpy_widget_1" class="chimpy_signup_form sky-form sky-form-orange chimpy_custom_css" novalidate="novalidate"> <input type="hidden" name="chimpy_widget_subscribe[form]" value="1"> <input type="hidden" id="chimpy_form_context" name="chimpy_widget_subscribe[context]" value="widget"> <header>Join our mailing list</header> <div class="chimpy_status_underlay"> <fieldset> <div class="description">blog updates and exclusive offers for members</div> <section> <label class="input"><i class="icon-append fa-user"></i> <input type="text" id="chimpy_widget_field_FNAME" name="chimpy_widget_subscribe[custom][FNAME]" placeholder="First Name ..."> </label> </section> <section> <label class="input"><i class="icon-append fa-user"></i> <input type="text" id="chimpy_widget_field_LNAME" name="chimpy_widget_subscribe[custom][LNAME]" placeholder="Last Name ..."> </label> </section> <section> <label class="input"><i class="icon-append fa-envelope-o"></i> <input type="text" id="chimpy_widget_field_EMAIL" name="chimpy_widget_subscribe[custom][EMAIL]" placeholder="Email Address ..."> </label> </section> </fieldset> <div id="chimpy_signup_widget_processing" class="chimpy_signup_processing" style="display: none;"></div> <div id="chimpy_signup_widget_error" class="chimpy_signup_error" style="display: none;"> <div></div> </div> <div id="chimpy_signup_widget_success" class="chimpy_signup_success" style="display: none;"> <div></div> </div> </div> <footer> <button type="button" id="chimpy_widget_submit" class="button">sign me up</button> </footer> </form> <script type="text/javascript"> jQuery(function() { jQuery("#chimpy_widget_1").validate({ rules: { "chimpy_widget_subscribe[custom][FNAME]": { "required": false, "maxlength": 200 }, "chimpy_widget_subscribe[custom][LNAME]": { "required": false, "maxlength": 200 }, "chimpy_widget_subscribe[custom][EMAIL]": { "required": true, "maxlength": 200, "email": true } }, messages: { "chimpy_widget_subscribe[custom][FNAME]": [], "chimpy_widget_subscribe[custom][LNAME]": [], "chimpy_widget_subscribe[custom][EMAIL]": { "required": "Please enter a value", "email": "Invalid format" } }, errorPlacement: function(error, element) { error.insertAfter(element.parent()); } }); }); </script> </aside> I am using a jQuery plugin flipoclock.js to put the countdown timer in my webpage.Currently the code works fine for current time,Now i want to customize into my specific time for example i am developing an online quiz application so i should keep timer for 30 minutes.Anyone can help me? ,following script as below
// enter code here var clock; $(document).ready(function () { clock = $('.clock').FlipClock({ clockFace: 'TwelveHourClock' });
-3165742 1 Having PyQt app controlling all. How use reactor? I've a django application, served via Twisted, which also serves ohter services (three sockets, mainly).
I need to have it working under windows, and I decide to write a PyQt4 application which acts quite like Apache Service Monitor for windows.
I was not able to connect twisted reactor to pyqt application reactor, so any hint on this will be welcome too.
Now I've this kind of architecture:
I need to understand how to run the reactor, becouse calling reactor.start() from QtCore.QThread works not at all, giving me:
exceptions.ValueError: signal only works in main thread Also I'm asking your opinion on the design of applications, does it makes sense for you?
-586149 0You could allow every subdomain in the first place and then check if the subdomain is valid. For example:
RewriteEngine on RewriteCond %{HTTP_HOST} ^[^.]+\.example\.com$ RewriteRule !^index\.php$ index.php [L] Inside the index.php you can than extract the subdomain using:
if (preg_match('/^([^.]+)\.example\.com$/', $_SERVER['HTTP_HOST'], $match)) { var_dump($match[1]); } But all this requires that your webserver accepts every subdomain name.
-37125614 0Why not do something like:
np.sort(m)[:,-N:]
-30541294 0 Computation with Floating Point Numbers: When to Round? I'm performing some computations in C with floating point numbers. I'm specifically dealing with the case where I get the lowest possible single precision value for the exponent.
Say my exponent is -126 and I have to decrement it. In this case, I can't go any lower, so I need to right shift my mantissa once. I know I'm supposed to get the exact answer for a calculation and then round (to whatever place is specified).
I'm thinking of doing (let M be the mantissa):
M >>= 1; //round mantissa since I'm shifting the mantissa to the right and there was an implied 1 to the left of the floating point, do I need to modify M after shifting with something like:
M |= (1 << 23) to ensure I have a 1 in the most significant bit?
It seems weird to round after losing a bit of information but is this standard / accepted practice? Or should I calculate the full result by using more bits and then rounding?
I'd give this a shot http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
<script> var app = angular.module('myApp', []); app.controller('customersCtrl', function($scope, $http) { $http.jsonp("http://localhost/json/customer.php?callback=JSON_CALLBACK") .success(function (response) { $scope.simo = response.data; console.log($scope.simo) }); }); app.directive('display',function(){ return { restrict: 'E', scope: { simo: '=' }, template: '<li ng-repeat="x in simo">{{ x.Name + ', ' + x.Country }}</li>' }; }); </script> Not sure if your intent was to pass the entire response object to the directive, but response.data is the location of what you're likely expecting back from the ajax call.
Aside from that I would make sure that your object structure is correct. Or if you're returning an array that you set that flag in the $http call.
-16435041 0 Changing a displayedI would like to ask some help on this thing. I created a site that has a lot of div and what I want is that when a link is clicked only one div will be displayed without reloading the whole page.
Sample code:
<ul> <li><a href="">Div 1</a></li> <li><a href="">Div 2</a></li> <li><a href="">Div 3</a></li> </ul> <div id="content1"> <p>This is content 1</p> </div> <div id="content2"> <p>This is content 2</p> </div> <div id="content3"> <p>This is content 13</p> </div> Is it possible if I'll just use php? And please help me on how I will do it.
-13646954 1 swig generated code, generating illegal storage class for python wrapper of C++ APII'm trying to take the approach of using swig with the main header file. It seems like swig will work doing this, but I've run into some problems. I asked a first question about it here on stackoverflow and while I haven't yet been successful, I've made enough progress to feel encouraged to continue...
So now, here's my interface file:
/* File : myAPI.i */ %module myAPI %{ #include "stdafx.h" #include <boost/algorithm/string.hpp> ... many other includes ... #include "myAPI.h" #include <boost/algorithm/string/predicate.hpp> #include <boost/filesystem/path.hpp> #include <boost/filesystem/operations.hpp> using boost::format; using namespace std; using namespace boost::algorithm; using namespace boost::serialization; %} /* Let's just grab the original header file here */ %include "myAPI.h" As far as I can tell swig runs just fine. However, in the generated code it produces numerous definitions like this one:
SWIGINTERN int Swig_var_ModState_set(PyObject *_val) { { void *argp = 0; int res = SWIG_ConvertPtr(_val, &argp, SWIGTYPE_p_MY_API, 0 | 0); if (!SWIG_IsOK(res)) { SWIG_exception_fail(SWIG_ArgError(res), "in variable '""ModState""' of type '""MY_API""'"); } if (!argp) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in variable '""ModState""' of type '""MY_API""'"); } else { MY_API * temp; temp = reinterpret_cast< MY_API * >(argp); ModState = *temp; if (SWIG_IsNewObj(res)) delete temp; } } return 0; fail: return 1; } Visual Studio 2010 complains with an error for each of these code blocks. The error is based on the temp var:
2>c:\svn\myapi\myapi_wrap.cxx(3109): error C2071: 'temp' : illegal storage class I tried just to add a global declaration of this variable as an int to the swig generated _wrap.cxx file, but it didn't not work. (clearly a naive approach...).
Does anyone have some insight as to what I need to do to avoid this error?
Thanks in advance!
-26681054 0Note change event fires after the input loses focus. You may want to use input event instead.
To convert the string to numbers, you can use the unary operator + instead of Number.
To default to 0 when some expression is falsy, you can use expr || 0.
var field1 = document.getElementById('field1'), field2 = document.getElementById('field2'), total = document.getElementById('total'); field1.oninput = field2.oninput = function updateTotalCosts() { total.value = (+field1.value || 0) + (+field2.value || 0); }; <input id="field1" /> + <input id="field2" /> = <input id="total" /> Or, using jQuery,
var $field1 = $('#field1'), $field2 = $('#field2'), $total = $('#total'); $field1.add($field2).on('input change', function updateTotalCosts() { $total.val((+$field1.val() || 0) + (+$field2.val() || 0)); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input id="field1" /> + <input id="field2" /> = <input id="total" /> It's saying that there are virtual fields in Person which are not defined. So far we can see your declarations, but not definitions. Check that every virtual field in Person, including those inherited, is defined.
if you are using {% render_comment_form for object %} tag in your template, just add something like {% url object's_named_view object.id as next %} or wrap it with {% with object.get_absolute_url as next %} ... {% endwith %} construction.
You just have to know that you might be reloading the page, and you may try to use the
if(!IsPostBack) in your Page_Load(object sender, EventArgs e)
You've an answer how to do this with XML::Simple already. But I'd suggest not, and use XML::Twig instead, which is MUCH less nasty.
Why is XML::Simple "Discouraged"?
I'm going to assume that your XML looks a bit like this:
<opt Timeout="5"> <Roots> <Root Action="Reject" Interval="Order" Level="Indeterminate" Name="Sales"> <Profiles> <Profile Age="50" Name="Bill" Status="Active" /> <Profile Age="24" Name="Bob" Status="Inactive" /> </Profiles> </Root> </Roots> </opt> I can't tell for sure, because that's the joy of XML::Simple. But:
#!/usr/bin/env perl use strict; use warnings; use XML::Twig; my $twig = XML::Twig -> new -> parsefile ( $configfile ); print $twig -> get_xpath ( '//Profile[@Name="Bob"]',0 ) -> att('Status') This uses xpath to locate the attribute you desire - // denotes a 'anywhere in tree' search.
But you could instead:
print $twig -> get_xpath ( '/opt/Roots/Root/Profiles/Profile[@Name="Bob"]',0 ) -> att('Status') Much simpler wouldn't you agree?
Or iterate all the 'Profiles':
foreach my $profile ( $twig -> get_xpath ('//Profile' ) ) { print $profile -> att('Name'), " => ", $profile -> att('Status'),"\n"; }
-36578070 0 Google Cloud Messaging IP address I have made an android application with GCM enabled service in it which works on localhost. User needs to register in order save the device id in the database which would help administrator to send push notifications to the user. Since, the database is on localhost, registration works fine on emulator. But after installing the app on phone, the device does not get registered. Due to unsuccessful registration, the details do not get entered into the database. After searching a bit, found out the problem as the ip address. IP address on pc is different than the address taken by phone even via same router. Is there any solution for this problem? I really need to run the app on the phone and not just on emulator. Thanks in advance!
-28619001 0 How to migrate from Qt Creator to other IDEs, like Eclipse and Code::BlocksI'm trying to develop a toolbox for System Identification and some other Engineering problems. I've managed to write source codes in C++ and they seem to be functional.
Now I'm trying to create some GUI using Qt Creator. Using some tutorials I've found using Qt very simple, but I'm not sure what happens if I decide to change my IDE for some reasons.
In my code there are a lot of code lines specific to Qt like: QtWidgets/QApplication, QtWidgets/QLabel, ...
As a newbie in programming could someone explain me if there are some standard methods for migrating from Qt Creator to other IDEs.
-3665231 0You can add functions to Studio by putting PHP files with stub function descriptions into special directory. Find this directory in filesystem in a following way: write something like gmdate(), select the name and press F3. You will be taken to one of the prototype files. Note the directory where this file resides (shown on the top and if you hover over the tab). Now you need to create stubs for functions you are missing just like the one you're looking at. You can put them into any file, generally, but I suggest putting them into separate file - like geoip.php - and put this file into that directory. You may also want to do right-click/Show In/PHP Explorer and browse other prototype files if you need examples of how to do it right.
-11843865 0It's very simple:
DocsList.getFileById(SpreadsheetApp.getActiveSpreadsheet().getId()).makeCopy(SpreadsheetApp.getActiveSpreadsheet().getName() + "_copy");
-10703019 0 Redis fetch all value of list without iteration and without popping I have simple redis list key => "supplier_id"
Now all I want it retrieve all value of list without actually iterating over or popping the value from list
Example to retrieve all the value from a list Now I have iterate over redis length
element = [] 0.upto(redis.llen("supplier_id")-1) do |index| element << redis.lindex("supplier_id",index) end can this be done without the iteration perhap with better redis modelling . can anyone suggest
-15150483 0I think StringTokenizer based solution will be the fastest
public static int[] splitDateTime(String dateTime) { int[] intParts = new int[5]; StringTokenizer t = new StringTokenizer(dateTime, "/ :"); for (int i = 0; t.hasMoreTokens(); i++) { intParts[i] = Integer.parseInt(t.nextToken()); } return intParts; } public static void main(final String[] args) throws IOException { System.out.println(Arrays.toString(splitDateTime("01/03/2013 09:00"))); } output
[1, 3, 2013, 9, 0]
-22496898 0 Refresh a page in MVC How to refresh the current page in MVC.
[HttpGet] public ActionResult Request() { if (Session["type"] != null && Session["resulttype"] != null) { return View(); } else { return null; } } I want to refresh my page in else part. That is when return null value.
-1104625 0 Cruisecontrol, deployment, folder permissionsWe're using cruisecontrol.net, it builds the version, creates a zip file, then 15 min later, unzips the file on the Integration server. But when the folder gets to the integration server, often, the security permission on one of the folders is totally hosed. The Domain admin and folder owner can't even open the folder in explorer. We reboot and the folder permissions are good we can delete the folder and redeploy the zip file and it's okay.
Does anyone have any idea what or how the folder permissions are getting so messed up? Any tools to use to diagnose/watch what exactly is messing it up?
-23111106 0 In My database my application form data not storingI developed one form.it will not work properly.here is my code all db,model,controller classes
here is database code.
database:
CREATE TABLE users ( id INT( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY , username VARCHAR( 40 ) NOT NULL , password VARCHAR( 40 ) NOT NULL , email VARCHAR( 255 ) NOT NULL , first_name VARCHAR( 40 ) NOT NULL , last_name VARCHAR( 40 ) NOT NULL ) model class:
<?php class User extends AppModel{ var $name='User'; } ?> view class:
<html> <form action="../users/register" method="post"> <p>Please fill out the form below to register an account.</p> <label>Username:</label><input name="username" size="40" /> <label>Password:</label><input type="password" name="password" size="40"/> <label>Email Address:</label><input name="email" size="40" maxlength="255" /> <label>First Name:</label><input name="first_name" size="40" /> <label>Last Name:</label><input name="last_name" size="40" /> <input type="submit" value="register" /> </form> </html> controller class:
<?php class UsersController extends AppController{ function register(){ if (!empty($this->params['form'])){ if($this->User->save($this->params['form'])){ $this->flash('Registration Successful','/users/register'); } else{ $this->flash('Not succeeded','/users/register'); } } } } ?> please resolve my problem
-13872904 0 Javascript alert box and confirmation afterI want to create a javascript for checking value of textbox so if the textbox blank, it won't proceed to next page. AND after checking (if all condition is true) it will return the result of textbox.
I've created this javascript:
function cekdata(myform) { var id = document.myform.clientid.value; var nama = document.myform.nama.value; var divisi = document.myform.divisi.value; var way = document.getElementById('twoway').value; var ori = document.myform.lokasi.value; var desti = document.myform.tujuan.value; var ket = document.myform.keterangan.value; var tpergi = document.myform.tglb.value; var jpergi = document.myform.jamb.value; var mpergi = document.myform.menitb.value; var pegi = tpergi+', '+jpergi+':'+mpergi; var tplg = document.myform.tglp.value; var jplg = document.myform.jamp.value; var mplg = document.myform.menitp.value; var plg = tplg+', '+jplg+':'+mplg; if (document.myform.clientid.value == "") { alert("Please Fill Your ID"); myform.clientid.focus(); return false; } else if (document.myform.nama.value == "") { alert("Please Fill Passenger Name"); myform.nama.focus(); return false; } else if (document.myform.lokasi.value == "") { alert("Please Fill Origin Location"); myform.lokasi.focus(); return false; } else if (document.myform.tujuan.value == "") { alert("Please Fill Your Destination"); myform.tujuan.focus(); return false; } else if (document.myform.tglb.value == "") { alert("Please Fill Departure Date"); myform.tglb.focus(); return false; } else if (document.myform.novehicle.value == "") { alert("Please Fill Vehicle Number"); myform.novehicle.focus(); return false; } else if (document.myform.driverid.value == "") { alert("Please Fill Driver ID"); myform.driverid.focus(); return false; } else if(document.getElementById('twoway').checked) { if (document.myform.tglp.value == "") { alert("Please Fill Return Date"); myform.tglp.focus(); return false; } else if (document.myform.tglb.value > document.myform.tglp.value) { alert("Return date must bigger than departure date"); myform.tglp.focus(); return false; } } else { var a = window.confirm("CONFIRMATION :\nID : " +id+"\nName : "+nama+"\nDivision : "+divisi+"\nOne Way : "+way+"\nOrigin : "+ori+"\nDestination : "+desti+"\nNotes : "+ket+"\nDeparture : "+pegi+"\nArrived :"+plg); if (a==true) { return true; } else { return false; } } } And I called this function like this:
<form name="myform" onsubmit="return cekdata(this);" method="POST" action="<?php $_SERVER["PHP_SELF"]; ?>"> But what I got is the confirm box never show up, and it returns true (and go to next page). So, how to change this condition so my confirmation box showed up first, then after click OK, it go to next page, and if CANCEL, do nothing?
-39601609 0 Angular 2 - cant load demo libraries (Visual Studio 2015)OK I am stumped: Is there a basic, minimal, working Angular 2 tutorial for Visual Studio 2015
that actually works?
I've attempted numerous tutorials including the official one: https://angular.io/docs/ts/latest/cookbook/visual-studio-2015.html
Believe it or not, at the time of writing this post this example does not work - throws a 404 for numerous dependencies referenced in the NPM package.json file (as for the others tuts, well they reference a lot of beta removed or non-existing references).
I mean, where do you actually download Angular 2 Typings from? They are certainly not listed with the rest of the library on the official site: https://code.angularjs.org/
It actually seems to be impossibly complicated to create an Angular 2 application in Visual Studio that does not require a mass of dependencies and actually works.
Is it just me or are other members of the VS dev community experiencing the same?
output for NPM package.json:
npm WARN package.json angular-quickstart@1.0.0 No README data npm http GET https://registry.npmjs.org/core-js npm http GET https://registry.npmjs.org/bootstrap npm http GET https://registry.npmjs.org/reflect-metadata npm http GET https://registry.npmjs.org/zone.js npm http GET https://registry.npmjs.org/systemjs npm http GET https://registry.npmjs.org/angular2-in-memory-web-api npm http GET https://registry.npmjs.org/http-server npm http GET https://registry.npmjs.org/lite-server npm http GET https://registry.npmjs.org/canonical-path npm http GET https://registry.npmjs.org/jasmine-core npm http GET https://registry.npmjs.org/karma-chrome-launcher npm http GET https://registry.npmjs.org/karma-htmlfile-reporter npm http GET https://registry.npmjs.org/angular/core npm http GET https://registry.npmjs.org/angular/compiler npm http GET https://registry.npmjs.org/angular/common npm http GET https://registry.npmjs.org/angular/platform-browser npm http GET https://registry.npmjs.org/angular/platform-browser-dynamic npm http GET https://registry.npmjs.org/angular/http npm http GET https://registry.npmjs.org/angular/forms npm http GET https://registry.npmjs.org/angular/router npm http GET https://registry.npmjs.org/angular/upgrade npm http GET https://registry.npmjs.org/karma-cli npm http GET https://registry.npmjs.org/karma-jasmine npm http GET https://registry.npmjs.org/rxjs npm http GET https://registry.npmjs.org/lodash npm http GET https://registry.npmjs.org/typescript npm http GET https://registry.npmjs.org/tslint npm http GET https://registry.npmjs.org/typings npm http GET https://registry.npmjs.org/karma npm http GET https://registry.npmjs.org/protractor npm http GET https://registry.npmjs.org/rimraf npm http GET https://registry.npmjs.org/concurrently npm http 304 https://registry.npmjs.org/systemjs npm http 304 https://registry.npmjs.org/zone.js npm http 304 https://registry.npmjs.org/core-js npm http 304 https://registry.npmjs.org/reflect-metadata npm http 304 https://registry.npmjs.org/angular2-in-memory-web-api npm http 200 https://registry.npmjs.org/http-server npm http 304 https://registry.npmjs.org/lite-server npm http 304 https://registry.npmjs.org/jasmine-core npm http 304 https://registry.npmjs.org/karma-chrome-launcher npm http 304 https://registry.npmjs.org/bootstrap npm http 304 https://registry.npmjs.org/karma-htmlfile-reporter npm http 304 https://registry.npmjs.org/canonical-path npm http 404 https://registry.npmjs.org/angular/core npm ERR! 404 Not Found npm ERR! 404 npm ERR! 404 'angular/core' is not in the npm registry. npm ERR! 404 You should bug the author to publish it npm ERR! 404 It was specified as a dependency of 'angular-quickstart' npm ERR! 404 npm ERR! 404 Note that you can also install from a npm ERR! 404 tarball, folder, or http url, or git url. npm ERR! System Windows_NT 6.2.9200 npm ERR! command "C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\IDE\\Extensions\\Microsoft\\Web Tools\\External\\\\node\\node" "C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\IDE\\Extensions\\Microsoft\\Web Tools\\External\\npm\\node_modules\\npm\\bin\\npm-cli.js" "install" npm ERR! cwd D:\www\WebApplication1\WebApplication1 npm ERR! node -v v0.10.31 npm ERR! npm -v 1.4.9 npm ERR! code E404 npm http 404 https://registry.npmjs.org/angular/platform-browser npm http 404 https://registry.npmjs.org/angular/platform-browser-dynamic npm http 404 https://registry.npmjs.org/angular/http npm http 404 https://registry.npmjs.org/angular/compiler npm http 404 https://registry.npmjs.org/angular/router npm http 404 https://registry.npmjs.org/angular/upgrade npm http 404 https://registry.npmjs.org/angular/common npm http 304 https://registry.npmjs.org/karma-cli npm http 304 https://registry.npmjs.org/karma-jasmine npm http 304 https://registry.npmjs.org/rxjs npm http 304 https://registry.npmjs.org/typescript npm http 304 https://registry.npmjs.org/tslint npm http 404 https://registry.npmjs.org/angular/forms npm http 304 https://registry.npmjs.org/karma npm http 304 https://registry.npmjs.org/protractor npm http 200 https://registry.npmjs.org/lodash npm http 304 https://registry.npmjs.org/typings npm http 304 https://registry.npmjs.org/concurrently npm http 200 https://registry.npmjs.org/rimraf npm ====npm command completed with exit code 1====
-38661019 0 Try .nextUntil():
$(".lev1").click(function(){ $(this).nextUntil(".lev1").toggle(); }); $(".lev1").click(function(){ $(this).nextUntil(".lev1").toggle(); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='folder lev1'>323</div> <div class='folder lev2'>525</div> <div class='file lev3'>727</div> <div class='file lev4'>1625</div> <div class='folder lev1'>new</div> I am trying to use remove the repeated classes declared in css file using css purge of node js but after installing purge package i am getting error as shown in screenshot please help error : cannot find module /lib/css_purge
-6025821 0As eluded to by @Space_C0wb0y, you need to either build Boost.System or use its correct name for linking (e.g. -lboost_system-mt).
-8464254 0You can use java.lang.Runtime.exec(String command) to execute a shell script from Java.
-11935566 0From the top of my mind:
void * const var; // The pointer is constant and var can change const void * var; // The pointer can change but not var so I would think that your syntax
const void * const *ptr; means that ptr is a pointer to a pointer. So ptr would point to an address and that address cannot change (the first const). Also the address that ptr is located cannot change (the second const). But I am not totally sure of this.
-11715834 0 Binding jqplot with dynamic data in asp.net c#I am using jqplot to plot the graph in my project.I was able to draw it with static data.But i need to bind the chart with dynamic data from code behind with some datasource.
I am new to jqplot and also in jquery. So, I am stuck on this. I will be very thankful for any solution to it.It will be grateful if you can provide example solution
-5089719 0 from facebook, i want to fetch Hometown details . from it i want to saparate city,state, countryFrom facebook, i want to fetch Hometown details . from it i want to separate city,state, country. These fields are separated by comma. so i can split them by comma.
my problem is: as soon i enter city name in hometown field of facebook, it is giving combination of city,state and country. but sometime it is giving combination of city and country so, when i split this string by comma, how to i know that second element is state or country.
I can do one thing, i can check the length of array, if it has three filed then it has city/state/county. else city/county.
Is this ture? can it have more files.
-19444591 0The cross section is just a line graph (or two) overlayed on your original chart.
Here's an example of overlayed charts:
http://www.sqljason.com/2012/03/overlapping-charts-in-ssrs-using-range.html
-671136 0 Wrap NSButton titleAny way to have a NSButton title to wrap when it's width is longer than the button width, instead of getting clipped?
I'm trying to have a radio button with a text that can be long and have multiple lines. One way I thought about having it work is to have an NSButton of type NSRadioButton but can't get multiple lines of text to work.
Maybe my best alternative is to have an NSButton followed by an NSTextView with the mouseDown delegate function on it triggering the NSButton state?
-29326209 0 How would I get edit function with Json to redirect to another page with Angular jsI am having an issue were when i click edit the data only shows up on the same page not sure how to get it to redirect and show up on another page.
controller partial code just the edit and update function
/** function to edit product details from list of product referencing php **/ $scope.prod_edit = function(index) { $scope.update_prod = true; $scope.add_prod = false; $http.post('db.php?action=edit_product', { 'prod_index' : index } ) .success(function (data, status, headers, config) { //alert(data[0]["prod_name"]); $scope.prod_id = data[0]["id"]; $scope.prod_name = data[0]["prod_name"]; $scope.prod_desc = data[0]["prod_desc"]; $scope.prod_price = data[0]["prod_price"]; $scope.prod_quantity = data[0]["prod_quantity"]; }) .error(function(data, status, headers, config){ }); } /** function to update product details after edit from list of products referencing php **/ $scope.update_product = function() { $http.post('db.php?action=update_product', { 'id' : $scope.prod_id, 'prod_name' : $scope.prod_name, 'prod_desc' : $scope.prod_desc, 'prod_price' : $scope.prod_price, 'prod_quantity' : $scope.prod_quantity } ) .success(function (data, status, headers, config) { $scope.get_product(); alert("Product has been Updated Successfully"); }) .error(function(data, status, headers, config){ }); } }); db.php
/** Function to Edit Product **/ function edit_product() { $data = json_decode(file_get_contents("php://input")); $index = $data->prod_index; $qry = mysql_query('SELECT * from product WHERE id='.$index); $data = array(); while($rows = mysql_fetch_array($qry)) { $data[] = array( "id" => $rows['id'], "prod_name" => $rows['prod_name'], "prod_desc" => $rows['prod_desc'], "prod_price" => $rows['prod_price'], "prod_quantity" => $rows['prod_quantity'] ); } print_r(json_encode($data)); return json_encode($data); } /** Function to Update Product **/ function update_product() { $data = json_decode(file_get_contents("php://input")); $id = $data->id; $prod_name = $data->prod_name; $prod_desc = $data->prod_desc; $prod_price = $data->prod_price; $prod_quantity = $data->prod_quantity; // print_r($data); $qry = "UPDATE product set prod_name='".$prod_name."' , prod_desc='".$prod_desc."',prod_price='.$prod_price.',prod_quantity='.$prod_quantity.' WHERE id=".$id; $qry_res = mysql_query($qry); if ($qry_res) { $arr = array('msg' => "Product Updated Successfully!!!", 'error' => ''); $jsn = json_encode($arr); // print_r($jsn); } else { $arr = array('msg' => "", 'error' => 'Error In Updating record'); $jsn = json_encode($arr); // print_r($jsn); } } ?> The page i need it to redirect is http://localhost/angular_php/create_update.php
<!DOCTYPE html> <html ng-app="listpp" ng-app lang="en"> <head> <meta charset="utf-8"> <link href="assets/css/bootstrap.min.css" rel="stylesheet"> <style type="text/css"> ul>li, a{cursor: pointer;} </style> <title>Angular With PHP</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"> </script> <script src="controller.js"></script> </head> <body> <?php include "templates/header.php";?> <br><br> <div ng-controller="maincontroller"> <div class="wrapper"> <div class="container col-sm-8 col-sm-offset-2"> <div class="page-header"> <h4>Add/Update Product</h4> </div> <form class="form-horizontal" name="add_product" > <input type="hidden" name="prod_id" ng-model="prod_id"> <div class="form-group"> <label for="firstname" class="col-sm-2 control-label">Prod Name</label> <div class="col-sm-3"> <input type="text" class="form-control" name="prod_name" ng-model="prod_name" placeholder="Enter Product Name"> </div> </div> <div class="form-group"> <label for="lastname" class="col-sm-2 control-label">Prod Desc</label> <div class="col-sm-3"> <input type="text" class="form-control" name="prod_desc" ng-model="prod_desc" placeholder="Enter Product Description"> </div> </div> <div class="form-group"> <label for="lastname" class="col-sm-2 control-label">Prod Price</label> <div class="col-sm-3"> <input type="text" class="form-control" name="prod_price" ng-model="prod_price" placeholder="Enter Product Price"> </div> </div> <div class="form-group"> <label for="lastname" class="col-sm-2 control-label">Prod Quantity</label> <div class="col-sm-3"> <input type="text" class="form-control" name="prod_quantity" ng-model="prod_quantity" placeholder="Enter Product Quantity"> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default" name="submit_product" ng-show='add_prod' value="Submit" ng-click="product_submit()">Submit</button> <button type="submit" class="btn btn-default" name="update_product" ng-show='update_prod' value="Update" ng-click="update_product()">Update</button> </div> </div> </div> </form> </div> </div> <script src="assets/js/ui-bootstrap-tpls-0.10.0.min.js"></script> </body> </html>
-2401596 0 Please see this link.
I just solved it actually by setting in the <Applet .... tag the Name= property ...Now the Applet name is consistent across browsers.
Otherwise try repeatedly calling:
getAppletContext().showStatus(""); As described on jGuru.
-506534 0Yes, though you need to get familiar with the Team Foundation Server command line tf.exe.
See the post I did about this a while ago here http://www.woodwardweb.com/vsts/unlocking_files.html
Since I wrote that post (in October 2005) some alternatives have come about for people who don't want the hassle of learning a new command line.
You could install the TFS 2008 Power Tools on top of Visual Studio 2008 SP1 and you are able to do some of this from the UI in Visual Studio (Right click on the Developer in the Team Members node installed by the power tools and select "Show Pending Changes" and then "Undo..."
Alternatively, install the excellent (and free) TFS Sidekicks from Attrice.
Good luck.
-12796529 0If you still need to write code under -(void)methodA do
-(void)methodA { if(!isKeyBoarHidden){ [textField resignFirstResponder]; } else{ //code here } } - (void)keyboardHidden:(NSNotification *)notification { isKeyBoarHidden = YES; [self methodA]; } sometime it may be helpful if we have some local variables inside methodA and we dont need to make variables global.
I ended up using this middleware https://github.com/rs/cors, and that got everything working correctly.
-4992848 0As a starting point I'd look at the WinSock API. You may find a way of pulling traffic information on a per process basis. If you want to see total network usage, I'd use the Performance Monitoring tools. I found this example from a web search:
private static void ShowNetworkTraffic() { PerformanceCounterCategory performanceCounterCategory = new PerformanceCounterCategory("Network Interface"); string instance = performanceCounterCategory.GetInstanceNames()[0]; // 1st NIC ! PerformanceCounter performanceCounterSent = new PerformanceCounter("Network Interface", "Bytes Sent/sec", instance); PerformanceCounter performanceCounterReceived = new PerformanceCounter("Network Interface", "Bytes Received/sec", instance); for (int i = 0; i < 10; i++) { Console.WriteLine("bytes sent: {0}k\tbytes received: {1}k", performanceCounterSent.NextValue() / 1024, performanceCounterReceived.NextValue() / 1024); Thread.Sleep(500); } }
-9365243 0 SQLite doesn't have any built in boolean type. You need to handle it yourself. I typically use and integer value instead and set it equal to 1 or 0 for true or false. Then if you want to check if it is true in the DB you check if the value is 1, etc.
-19227641 0 store each string in sentence in reverse wayi try with buffered string.reverse(); but i want reverse each word of sentence. so i try with this..
for(int a = 0;a <= msgLength; a++){ temp += msg.charAt(a); if((msg.charAt(a) == '')||(a == msgLength)){ for(int b = temp.length()-1; b >= 0; b--){ encrypt_msg += temp.charAt(a); if((b == 0) && (a != msgLength)) encrypt_msg += ""; } temp = ""; } } plz help me to simplify this logic. string is user defined. i wanted to print reversed string in jtextfields.
-33759346 0Solution is to ditch the join table and have a direct reference between Test <> Team.
The SQL you are seeing makes sense as Hibernate cannot know that TestTeam will be the same entity referenced by Test and Team.
Test test = .../ test.getTestTeam();//triggers load **where test_id = test.id** Team team = test.getTestTeam().getTeam(); team.getTestTeam();// triggers load **where team_id = team.id**
-37312954 0 runtime.Stack() puts a formatted stack trace into a supplied []byte. You can then convert that to a string.
You can also use debug.Stack(), which allocates a large enough buffer to hold the entire stack trace, puts the trace in it using runtime.Stack, and returns the buffer ([]byte).
I guess you may be seeing a NPE, as you may be violating the paragraph you were citing:
String custData = custFacade.find(customerId).toString(); The find seems to implicitly querying for the object (as you describe), which may not be fully synced to the database and thus not yet accessible.
I have this code:
<?php if (isset ($_FILES['UploadFileField'])){ $UploadName = $_FILES['UploadFileField'] ['name']; $UploadName = mt_rand (100000, 999999).$UploadName; $UploadTmp = $_FILES['UploadFileField'] ['tmp_name']; $UploadType = $_FILES['UploadFileField'] ['type']; $FileSize = $_FILES['UploadFileField'] ['size']; $UploadName = preg_replace("#[^a-z0-9.]#i", "", $UploadName); if(($FileSize > 1250000)){ die ("Error - File to Big"); } if(!$UploadTmp) { die ("No File Selected"); } else { move_uploaded_file($UploadTmp, "Upload/$UploadName"); } header('Location: /index.php'); exit; } ?> This code works, but I need insert a message of successful after that is done Upload file. Thank you!
-5884061 0 LdrLoadDll problemI am trying to code an alternative to LoadLibrary function, based on the idea of calling the function LdrLoadDll from ntdll. This function needs as a parameter the dll file to load, in a UNICODE_STRING format. I really can't get what I am doing wrong here (string seems to be correctly initialized), but when LdrLoadDll is called, I get the following error:
Unhandled exception in "Test.exe" (NTDLL.DLL): 0xC0000005: Access Violation.
I use Visual C++ 6.0 for this test, and I am using Windows 7 64 bit.
I post full code here, thanks in advance for any help:
#include <Windows.h> typedef LONG NTSTATUS; //To be used with VC++ 6, since NTSTATUS type is not defined typedef struct _UNICODE_STRING { //UNICODE_STRING structure USHORT Length; USHORT MaximumLength; PWSTR Buffer; } UNICODE_STRING; typedef UNICODE_STRING *PUNICODE_STRING; typedef NTSTATUS (WINAPI *fLdrLoadDll) //LdrLoadDll function prototype ( IN PWCHAR PathToFile OPTIONAL, IN ULONG Flags OPTIONAL, IN PUNICODE_STRING ModuleFileName, OUT PHANDLE ModuleHandle ); /************************************************************************** * RtlInitUnicodeString (NTDLL.@) * * Initializes a buffered unicode string. * * RETURNS * Nothing. * * NOTES * Assigns source to target->Buffer. The length of source is assigned to * target->Length and target->MaximumLength. If source is NULL the length * of source is assumed to be 0. */ void WINAPI RtlInitUnicodeString( PUNICODE_STRING target, /* [I/O] Buffered unicode string to be initialized */ PCWSTR source) /* [I] '\0' terminated unicode string used to initialize target */ { if ((target->Buffer = (PWSTR) source)) { unsigned int length = lstrlenW(source) * sizeof(WCHAR); if (length > 0xfffc) length = 0xfffc; target->Length = length; target->MaximumLength = target->Length + sizeof(WCHAR); } else target->Length = target->MaximumLength = 0; } NTSTATUS LoadDll( LPCSTR lpFileName) { HMODULE hmodule = GetModuleHandleA("ntdll.dll"); fLdrLoadDll _LdrLoadDll = (fLdrLoadDll) GetProcAddress ( hmodule, "LdrLoadDll" ); int AnsiLen = lstrlenA(lpFileName); BSTR WideStr = SysAllocStringLen(NULL, AnsiLen); ::MultiByteToWideChar(CP_ACP, 0, lpFileName, AnsiLen, WideStr, AnsiLen); UNICODE_STRING usDllFile; RtlInitUnicodeString(&usDllFile, WideStr); //Initialize UNICODE_STRING for LdrLoadDll function ::SysFreeString(WideStr); NTSTATUS result = _LdrLoadDll(NULL, LOAD_WITH_ALTERED_SEARCH_PATH, &usDllFile,0); //Error on this line! return result; } void main() { LoadDll("Kernel32.dll"); }
-35618210 0 Why are you putting ref.a inside {}? You were essentially trying to create a object with no key value. Here's the fix:
var ref = [{"a":"x","b":"y"]; var someArrayOfObject = [{t1:ref.a},{t1:ref.b}];
-10618822 0 JavaScript doesn't append script I'm using "PHP Form Builder Class" to generate form and submit it with ajax, but i dont think problem is related to "PHP Form Builder Class".
I`m loading form and "PHP Form Builder Class" is generating javascript that binds some events to submit action, and jquery-ui button etc.
When i submit form and get response from server (html+javascript) then i empty container and load new data - with the same form (to show errors or submit new one).
Problem is that second time it wont bind any events to my form.
I have removed all events from previous html code, before deleting it and adding new one.
So now to the weird part - when i insert new html and js into my container it wont show that particular javascript code that is intended for form. I cant see it in html DOM anywhere when inspecting. I added simple alert(1) in it to check if it will run, and it does, although rest of the code doesnt - and i dont get any errors. So how can this alert run when it doesn't show in dom. I'm appending code with jquery.html()
I know its not easy to understand my problem, but i hope someone will
-40798146 0 accessing class instances in all classesFor a school assignment, I have created a program that add and searches for products, the adding and searching are performed in the class EStoreSearch, I've created 3 other classes to create GUI JFrames. My question is how do I allow the JFrame classes to access the same instance of the EStoreSearch class that stores the ArrayList data(which stores all the products) so that I can add and search for products in the GUI?
i have a simple markup with a navigation div, a content div and a footer div. If I open my "page", everything seems okay. But if I open the page and then resize the browser window to e.g. 30%, then the content div slides down.
It seems only to occur in internet explorer.
The test markup:
<html> <body> <div id="container"> <div id="navi" style="float:left;width:197px;background-color:blue;"> NaviContent <br /><br /> more NaviContent </div> <div id="content" style="width:820px;background-color:yellow"> <table> <tr> <td>Content <br /><br /> more ContentContent <br /><br /><br /><br /> <br /><br /><br /><br /> more ContentContent <br /><br /><br /><br /> <br /><br /><br /><br /> more ContentContent </td> </tr> </table> </div> <div id="footer" style="clear:both;"> Footer Content </div> </div> </body> </html> Images of the problem:
browser in 100% view: http://www.suckmypic.net/25729/1.png
browser window resized: http://www.suckmypic.net/25730/2.png
Please help
-13616939 0The only thing that sticks out is "&" which is + in SQL Server. However, & in access also treats NULL values as the empty string, which needs further processing with ISNULL in SQL Server:
SELECT table1.* FROM table1 INNER JOIN (table2 INNER JOIN table3 ON ( table2.custkey = table3.custkey ) AND ( table2.sequence = table3.sequence )) ON table1.account = table2.account WHERE (( LEFT(table2.keyid, 1) = 'B' )) ORDER BY isnull(table3.lastname,'') + isnull(table3.firstname,''), table1.account; If I were to write the query in SQL Server from scratch, I would probably do the joins serially rather than do the t2-t3 in a bracket before joining back to t1. The test for the first character would also be expressed as LIKE (a personal preference).
SELECT table1.* FROM table1 JOIN table2 ON table1.account = table2.account JOIN table3 ON table2.custkey = table3.custkey AND table2.sequence = table3.sequence WHERE table2.keyid LIKE 'B%' ORDER BY isnull(table3.lastname,'') + isnull(table3.firstname,''), table1.account;
-8358760 0 I think that the term you're looking for is Software Configuration Management. There's a pretty hefty document about it here too: http://www.sei.cmu.edu/reports/87cm004.pdf.
-4544859 0 How to display something from array with another name in PHP?I have one array that returns one element $name, and I want to display it with another name, For example:
$name = 'PC' and I want to display it as 'PC COMPUTER', first array displays element wich is true, how to compare this elements with another array to display it with that other names?
-13258264 0textBox1.Enter += new EventHandler(txtSearch_TextChanged); private void txtSearch_TextChanged(object sender, EventArgs e) { foreach (TreeNode node in this.treeView1.Nodes) { if (node.Text.ToUpper().Contains(this.textBox1.Text.ToUpper())) { treeView1.Select(); // First give the focus to the treeview control, //doing this, the control is able to show the selectednode. treeView1.SelectedNode = node; break; } }
-29242028 0 because your .column divs are float:left; you need a container with clear:both; after the columns:
<section> <h4>WHAT WE DO</h4> <h2>HEADING</h2> <div class="column"> <div class="item"></div> <h3>ITEM1</h3> <p>Necessitatibus ipsa ex hic sunt maxime.</p> </div> <div class="column"> <div class="item"></div> <h3>ITEM2</h3> <p>Molestias ipsum ex deleniti illo qui obcaecati repellat.</p> </div> <div class="column"> <div class="item"></div> <h3>ITEM3</h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p> </div> <div class="clearer"></div> </section> CSS
.clearer { clear:both; } http://codepen.io/anon/pen/myvwNY
Without the clear the container the floating divs are in has no height.
Jesse Gallagher's Scaffolding framework also accesses Java objects rather than dominoDocument datasources. I've used (and modified) Tim Tripcony's Java objects in his "Using Java in XPages series" from NotesIn9 (the first is episode 132. The source code for what he does is on BitBucket. This basically converts the dominoDocument to a Map. It doesn't cover MIME (Rich Text) or attachments. If it's useful, I can share the amendments I made (e.g. making field names all the same case, to ensure it still works for existing documents, where fields may have been created with LotusScript).
-32993646 0 -24918970 0 Git GUI push button does not workI was copying my repository to github from my local computer using the command - git push origin master, after cd-ing into my repo directory.
When, I tried this using Git gui, I can scan for changes to the repo and commit them. But I cannot push them to my remote repository. How do I find out the reason for this error and how do I fix it ?
-40630263 0This is happening because you're calling message+= on a null string, so you're adding currentLine to null.
Simplest fix would be to set massage to "" when you initialise it:
String message = ""; //Rest of code...
-32441279 0 How can I add custom entries into iOS watchKit extension info.plist? I use info.plist to define variables into my app and its today extension.
But I can't add those variables to the WatchKit info.plist without getting an error while building :
Am I missing something?
(xCode 7.0 beta 6)
-10589688 0If what you're talking about is the space in between each box, the class "box" is inline-block, so the line-breaks in the markup are interpreted as implied spaces. Place all the inline-block markup on a single line <div></div><div></div>... and the "space" between will collapse.
I am new to the whole GWT thing and for a project I need to read a serverside file via an asynchronous call and return an array of data to the client. So far I followed an RPC tutorial and implemented the server and client side code as well as the web.xml file but when I try to RPC the DataExtraction method on my client, it will result in the following error:
javax.servlet.ServletContext log: Exception while dispatching incoming RPC call com.google.gwt.user.server.rpc.UnexpectedException: Service method 'public abstract int[] ch.uzh.ifi.se.swela.client.DataExtractorService.extract(java.lang.String) throws java.io.IOException' threw an unexpected exception: java.security.AccessControlException: access denied ("java.io.FilePermission" "/SE Swiss Election App/war/tables/Ferien_K.csv" "read")
This is the call:
DataExtractorServiceClientImpl clientImpl = new DataExtractorServiceClientImpl(GWT.getModuleBaseURL() + "dataExtractor"); clientImpl.extract("/SE Swiss Election App/war/tables/Ferien_K.csv"); For me it seems like, that the server does not have the permission to open the file, but how would I fix that? Thank you in advance.
-9614206 0Without knowing the contents of 'BBnormalLinks.txt' or the final value of $rand_link, it is difficult to say precisely what is going wrong.
Your usage of file() and mt_rand() appear to be correct, though you aren't doing anything to ensure that you are getting a valid URL.
This is purely conjecture, but I suspect that you don't have PHP properly configured to display errors. If the file fails to load, $links will have a null value going into your penultimate line. You will then try to access element 0 of a null array and receive an empty value. This will result in header('refresh:2;url=') and your page will simply refresh itself every 2 seconds.
Unwind has it right, except you should use 'sendto'
Here is an example, that assumes you already have a socket. It was taken from clamav
static void broadcast(const char *mess) { struct sockaddr_in s; if(broadcastSock < 0) return; memset(&s, '\0', sizeof(struct sockaddr_in)); s.sin_family = AF_INET; s.sin_port = (in_port_t)htons(tcpSocket ? tcpSocket : 3310); s.sin_addr.s_addr = htonl(INADDR_BROADCAST); cli_dbgmsg("broadcast %s to %d\n", mess, broadcastSock); if(sendto(broadcastSock, mess, strlen(mess), 0, (struct sockaddr *)&s, sizeof(struct sockaddr_in)) < 0) perror("sendto"); }
-3882575 0 Have you tried pyqver? It will tell you which is the minimum version of Python required by your code
I hope it helps
-38674591 0enter code hereDemo:
http://jsfiddle.net/subhash9/fRUUd/1511/ Code $(".scrollbar").animate({ scrollTop: 1000 }, 2000);
I used sequoyah plug-in until now to debug both Java & native code simultaneously. It worked However I am using ADT Build v21.0.0.1 - 543035, and I followed http://tools.android.com/recent/usingthendkplugin
As usual Google seems to be ignoring native developers, and provide very little information how to debug both Java and Native code simultaneously seamlessly, if any one has insights please provide the information.
-15115077 0 Adding the Image in bundle to the UIImageView using GPU Image?I am very new to the user of GPU Image Framework. In my application I use the following code to get the filter effect of the Image in bundle(knee.png) , But I get only Black ImageView . I get the code from this link
show me where I went wrong
UIImage *inputImage = [UIImage imageNamed:@"knee.png"]; GPUImagePicture *stillImageSource = [[GPUImagePicture alloc] initWithImage:inputImage]; GPUImageSepiaFilter *stillImageFilter = [[GPUImageSepiaFilter alloc] init]; [stillImageSource addTarget:stillImageFilter]; [stillImageSource processImage]; UIImage *quickFilteredImage = [stillImageFilter imageByFilteringImage:inputImage]; [self.imgView setImage:quickFilteredImage];
-40463680 0 Resolution:
SC can not determine the .env or phpunit.xml in this case, so i have to specify it in my web Test Case setup method:
putenv('DB_DATABASE=db_name'); putenv('DB_USERNAME=postgres'); putenv('DB_PASSWORD=postgres'); putenv('DB_CONNECTION=pgsql'); putenv('DB_PORT=5432'); the most important variable is DB_CONNECTION.
You should try this simple solution :
jQuery(function($) { $('form input').on('change',function() { isDisabled = !(($('#txtusername').val().length > 0 && $('#txtpassword').val().length > 0) || $('input[type="checkbox"]:checked').length > 0); $('#signin').attr('disabled', isDisabled); }); }); It does its job.
-34427474 0 Centering image in columns (liquid layout)My goal is to make each of these images be centered in their respective columns while maintaining the liquid layout. Each of the images should be centered in each column (e.g. one flag per column centered). Any help would be appreciated as this is an assignment. Thanks
HTML and CSS Code
.two { -moz-column-count: 2; -webkit-column-count: 2; column-count: 2; } .column1 { width:33%; float:left; } .column2 { width:33%; display: inline-block; } .column3 { width:33%; float:right; } <p class="two"> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eosle et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p> <p class="column1"> <img src="australia_flag.jpg" height="200" width="300" /> <br>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eosle et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. </p> <p class="column2"> <img src="brazil_flag.jpg" height="200" width="300" /> <br>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eosle et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. </p> <p class="column3"> <img src="china_flag.jpg" height="200" width="300" /> <br>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eosle et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. </p> Thanks!
-8326335 0@m_UserIdList is a VARCHAR(500), not a list of values, so this will not work. You can try and parse the passed in string into a table (and there are plenty of ways of doing so - just search this site).
However, since you are using SQL Server 2008, you should take a look at table valued parameters - these allow you to pass a table of values to a stored procedure.
-9471576 0 Extract first word in a SQLite3 databaseI have a SQLITE3 database wherein I have stored various columns. One column (cmd) in particular contains the full command line and associated parameters. Is there a way to extract just the first word in this column (just before the first space)? I am not interested in seeing the various parameters used, but do want to see the command issued.
Here's an example:
select cmd from log2 limit 3;
user-sync //depot/PATH/interface.h user-info user-changes -s submitted //depot/PATH/build/...@2011/12/06:18:31:10,@2012/01/18:00:05:55 From the result above, I'd like to use an inline SQL function (if available in SQLITE3) to parse on the first instance of space, and perhaps use a left function call (I know this is not available in SQLITE3) to return just the "user-sync" string. Same for "user-info" and "user-changes".
Any ideas?
Thanks.
-19791954 0I experienced the same thing. An alternative would be to add a Label control and set the properties on that instead.
Rather than using a BoundField, use a TemplateField. Assuming that your data is returning an indexable item:
<asp:GridViewControl runat="server" ID="GridView2" AutoGenerateColumns="false"> <asp:BoundField HeaderText="Field0" DataField="[0]" /> <asp:BoundField HeaderText="Field1" DataField="[1]" /> <asp:TemplateField HeaderText="Monkey1" /> <asp:TemplateField HeaderText="Monkey2" /> </asp:GridViewControl> Then in the code-behind:
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { var data_item = e.Row.DataItem; // Can use "as <type>;" if you know the type. if (data_item != null) { for (int i = 2; i <= 3; i++) { var cell_content = new Label(); e.Row.Cells[i].Controls.Add(cell_content); cell_content.Text = data_item[i]; if (data_item[i].Contains("monkey")) { cell_content.Attributes.Add("class", "monkey bold"); } else { cell_content.Attributes.Add("class", "nomonkey bold"); } } } Of course an alternative would be to add the Label in the TemplateField -> ItemTemplate declaration with an ID and use "Cells[i].FindControl("label_id")".
-2036205 0I'd strongly recommend using the C99 <stdint.h> header. It declares int32_t, int64_t, uint32_t, and uint64_t, which look like what you really want to use.
EDIT: As Alok points out, int_fast32_t, int_fast64_t, etc. are probably what you want to use. The number of bits you specify should be the minimum you need for the math to work, i.e. for the calculation to not "roll over".
The optimization comes from the fact that the CPU doesn't have to waste cycles realigning data, padding the leading bits on a read, and doing a read-modify-write on a write. Truth is, a lot of processors (such as recent x86s) have hardware in the CPU that optimizes these access pretty well (at least the padding and read-modify-write parts), since they're so common and usually only involve transfers between the processor and cache.
So the only thing left for you to do is make sure the accesses are aligned: take sizeof(int_fast32_t) or whatever and use it to make sure your buffer pointers are aligned to that.
Truth is, this may not amount to that much improvement (due to the hardware optimizing transfers at runtime anyway), so writing something and timing it may be the only way to be sure. Also, if you're really crazy about performance, you may need to look at SSE or AltiVec or whatever vectorization tech your processor has, since that will outperform anything you can write that is portable when doing vectored math.
-19454923 0Most people would prevent the form from submitting by calling the event.preventDefault() function.
Another means is to remove the onclick attribute of the button, and get the code in processForm() out into .submit(function() { as return false; causes the form to not submit. Also, make the formBlaSubmit() functions return Boolean based on validity, for use in processForm();
katsh's answer is the same, just easier to digest.
(By the way, I'm new to stackoverflow, give me guidance please. )
-26986591 0 Angularjs: access template in directiveWhat I want to do is to append compiled template to some other DOM element in Angualrjs directive. Is it possible? How?
I know you can use transclude to include the template and keep content in the tag, but how do I attach my compiled template to other DOM element?
angular.module("my.directive") .directive('passwordStrength', [function(){ return { templateUrl: '/tpl/directive/passwordStrength.html', restrict: 'A', link: function postLink(scope, iElement, iAttrs){ console.log('password strength is running'); iElement.append($template) // problem here!!! } }; }]);
-31756697 0 I've got no idea how FactoryBoy works, but this strategy usually works for me when I need dynamic properties on fields in Django models:
def FooContainerFactory(factory.Factory): def __init__(self, count=20, *args, **kwargs): self.foos = factory.List([Foo() for _ in range(20)]) super(FooContainerFactory, self).__init__(*args, **kwargs) class Meta: model = FooContainerModel
-26230328 0 Try changing it to this;
<% @events.each do |e| %> <%= link_to '<i class=icon-trash></i>'.html_safe, account_show_path(@context, @event), :confirm => 'Are you sure?', :method => :delete %> <% end %> Make sure you have the following in your header;
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %> <%= csrf_meta_tags %>
-27396825 0 Try This:-
$('body').on('focus', '.datepicker_input', function() { $(this).datepicker({ dateFormat: 'dd-MM-yy', defaultDate: $(this).val(), ... }); });
-19977766 0 Looking at your desired output, you are looking for the crossprod function:
crossprod(table(test1)) # product # product p1 p2 p3 p4 # p1 4 1 1 0 # p2 1 3 1 0 # p3 1 1 4 1 # p4 0 0 1 2 This is the same as crossprod(table(test1$user, test1$product)) (reflecting Dennis's comment).
As far as syntax goes, you can use the null-coalescing operator if you want to be fancy, but it's not necessarily as readable.
get { return notes ?? (notes = CalcNotes()); } Edit: Updated courtesy of Matthew. Also, I think the other answers are more helpful to the question asker!
-27775846 0I have solved the issue by changing this line:
lblImageName = [[UILabel alloc] initWithFrame:CGRectMake(cell.frame.origin.x, cell.frame.origin.y, 200, 200)]; to:
lblImageName = [[UILabel alloc] initWithFrame:CGRectMake(0,0, 200, 200)];
-39978386 0 This has been tested and works:
override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) tableView.contentSize.height = 2000 }
-142640 0 Not with the default Route class, but you can make your own route class by deriving from RouteBase. You basically end up having to do all the work yourself of parsing the URL, but you can use the source from Route to help you get started.
-14975130 0 iOS crash logs printed to consoleMy problem appeared when iOS 6 was introduced, but now seems to affect 5.1.1 too.
When the app crashes, the log is printed to the 'Console' and no 'Device Logs' is saved. This is frustrating in so many ways:
It may be worth mentioning, that we work with accessories and have no way to connect debugger at the same time.
An idea how to fix this would save my day, but any decent workaround will be good too.
Thank you
EDIT: 'Console' and 'Device Logs' are the ones I get in the Organizer.
-1476139 0I would second jQTouch. It uses native CSS animations and behaves reasonably smoothly on my iPod Touch.
-20134891 0 SKPhysicsBody bodyWithPolygonFromPath memory leaksI have a strange memory leaks when creating Sprite Kit physics bodies with custom shapes. This is how my implementation looks:
CGFloat offsetX = self.frame.size.width * self.anchorPoint.x; CGFloat offsetY = self.frame.size.height * self.anchorPoint.y; CGMutablePathRef path = CGPathCreateMutable(); CGPathMoveToPoint(path, NULL, 4 - offsetX, 3 - offsetY); CGPathAddLineToPoint(path, NULL, 66 - offsetX, 3 - offsetY); CGPathAddLineToPoint(path, NULL, 35 - offsetX, 57 - offsetY); CGPathCloseSubpath(path); self.physicsBody = [SKPhysicsBody bodyWithPolygonFromPath:path]; CGPathRelease(path); Everything is going on inside SKSpriteNode method. Instruments tells me about several memory leaks after creating such bodies:
Leaked object: Malloc 32 Bytes Size: 32 Bytes Responsible Library: PhysicsKit Responsible Frame: std::__1::__split_buffer<PKPoint, std::__1::allocator<PKPoint>&>::__split_buffer(unsigned long, unsigned long, std::__1::allocator<PKPoint>&) The CGPathRelease(path); line is necessary - without it I'm getting more memory leaks about CGPath which is understandable. When I'm using this implementation instead (for testing purposes):
CGFloat radius = MAX(self.frame.size.width, self.frame.size.height) * 0.5f; self.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:radius]; ...everything is working well, without memory leaks. I wonder if this is Sprite Kit bug or I'm doing something wrong.
-29792746 0This maybe a difficult one for someone with limited Alfresco knowledge, so hopefully you'll understand it.
First change the custom control which selects the assignee. This control goes to a repository webscript which shows/searches all the users/groups.
-23913212 0Please change your
default_validation_class = UTF8Type to default_validation_class = LongType It should work.
-17796347 0Unfortunately, no, this isn't currently possible in an official or supported way. These shared links don't offer any metadata or API for access like this.
-1797502 0 Is there a scala identity function?If I have something like a List[Option[A]] and I want to convert this into a List[A], the standard way is to use flatMap:
scala> val l = List(Some("Hello"), None, Some("World")) l: List[Option[java.lang.String]] = List(Some(Hello), None, Some(World)) scala> l.flatMap( o => o) res0: List[java.lang.String] = List(Hello, World) Now o => o is just an identity function. I would have thought there'd be some way to do:
l.flatMap(Identity) //return a List[String] However, I can't get this to work as you can't generify an object. I tried a few things to no avail; has anyone got something like this to work?
Well you could use python itself to reverse the line through the filter command. Say the text you had written was:
Python You could reverse it by issuing.
:1 ! python -c "print raw_input()[::-1]" And your text will be replaced to become:
nohtyP The "1" in the command tells vi to send line 1 to the python statement which we are executing: "print raw_input()[::-1]". So if you wanted some other line reversed, you would send that line number as argument. The python statement then reverses the line of input.
-19262644 0 How to pass a NSMutableArray including NSManagedObjects to another view controller?I embedded 'Core Data' into my app. I use a predicate and fetch the result. I use a mutableArray called "fetchedObjects" to get the (predicated and then fetched) result. Now I need to pass this result to another view controller. How can I do that?
1.First thing I tried is using 'NSCoding' but it didn't work out. I think Core Data doesn't comply with NSCoding, am I right?
If I can use 'NSCoding', how do I do it? I tried to save and then load the fetchedObjects but it didn't work out.
2.Off course I can define a pointer using
"product = [[Product alloc] initWithEntity:entity insertIntoManagedObjectContext:self.managedObjectContext];" but how can I get just the "fetchedObjects" mutableArray but not all the objects?
3.Do you know a better way to pass a NSMutableArray having NSManagedObjects in it? and how can we pass the NSManagedObjects to the other view controllers, only in the context?
Thanks!
-24859051 0It is a shorthand way to reference to the route, by using
@Html.RouteLink("Privacy"); Here an article on ASP.NET about routing, which helped me a lot...
ASP.NET MVC Routing Overview (C#)
-21812622 0Try with something like this
db.collectionName.find({:barsIds => {"$in" => BSON::ObjectId("5300c6ba4a5ce5614bcd5d9a")}})
-18886564 0 You can inspect the page to find out all the fields need to be posted. There is a nice tutorial for Chrome DevTools. Other tools like FireBug on FireFox or DragonFly on Opera also do the work while I recommend DevTools.
After you post a query. In the Network panel, you can see the form data which actually been sent. In this case:
__EVENTTARGET: __EVENTARGUMENT: __LASTFOCUS: __VIEWSTATE:5UILUho/L3O0HOt9WrIfldHD4Ym6KBWkQYI1GgarbgHeAdzM9zyNbcH0PdP6xtKurlJKneju0/aAJxqKYjiIzo/7h7UhLrfsGul1Wq4T0+BroiT+Y4QVML66jsyaUNaM6KNOAK2CSzaphvSojEe1BV9JVGPYWIhvx0ddgfi7FXKIwdh682cgo4GHmilS7TWcbKxMoQvm9FgKY0NFp7HsggGvG/acqfGUJuw0KaYeWZy0pWKEy+Dntb4Y0TGwLqoJxFNQyOqvKVxnV1MJ0OZ4Nuxo5JHmkeknh4dpjJEwui01zK1WDuBHHsyOmE98t2YMQXXTcE7pnbbZaer2LSFNzCtrjzBmZT8xzCkKHYXI31BxPBEhALcSrbJ/QXeqA7Xrqn9UyCuTcN0Czy0ZRPd2wabNR3DgE+cCYF4KMGUjMUIP+No2nqCvsIAKmg8w6Il8OAEGJMAKA01MTMONKK4BH/OAzLMgH75AdGat2pvp1zHVG6wyA4SqumIH//TqJWFh5+MwNyZxN2zZQ5dBfs3b0hVhq0cL3tvumTfb4lr/xpL3rOvaRiatU+sQqgLUn0/RzeKNefjS3pCwUo8CTbTKaSW1IpWPgP/qmCsuIovXz82EkczLiwhEZsBp3SVdQMqtAVcYJzrcHs0x4jcTAWYZUejvtMXxolAnGLdl/0NJeMgz4WB9tTMeETMJAjKHp2YNhHtFS9/C1o+Hxyex32QxIRKHSBlJ37aisZLxYmxs69squmUlcsHheyI5YMfm0SnS0FwES5JqWGm2f5Bh+1G9fFWmGf2QeA6cX/hdiRTZ7VnuFGrdrJVdbteWwaYQuPdekms2YVapwuoNzkS/A+un14rix4bBULMdzij25BkXpDhm3atovNHzETdvz5FsXjKnPlno0gH7la/tkM8iOdQwqbeh7sG+/wKPqPmUk0Cl0kCHNvMCZhrcgQgpIOOgvI2Fp+PoB7mPdb80T2sTJLlV7Oe2ZqMWsYxphsHMXVlXXeju3kWfpY+Ed/D8VGWniE/eoBhhqyOC2+gaWA2tcOyiDPDCoovazwKGWz5B+FN1OTep5VgoHDqoAm2wk1C3o0zJ9a9IuYoATWI1yd2ffQvx6uvZQXcMvTIbhbVJL+ki4yNRLfVjVnPrpUMjafsnjIw2KLYnR0rio8DWIJhpSm13iDj/KSfAjfk4TMSA6HjhhEBXIDN/ShQAHyrKeFVsXhtH5TXSecY6dxU+Xwk7iNn2dhTILa6S/Gmm06bB4nx5Zw8XhYIEI/eucPOAN3HagCp7KaSdzZvrnjbshmP8hJPhnFhlXdJ+OSYDWuThFUypthTxb5NXH3yQk1+50SN872TtQsKwzhJvSIJExMbpucnVmd+V2c680TD4gIcqWVHLIP3+arrePtg0YQiVTa1TNzNXemDyZzTUBecPynkRnIs0dFLSrz8c6HbIGCrLleWyoB7xicUg39pW7KTsIqWh7P0yOiHgGeHqrN95cRAYcQTOhA== __SCROLLPOSITIONX:0 __SCROLLPOSITIONY:106 __VIEWSTATEENCRYPTED: __EVENTVALIDATION:g2V3UVCVCwSFKN2X8P+O2SsBNGyKX00cyeXvPVmP5dZSjIwZephKx8278dZoeJsa1CkMIloC0D51U0i4Ai0xD6TrYCpKluZSRSphPZQtAq17ivJrqP1QDoxPfOhFvrMiMQZZKOea7Gi/pLDHx42wy20UdyzLHJOAmV02MZ2fzami616O0NpOY8GQz1S5IhEKizo+NZPb87FgC5XSZdXCiqqoChoflvt1nfhtXFGmbOQgIP8ud9lQ94w3w2qwKJ3bqN5nRXVf5S53G7Lt+Du78nefwJfKK92BSgtJSCMJ/m39ykr7EuMDjauo2KHIp2N5IVzGPdSsiOZH86EBzmYbEw== ctl00$MainContent$hdnApplyMasterPageWitoutSidebar:0 ctl00$MainContent$hdn1:0 ctl00$MainContent$CorpSearch:rdoByEntityName ctl00$MainContent$txtEntityName:GO ctl00$MainContent$ddBeginsWithEntityName:M ctl00$MainContent$ddBeginsWithIndividual:B ctl00$MainContent$txtFirstName: ctl00$MainContent$txtMiddleName: ctl00$MainContent$txtLastName: ctl00$MainContent$txtIdentificationNumber: ctl00$MainContent$txtFilingNumber: ctl00$MainContent$ddRecordsPerPage:25 ctl00$MainContent$btnSearch:Search Corporations ctl00$MainContent$hdnW:1920 ctl00$MainContent$hdnH:1053 ctl00$MainContent$SearchControl$hdnRecordsPerPage: What I post is Begin with 'GO'. This site is build with WebForms, so there are these long __VIEWSTATE and __EVENTVALIDATION fields. We need send them as well.
Now we are ready to make the query. First we need to get a blank form. The following code are written in Python 3.3, through I think they should still work on 2.x.
import requests from lxml import etree URL = 'http://corp.sec.state.ma.us/CorpWeb/CorpSearch/CorpSearch.aspx' def get_fields(): res = requests.get(URL) if res.ok: page = etree.HTML(res.text) fields = page.xpath('//form[@id="Form1"]//input') return { e.attrib['name']: e.attrib.get('value', '') for e in fields } With get_fields(), we fetched all <input>s from the form. Note there are also <select>s, I will just hardcode them.
def query(data): formdata = get_fields() formdata.update({ 'ctl00$MainContent$ddRecordsPerPage':'25', }) # Hardcode some <select> value formdata.update(data) res = requests.post(URL, formdata) if res.ok: page = etree.HTML(res.text) return page.xpath('//table[@id="MainContent_SearchControl_grdSearchResultsEntity"]//tr') Now we have a generic query function, lets make a wrapper for specific ones.
def search_by_entity_name(entity_name, entity_search_type='B'): return query({ 'ctl00$MainContent$CorpSearch':'rdoByEntityName', 'ctl00$MainContent$txtEntityName': entity_name, 'ctl00$MainContent$ddBeginsWithEntityName': entity_search_type, }) This specific example site use a group of <radio> to determine which fields to be used, so 'ctl00$MainContent$CorpSearch':'rdoByEntityName' here is necessary. And you can make others like search_by_individual_name etc. by yourself.
Sometimes, website need more information to verify the query. By then you could add some custom headers like Origin, Referer, User-Agent to mimic a browser.
And if the website is using JavaScript to generate forms, you need more than requests. PhantomJS is a good tool to make browser scripts. If you want do this in Python, you can use PyQt with qtwebkit.
Update: It seems the website blocked our Python script to access it after yesterday. So we have to feign as a browser. As I mentioned above, we can add a custom header. Let's first add a User-Agent field to header see what happend.
res = requests.get(URL, headers={ 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36', }) And now... res.ok returns True!
So we just need to add this header in both call res = requests.get(URL) in get_fields() and res = requests.post(URL, formdata) in query(). Just in case, add 'Referer':URL to the headers of the latter:
res = requests.post(URL, formdata, headers={ 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36', 'Referer':URL, })
-20061078 0 Finding cache cpi time I need a formula or to at least be pointed in the right direction it involves cache and cpi time. I have a base machine that has a 2.4ghz clock rate it has L1 and L2 cache. L1 is 256k direct mapped write through . 90% read without a hit rate without penalty, miss penalty costs 4 cycles all writes take 1 cycle. L2 cache is 2mb, 4 way set associative write back. 99.5% hit rate 60 cycle miss penalty. 30% of all instructions are reads and 10% are writes all other instructions take one cycle.. I need to figure how to get the cpi. I know i have to find the base cpi but from there I'm not really sure where to go. Any tips on not just what the answer is but how is more important would be greatly appreciated.
-38852460 0 Login page redirect new page if sucessMy application uses Mithril.js and Play Framework.
I would like to know if there is a (good) way to divide my application between mithril and play. I would like to have play renders a login.html, this login.html will only contain only the import of my mithril.js component (login.js). If the login is a success I would like play to redirect my application to another html page. This pages will contain all the imports of all my mithril's components.
So my application will have only two html pages on the play framework side, one which imports only one mithril component and the other which import all the others components (only if credentials are checked).
Play router :
GET / controllers.Index.index
Play controller :
def index = Action { Ok(views.html.login()) }
login.html
<!DOCTYPE html> <html lang="en"> <head> <title>IHM</title> StylesSheet import.. </head> <body id="app" class="body"> <script src="https://cdnjs.cloudflare.com/ajax/libs/mithril/0.2.2-rc.1/mithril.min.js"></script> <script src="@routes.Assets.versioned("javascripts/claravista/login.js")" type="text/javascript"></script> <script type="text/javascript"> m.route.mode = "pathname"; m.route(document.getElementById('app'), "/", { "/": login, }); </script> </body> Mithril ask play check credentials (in component login)
m.request({method: "PUT", url: "/check-user", data : login.user }).then(returnCall);
Case Credentials false : ask again (I already did this part)
Case Credentials true : redirect to another html page (How to do this?)
<!DOCTYPE html> <html lang="en"> <head> <title>IHM</title> </head> <body id="appmain" class="body"> <script src="https://cdnjs.cloudflare.com/ajax/libs/mithril/0.2.2-rc.1/mithril.min.js"></script> ALL MY MITHRIL COMPONENTS IMPORT <script type="text/javascript"> m.route.mode = "pathname"; m.route(document.getElementById('appmain'), "/main", { "/main": main, }); </script>
How can I redirect to another html page after credentials are checked? Is there a better way to prevent the server to send all the JavaScript files before the user is logged?
-40367483 1 Python determine whether an exception was thrown (regardless of whether it is caught or not)I am writing tests for some legacy code that is littered with catch-all constructs like
try: do_something() do_something_else() for x in some_huge_list(): do_more_things() except Exception: pass and I want to tell whether an exception was thrown inside the try block.
I want to avoid introducing changes into the codebase just to support a few tests and I don't want to make the except cases more specific for fear of unintentionally introducing regressions.
Is there a way of extracting information about exceptions that were raised and subsequently handled from the runtime? Or some function with a similar API to eval/exec/apply/call that either records information on every raised exception, lets the user supply an exception handler that gets run first, or lets the user register a callback that gets run on events like an exception being raised or caught.
If there isn't a way to detect whether an exception was thrown without getting under the (C)Python runtime in a really nasty way, what are some good strategies for testing code with catch-all exceptions inside the units you're testing?
-23044176 0I am not an VB.NET expert, but usually getting access to clipboard isn't as easy as it looks.
Check this:
It can be only a tip, not really solution. Look into your clipboard functionallity

I want present a UINavigationController like the image above, I use
nvc.modalPresentationStyle = UIModalPresentationFormSheet; But I can't change the controller's size.
This is how I did:
UIViewController *vc = [[UIViewController alloc] init]; vc.view.backgroundColor = [UIColor grayColor]; UINavigationController *nvc = [[UINavigationController alloc] initWithRootViewController:vc]; nvc.modalPresentationStyle = UIModalPresentationFormSheet; nvc.view.frame = CGRectInset(self.view.bounds, 20, 20); [self presentViewController:nvc animated:YES completion:nil]; But the present viewController is still full screen.
-30548400 0Twitter's Tweet Web Intent doesn't provide this functionality. You'd have to build a solution using either the REST or Streaming APIs. Even that would only work if the user's Tweets are public, or if they give you read access to their timeline.
-6128038 0There are many scenarios when you need culture based formatting.
For example: - Number Format
5.25 in English is written as 5,25 in French
So, if you want to display French formatted number in your program which is in English culture the culture based string format comes into action.
You can somehow try to compress the information somehow. You need to show the user if he has read a post, only if the user logs on, so you should store the information somewhere near the user. The user might look throught your posts in a date sorted way, so read-post-information of nearly dates should ly nearby, for efficient caching and reading of many values.
Try a table with this stucture:
Depending on how many posts you expect, you might use week or day instead of month. If you cache the value in your app, you might see a performance increase when displaying many posts.
-7892197 0How often these images change is not up to Amazon but depends entirely on the publishers.
I work for a publishing house and I can tell you from personal experience that a book cover can change quite frequently before going into print. Once it's available as physical product though (i.e. no more pre-order), it will remain the same until the next edition is published.
-17730157 0To animate you'll need to define a starting state, and a target (or finished) state and an easing function to control the rate of change.
Rather than start from scratch I'd suggest leveraging an existing solution, there is a LOT of code out there to help you do this.
Check out: https://github.com/sole/tween.js
-34707711 0 How do I get two things to hit each other and then remove one from the scene?I have four colored bars aligned horizontally. I also have some of the exact colors falling from the top of the screen which need to be matched with the bars at the bottom and then removed from the scene on contact. (If falling yellow bar hits bottom yellow bar, remove falling yellow bar from the scene) So, should I have eight different cases for each node in an enum instead of four? This is what it looks like now:
enum Bodies: UInt32 { case blueBar = 1 case redBar = 2 case yellowBar = 4 case greenBar = 8 } Some of them are not doing what they're supposed to which is why I'm asking. Thanks in advance.
-25357876 0 Replacing double quotes while sending parameter to javascript functionThis is JSFiddle :
I have button as follows:
<button class="buttoncss" title="Modify This Artifact File" onclick="setFileDescriptionForUpdate('!@#$%^&*()_+-=~`{}|[]\:" ;'<>?,.="" ','state.dat','167','1','c:\\pp_artifactsuploadedfiles\evalid_318\state.dat');">Modify</button> in this on click i am calling setFileDescriptionForUpdate function whose first parameter is string and is as follows:
!@#$%^&*()_+-=~`{}|[]\:";'<>?,./ when " is involved in string it creates problem.
What changes i can make to avoid this??
Please help me.
-34727887 0Fixed it using some of the suggestions below.
$startDate = new DateTime(date("2012-4-1")); $endDate = new DateTime(date("Y-m-t", strtotime($startDate->format("Y-m-d")))); echo "The start date should be 2012-4-1: " . $startDate->format("Y-m-d") . "<br />"; echo "The end date should be 2012-4-30: " . $endDate->format("Y-m-d") . "<br />"; I've verified that this works.
-20214430 0 SSRS Date Parameter Not workingI have two parameters for the report "StartDate" and "EndDate" respectively. They work fine in the chart filter expressions , however when I use the same in the series expression as CDate(Parameters!Startdate.Value) > CDate(Fields!InAck.value) of the chart to compare against a date column in the dataset and calculate the series value for datediff, it doesn't return the values promptly .
-6686083 0 Alternatives to window.onloadIs there a different option than window.onload=function; or <body onload="function();"> to call a function after the page loads.
I have a script found on the net satisfies my needs, but it overrides window.onload, so this prevents me from using the native window.onload.
Are there any alternatives?
-2902943 0Why, you can still static assert with const int:
#define static_assert(e) extern char (*ct_assert(void)) [sizeof(char[1 - 2*!(e)])] static_assert( THIS_LIMIT > OTHER_LIMIT ) Also, use boost!
BOOST_STATIC_ASSERT( THIS_LIMIT > OTHER_LIMIT ) ... you'll get a lot nicer error messages...
-32415813 0As Luksprog mentioned in the comment, ListAdapter is not filterable, you would have either have to create a customAdapter by extending the listadapter and implementing filterable in that object, or use an adapter provided by the sdk that implementals filterable
-23457152 0 Will calling window.setInterval open a new thread in chrome?I've read that all browsers except chrome have javascript code running in a single thread. I'm not even sure if this is still true, but assuming it is: Will calling window.setInterval multiple times open multiple threads in chrome?
-36819186 0 Cloud Foundry compatibility with DBsI have a set of restful services connecting to Oracle , MySQL and Phoenix DBs. These are running on tomcat. I have to migrate these services to pivotal cloud foundry. Is it sufficient if I externalize the connection parameters potentially using cloud config server or env variables to connect to these databases or is there anything additional that I need to do? I assume any db which works with a java application deployed outside cloud foundry will work when the app is deployed to pivotal cloud foundry. Please correct me if my assumption is incorrect.
-31170162 0Note the Statement documentation says:
By default, only one ResultSet object per Statement object can be open at the same time.
Now, you have these statements in your program:
ResultSet resultset = statement.executeQuery("select * from customer where first_name = '" + first_name + "'") ; statement.executeQuery("select * from customer where last_name = '" + last_name + "'") ; statement.executeQuery("select * from customer_order where amount = '" + amount + "'") ; statement.executeQuery("select * from customer_order where date_created = '" + date_created + "'") ; statement.executeQuery("select * from customer_order where reference_number = '" + reference_number + "'") ; statement.executeQuery("select * from customer_order where invoice_number = '" + invoice_number + "'") ; statement.executeQuery("select * from customer_order where status = '" + status + "'") ; statement.executeQuery("select * from ordered_product where quantity = '" + quantity + "'") ; statement.executeQuery("select * from ordered_product where product_name = '" + product_name + "'") ; statement.executeQuery("select * from ordered_product where product_price = '" + product_price + "'") ; This means you are calling the executeQuery several times with the same Statement object. But you are only saving the result of the first execution into resultset.
That is, the ResultSet object that resultset refers to is the one from this statement:
statement.executeQuery("select * from customer where first_name = '" + first_name + "'") ; All the others that follow it are separate queries and are not stored in the same variable if that's what you thought you were doing. They just create the ResultSet object, and then it gets thrown away because you don't assign the result to any variable.
As soon as you call the second executeQuery, because only one ResultSet object is allowed, the ResultSet object stored in resultset is closed, and a new one is opened. Then another, and then another.
Anyway, after you go through all these statements, you get to the part where you check resultset.next(). But at this point, that object, as I said, has already been closed.
Basically, you should decide which of the queries you want to run, run only that particular query, and then you'll have a live, open ResultSet in resultset. And then you can fill it in.
In addition, the part that prints the values from the result set should be inside the else block. You placed them after the curly brace of that else, which means you'll have trouble when no rows are returned from the query, because you'll be trying to print them anyway.
Looking at your code it appears there are 2 errors with your JSON. In it's original for it produces the follwoing string:
{"guid" : "26fac319-604b-11e5-b1fe", "senderid" : "003001", "campaign" : Weekday_EGV_21Sept_4pm_Round2_Tier1_Part1}} You are missing quotes around that final field value of campaign and you have an extra } at the end. If you make the following change:
json_body = "{\"guid\" : \""+ guid+"\", \"senderid\" : \""+ senderid+"\", \"campaign\" : \""+ str(campaign)+"\"}" it should resolve the JsonParseException error.
-12711657 0you can publish the code under Apache License, however the runtime would be under GPL. Got any details?
-40970335 0 Writing to virtual memory in Windows without writing back to diskI have to deal with a huge amount of temporary data, which I don't wish to saved to disk wasting precious space.
Instead, I want is that I keep the data in virtual memory so that the data is only on disk temporarilly and discard it once the processing has finished.
Neither, 'Boost memory mapping' nor, 'Windows CreateFileMapping' works this way, and In both the cases the changes affect available disk space.
Is there any way to get it done?
-12809367 0 Android beta testing serviceI've developed android app and want to start some beta testing with as many users as possible. Are there web services to find mobile beta testers, preferrably volunteers?
-15072586 0If you check the WSDL file for your web service, the parameter should have minOccurs=0. That's why the SOAPUI request put the optional comments there.
Please use @XmlElement(required=true) to annotate your WebParam that is required.
Right; let's see what we have here.
First, the code has to be blocked as follows:
variable declarations cursor declarations handler declarations everything else So your DECLARE CURSOR c2 must appear between DECLARE CURSOR c1 and DECLARE CONTINUE HANDLER. Also, you only need one CONTINUE HANDLER because it takes effect from the point of declaration to the end of the procedure.
Next is the statement
INSERT INTO ip_ER_subtotal SELECT Starting_Pitcher, Game_Date, Game_Number, innings_pitched, 0.0 FROM starting_pitchers_game_log; The named columns in the SELECT clause are the columns you're selecting from, not the ones you're inserting into, so they have to be columns in the table starting_pitchers_game_log. Also, since the columns not being copied from starting_pitchers_game_log (that is, ip_total, er_total and era) all have default values, you could use a column list on the INSERT statement, like so:
INSERT INTO pitcher_stats_temp (Starting_Pitcher, Game_Date, Game_Number, innings_pitched, er) SELECT pitcher_id, game_date, game_seq, innings_pitched, runs FROM starting_pitchers_game_log; This saves typing, documents which columns you're actually inserting values into and insulates your INSERT statement from the physical order of columns in the source and target tables.
Next, once you finish the CURSOR c1 loop, don't truncate the table or you'll lose all the work you've just done! TRUNCATE TABLE deletes all rows currently in the table, and is used here to clear out the results of the previous run.
Finally, the two loops have to have different labels, say fetch_loop_1 and fetch_loop_2. You would also need to reset accum and end_of_cursor before entering the second loop. However, in this case I believe we can do everything in one loop with one cursor, which makes the code simpler and thus easier to maintain.
Here's the complete procedure:
DROP PROCEDURE IF EXISTS pitcher_stats_era; DELIMITER $$ CREATE PROCEDURE pitcher_stats_era() BEGIN DECLARE pit_id CHAR(10); DECLARE gdate DATE; DECLARE seq INT; DECLARE in_pit REAL; DECLARE er INT; DECLARE accum_ip REAL; DECLARE accum_er INT; DECLARE earned_run_avg REAL; DECLARE prev_year YEAR(4); DECLARE end_of_cursor BOOLEAN; DECLARE no_table CONDITION FOR SQLSTATE '42S02'; DECLARE c1 CURSOR FOR SELECT pitcher_id, game_date, game_seq, innings_pitched, earned_runs FROM pitcher_stats_temp ORDER BY pitcher_id, game_date, game_seq; DECLARE CONTINUE HANDLER FOR NOT FOUND SET end_of_cursor := TRUE; DECLARE EXIT HANDLER FOR no_table BEGIN SIGNAL no_table SET MESSAGE_TEXT = "Work table not initialized. Please call pitcher_stats_reset() before continuing", MYSQL_ERRNO = 1146; END; ------------------------------------------------------------------ -- The following steps are now performed by pitcher_stats_reset() ------------------------------------------------------------------ -- TRUNCATE TABLE ip_subtotal; -- Clear our work table for a new run -- Copy data from main table into work table -- INSERT INTO ip_subtotal -- (pitcher_id, game_date, game_seq, innings_pitched, earned_runs) -- SELECT pitcher_id, game_date, game_seq, -- IFNULL(innings_pitched, 0), -- replace NULL with 0, if -- IFNULL(runs, 0) -- column not initialized -- FROM starting_pitchers_game_log; --------------------------------------------------------------------- SET end_of_cursor := FALSE; -- reset SET prev_year := 0; -- reset control-break OPEN c1; fetch_loop: LOOP FETCH c1 INTO pit_id, gdate, seq, in_pit, er; IF end_of_cursor THEN LEAVE fetch_loop; END IF; -- check control-break conditions IF YEAR(gdate) != prev_year THEN SET accum_ip := 0.0; SET accum_er := 0; SET prev_year := YEAR(gdate); END IF; SET accum_ip := accum_ip + in_pit; SET accum_er := accum_er + er; IF accum_er = 0 THEN -- prevent divide-by-zero SET earned_run_avg := 0; ELSE SET earned_run_avg := (accum_ip / accum_er) * 9; END IF; UPDATE pitcher_stats_temp SET ip_total = accum_ip, er_total = accum_er, std_era = earned_run_avg WHERE pitcher_id = pit_id AND game_date = gdate AND game_seq = seq; END LOOP; CLOSE c1; END $$ DELIMITER ; That should do the job. If anyone finds a bug, by all means please point it out.
EDIT: I've just added some code to illustrate how to protect against nulls coming from the source table, and how to avoid a divide-by-zero on the ERA calculation.
EDIT: I've changed back to my original column and table names in order to reduce my own confusion.
EDIT: Code changed to be consistent with the answer to How can I add a column to a work table using a new stored procedure
-23620004 0 How can I select a specific jquery element value from inside a loop?I am trying to put a string value in an array based on their position in relation to all of the elements with a class name. I get an array of the indexes that I want to use now I want to use each of the index values to select the appropriate value.
$(function () { $("#date").datepicker(); $('input[name=date]').datepicker(); var dateInput = $("select[name='searchString']"); var theClassTime = $("input.TextBoxDate"); var checkedindex = []; var classday = []; $("input[name='selectedCourses']").each(function (i) { if (this.checked) { // this works fine checkedindex.push(parseInt(i)); // this is where I’m trying to select values based on index. var dayofclass = $(".TextBoxDate:eq(" + checkedindex[i] + ")"); classday.push(dayofclass); alert(classday); } }); }); Say checkedindex has values: 2,3,9 meaning at index 0 of checkedindex is 2, at 1=3 and at 2=9. I want to use 2, 3 and 9 to do something like this:
var dayofclass = $(".TextBoxDate:eq(" + checkedindex[i] + ")"); What am I doing wrong here?
-24355862 0You are looping through the arrays. The puts function on its own just makes that difficult to see. Try this:
arrays = [[1, 52], [30, 1], [2, 1]] arrays.each do |array| puts array.inspect end Output:
[1, 52] [30, 1] [2, 1] See also:
puts [1, 2, 3] Output:
1 2 3
-18526985 0 jquery single each() function for both radio and checkboxes I'm having requirement that to check each radio button and checkbox of same div that was checked/unchecked. I tried this and found some what uneasy to have too separate loops.
{ $('#div1 input[type=radio]').each(...); } and
{ $('#div1 input[type=CHECKBOX]').each(...); } Instead of calling 2 methods, how can I use single each function for both types?
{ //Like $('#div input[type=radio || CHECKBOX]') }
-40859730 0 create .ipa using command line tool with dynamic app icon I want to create an .ipa file for an iOS project with different base URL, app icon images and splash images using command line tool or else.
Is it feasible by which we can change app icons and splash images from some uploaded directories.
Like an admin panel, in which a table is shown where multiple sizes of app icon images can be upload and same as splash.
And there will be button to create IPA for a project.
-23502087 0We ran into this and after a lot of time trying to debug, I came across this: https://code.google.com/p/go/source/detail?r=d4e1ec84876c
This shifts the burden onto clients to read their whole response bodies if they want the advantage of reusing TCP connections.
So be sure you read the entire body before closing, there are a couple of ways to do it. This function can come in handy to close to let you see whether you have this issue by logging the extra bytes that haven't been read and cleaning the stream out for you so it can reuse the connection:
func closeResponse(response *http.Response) error { // ensure we read the entire body bs, err2 := ioutil.ReadAll(response.Body) if err2 != nil { log.Println("Error during ReadAll!!", err2) } if len(bs) > 0 { log.Println("Had to read some bytes, not good!", bs, string(bs)) } return response.Body.Close() } Or if you really don't care about the body, you can just discard it with this:
io.Copy(ioutil.Discard, response.Body)
-6761975 0 You could do it like this
sed -ne '/$engineinfo = engine_getinfo();/a\'$'\n''$engineinfo['engine']="asterisk";\'$'\n''$engineinfo['version']="1.6.2.11";'$'\n'';p' /var/lib/asterisk/bin/retrieve_conf Add -i for modification in place once you confirm that it works.
What does it do and how does it work?
First we tell sed to match a line containing your string. On that matched line we then will perform an a command, which is "append text".
The syntax of a sed a command is
a\ line of text\ another line ; Note that the literal newlines are part of this syntax. To make it all one line (and preserve copy-paste ability) in place of literal newlines I used $'\n' which will tell bash or zsh to insert a real newline in place. The quoting necessary to make this work is a little complex: You have to exit single-quotes so that you can have the $'\n' be interpreted by bash, then you have to re-enter a single-quoted string to prevent bash from interpreting the rest of your input.
EDIT: Updated to append both lines in one append command.
-39553320 0You have an incorrect understanding of the shared folder. It is not a place to put files you wish to have copied to the build output folder. The folder you are looking for is entitled assets those files will be copied to the output directory, dist for both dev and prod builds.
The shared directory is a place to put common (or shared) portions of your application, whether they be components, directives, pipes, classes or services.
-35945228 0 Find 4 minimal values in 4 __m256d registersI cannot figure out how to implement:
__m256d min(__m256d A, __m256d B, __m256d C, __m256d D) { __m256d result; // result should contain 4 minimal values out of 16 : A[0], A[1], A[2], A[3], B[0], ... , D[3] // moreover it should be result[0] <= result[1] <= result[2] <= result[2] return result; } Any ideas of how to use _mm256_min_pd, _mm256_max_pd and shuffles/permutes in a smart way?
==================================================
This where I got so far, after:
__m256d T = _mm256_min_pd(A, B); __m256d Q = _mm256_max_pd(A, B); A = T; B = Q; T = _mm256_min_pd(C, D); Q = _mm256_max_pd(C, D); C = T; D = Q; T = _mm256_min_pd(B, C); Q = _mm256_max_pd(B, C); B = T; C = Q; T = _mm256_min_pd(A, B); Q = _mm256_max_pd(A, B); A = T; D = Q; T = _mm256_min_pd(C, D); Q = _mm256_max_pd(C, D); C = T; D = Q; T = _mm256_min_pd(B, C); Q = _mm256_max_pd(B, C); B = T; C = Q; we have : A[0] < B[0] < C[0] < D[0], A[1] < B[1] < C[1] < D[1], A[2] < B[2] < C[2] < D[2], A[3] < B[3] < C[3] < D[3],
so the minimal value is among A's, second minimal is among A's or B's, ... Not sure where to go from there ...
========================================================
Second idea is that the problem is reducible to itself, but with 2 input __m256 elements. If this can be done, then just do min4(A,B) --> P, min4(C,D) --> Q, min4(P,Q) --> return value.
No idea how to that for two vectors though :)
=======================================================================
Update 2 : problem almost solved -- the following function computes 4 minimal values.
__m256d min4(__m256d A, __m256d B, __m256d C, __m256d D) { __m256d T; T = _mm256_min_pd(A, B); B = _mm256_max_pd(A, B); B = _mm256_permute_pd(B, 0x5); A = _mm256_min_pd(T, B); B = _mm256_max_pd(T, B); B = _mm256_permute2f128_pd(B, B, 0x1); T = _mm256_min_pd(A, B); B = _mm256_max_pd(A, B); B = _mm256_permute_pd(B, 0x5); A = _mm256_min_pd(A, B); T = _mm256_min_pd(C, D); D = _mm256_max_pd(C, D); D = _mm256_permute_pd(D, 0x5); C = _mm256_min_pd(T, D); D = _mm256_max_pd(T, D); D = _mm256_permute2f128_pd(D, D, 0x1); T = _mm256_min_pd(C, D); D = _mm256_max_pd(C, D); D = _mm256_permute_pd(D, 0x5); C = _mm256_min_pd(C, D); T = _mm256_min_pd(A, C); C = _mm256_max_pd(A, C); C = _mm256_permute_pd(C, 0x5); A = _mm256_min_pd(T, C); C = _mm256_max_pd(T, C); C = _mm256_permute2f128_pd(C, C, 0x1); T = _mm256_min_pd(A, C); C = _mm256_max_pd(A, C); C = _mm256_permute_pd(C, 0x5); A = _mm256_min_pd(A, C); return A; }; All that remains is to sort the values in increasing order inside A before return.
-11504746 0 MYSQL SELECT SUM() BY DATE IF NO MATCH RETURN 0I have connected three tables to each other. I'm querying keywords + statistics.
I need to get data out by date range, and if there is no data for that specific date range i would like it to return 0 statistics
Lets say my query is:
SELECT keyword,SUM(stat) FROM keywords WHERE date >='2012-07-10' GROUP BY keyword;
It would return
|my keyword 1|3|
|my keyword 2|6|
Example table content:
| id | keyword | stat | date | keywordGroup |
| 1 | my keyword 1 | 2 | 2012-07-11 | 1 |
| 2 | my keyword 1 | 1 | 2012-07-12 | 1 |
| 3 | my keyword 2 | 6 | 2012-07-11 | 1 |
| 4 | my keyword 3 | 10 | 2012-07-09 | 1 |
But there are some keywords which have no stats for that date range
but I would still like to get those keywords showing 0 as stats.
Like this:
|my keyword 1|3|
|my keyword 2|6|
|my keyword 3|0|
The problem is that the where clause blocks values that are not found, is there a workaround.
As I said I have three tables with relations, I use LEFT JOIN to query data, for simplification I left that part out of my example query.
Table: Campaigns
id
name
Table: KeywordGroup
id
name
campaign
Table: KeywordData
id
keyword
stat
date
keywordGroup
Ideally you have a static and perhaps a non-static create() functions. There is a clever way to accomplish this.
Define a SuperBase class. It needs a virtual destructor and a pure virtual create() function. You'll use pointers/references to this class for normal late-binding OOP behaviours.
Define a Base class template that inherits from SuperBase. Base's template parameter will be the type of the Derived class. Base will also have a traits class template with a static function called create(). This static create() function will create a default object with new. Using the trait's create() function, Base will define both a static_create() and the pure virtual SuperBase::create() functions.
Implement Derived by inheriting from Base<Derived>.
One this is done, if you know you are using a derived type, then you can write Derived::create() to statically create a new one. If not, then you can always use an instance's create() method. Polymorphism is not broken since SuperBase would have the polymorphic interface you need/want --Base<D> is simply a helper class that auto defines the static_create() and create() functions so you would not normally use Base<D> directly.
Sample code appears below:
#include <memory> #include <iostream> class SuperBase { public: virtual ~SuperBase() = default; virtual std::shared_ptr<SuperBase> create() const = 0; }; template <typename T> struct Base_Traits { static T* create() { return new T; } }; template <typename Derived, typename Traits=Base_Traits<Derived>> class Base : public SuperBase { public: // Define a static factory function... static std::shared_ptr<SuperBase> static_create() { return std::shared_ptr<SuperBase>{Traits::create()}; } // Define pure virtual implementation... std::shared_ptr<SuperBase> create() const override { return static_create(); } }; class Derived : public Base<Derived> { }; int main() { auto newone = Derived::static_create(); // Type known @ compile time auto anotherone = newone->create(); // Late binding; type not known @ compile time }
-13712584 0 Check if webpage loaded after opening it as a process in C#? I am opening different browsers using
ProcessStartInfo startBrowser = new ProcessStartInfo(internetbrowser, website); Process.Start(startBrowser); Which works great. However, I need to also know when the webpage has loaded. Is there a way that I can check this? Or even better, fire an event when the page is fully loaded?
Thanks
-11046005 0Your row variable is not the a tag, so there is no attribute href on it.
Try with this:
Element table = doc.select("table.table"); Elements links = table.getElementsByTag("a"); for (Element link: links) { String url = link.attr("href"); String text = link.text(); System.out.println(text + ", " + url); } This is pretty much extracted from the JSoup documentation
-30544241 0 $http.get method of angularJS doesnot accept 5th parameter in URL stringi am developing mobile application in cordova+angularJS in ionic framework. I am trying to send parameters in the get request body that is probably the request to get specific data based on input parameters. My query string is this:
var queryString = base_url + "get/requestChartData.php?userid=" + window.localStorage.userid + "&token=" + token + "&formid=" + formID + "&questionid=" + questionID + "&chart=" + chartType; $http.get(queryString, {}).success(function (data, status, headers, config) { ..... ... This request when i send to the server where PHP handles the request, send me back response as <b>Notice</b>: Undefined index: chart in....
and even on my firebug debugging console, on the get request link when i expand, it shows me only four parameters instead of five.
is there any limit of sending number of parameters in the get request as a query string???
at PHP side i am doing this:
$userid = trim($_REQUEST['userid']); $formid = trim($_REQUEST['formid']); $fieldName = trim($_REQUEST['questionid']); $chartType = trim($_REQUEST['chart']); $token = trim($_REQUEST['token']); i am not getting this one any resolution to it????
-13974013 0I think that it isn't possible...
I can only suggest to you something that can give you something to getting started on it.
Jquery, on a big HTML with scroll, how to capture only the visible part of the HTML?
or you can use this plug-in:
jQuery.fracs, see the demo: demo
Probably if you want to show a portion of HTML and get only this visible part you must think up something and probably you can't use iFrame.
-32571406 0Try to:
private void getUserFriendsFacebookIds() { GraphRequest request = new GraphRequest( AccessToken.getCurrentAccessToken(), "/me/friends", null, HttpMethod.GET, new GraphRequest.Callback() { public void onCompleted(GraphResponse response) { /* handle the result */ Log.d("-@-", "graph response " + response.getJSONObject()); if (response.getError() != null) { Log.e(TAG, "User data error: " + response.getError(), response.getError().getException()); } else { setUserFriends(response.getRawResponse()); } } } ); Bundle parameters = new Bundle(); parameters.putString("fields", "id,name"); request.setParameters(parameters); request.executeAsync(); } private void setUserFriends(String json) { FacebookFriendsInfo ff = new Gson().fromJson(json, FacebookFriendsInfo.class); Log.i(TAG, "User friends: " + ff); ... } To parse response try to use GSON library.
public class FacebookFriendsInfo { public List<Friend> data = new ArrayList<Friend>(); public String getIds() { StringBuilder sb = new StringBuilder(); for (Friend f : data) { sb.append(String.format("%d,", f.id)); } return sb.toString(); } @Override public String toString() { return "FacebookFriendsInfo{" + "data=" + data + '}'; } public class Friend { public long id; public String name; @Override public String toString() { return "Friend{" + "id=" + id + ", name='" + name + '\'' + '}'; } } }
-897206 1 Python cgi FieldStorage slow, alternatives? I have a python cgi script that receives files uploaded via a http post. The files can be large (300+ Mb). The thing is, cgi.FieldStorage() is incredibly slow for getting the file (a 300Mb file took 6 minutes to be "received"). Doing the same by just reading the stdin took around 15 seconds. The problem with the latter is, i would have to parse the data myself if there are multiple fields that are posted.
Are there any faster alternatives to FieldStorage()?
-15707074 0 Two dimensional array of objects in as3Is it possible to make array in as3 like this :
countdowns[bodyID][powerupName] = { time: powerup.getTime(), onRemove: onRemove }; I have been trying for hours but no luck.. Thanks
-1993827 0Upon quick googling, http://www.phpfour.com/blog/2009/02/php-payment-gateway-library-for-paypal-authorizenet-and-2checkout/ looks like it might work.
-4386925 0Unfortunately, we don't have the FindAncestor mode on the RelativeSource markup extension that WPF has, so you can't use that (this will be added in Silverlight 5). It's nasty, but you can give your UserControl element a name, and use ElementName binding to bind to the command on the object assigned to its DataContext.
For example:
<UserControl Name="root"> Then bind the command (using dot notation from the DataContext of the UserControl):
Command="{Binding Path=DataContext.MyCommand, ElementName=root}" Give that a try.
-33215403 0.addMarker, not .addMarkerscode snippet:
var mgr; var map; function initialize() { var mapOptions = { zoom: 4, center: new google.maps.LatLng(34.6479355684, -0.2292535), mapTypeId: google.maps.MapTypeId.SATELLITE }; map = new google.maps.Map(document.getElementById('resultcnn'), mapOptions); mgr = new MarkerManager(map); var locations = [ ['rabat', 33.906896, -6.263123], ['rabat2', 34.053993, -6.792237], ['agdal', 33.994469, -6.848702], ['casa', 33.587596, -7.657156], ['casa2', 33.531808, -7.674601], ['casa3', 33.58824, -7.673278], ['casa4', 33.542325, -7.578557], ['agadir', 30.433948, -9.600005], ['kech', 31.634676, -8.000164], ['oujda,', 34.689969, -1.912365], ['tanger,', 35.771586, -5.801868], ['JIJEL-ACHOUAT', 36.8, 5.883333333, 1], ['JIJEL-PORT', 36.81666667, 5.883333333, 2], ['SKIKDA', 36.88333333, 6.9, 3], ['ANNABA', 36.83333333, 7.816666667, 4], ['EL-KALA', 36.9, 8.45, 8], ['ALGER-PORT', 36.76666667, 3.1, 9], ['DELLYS', 36.91666667, 3.95, 10.4], ['DAR-EL-BEIDA', 36.68333333, 3.216666667, 12.08571429], ['TIZI-OUZOU', 36.7, 4.05, 13.77142857] ]; google.maps.event.addListener(mgr, 'loaded', function() { for (var i = 0; i < locations.length; i++) { var marker = new google.maps.Marker({ position: new google.maps.LatLng(locations[i][1], locations[i][2]), }); mgr.addMarker(marker, 5); } mgr.refresh(); }); } google.maps.event.addDomListener(window, 'load', initialize); html, body, #resultcnn { height: 100%; width: 100%; margin: 0px; padding: 0px } <script src="https://maps.googleapis.com/maps/api/js"></script> <script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markermanager/src/markermanager.js"></script> <div id="resultcnn"></div> No branch heads exist yet.
A Git repository has no branches until you make your first commit. A newly-initialized repository sets HEAD to refs/heads/master, but refs/heads/master won't exist or contain a commit pointer until after the first commit is made.
During a commit, Git dereferences the symbolic-ref HEAD to find the head of the current branch, and then updates that head with the commit hash supplied by git-commit-tree.
The end result is that git branch has nothing to report in a new repository. With no branch heads present, it simply terminates silently with an exit status of zero.
I have a Wpf application using Nhibernate. I want to see details of sent query to database by NHibernate Profiler. For initial startup, what should I do?
-15806112 0 Getting full path from an HTTP requestI would like to know how can I get the full path of an HTTP request.
If a have a request like http://localhost:8080/path1/path2 how can I get the full /path1/path2?
Using request.getContextPath() returns only the /path1 section.
I have an application that spends about 80% of its time computing the centroid of a large list (10^7) of high dimensional vectors (dim=100) using the Kahan summation algorithm. I have done my best at optimizing the summation, but it is still 20x slower than an equivalent C implementation. Profiling indicates that the culprits are the unsafeRead and unsafeWrite functions from Data.Vector.Unboxed.Mutable. My question is: are these functions really this slow or am I misunderstanding the profiling statistics?
Here are the two implementations. The Haskell one is compiled with ghc-7.0.3 using the llvm backend. The C one is compiled with llvm-gcc.
Kahan summation in Haskell:
{-# LANGUAGE BangPatterns #-} module Test where import Control.Monad ( mapM_ ) import Data.Vector.Unboxed ( Vector, Unbox ) import Data.Vector.Unboxed.Mutable ( MVector ) import qualified Data.Vector.Unboxed as U import qualified Data.Vector.Unboxed.Mutable as UM import Data.Word ( Word ) import Data.Bits ( shiftL, shiftR, xor ) prng :: Word -> Word prng w = w' where !w1 = w `xor` (w `shiftL` 13) !w2 = w1 `xor` (w1 `shiftR` 7) !w' = w2 `xor` (w2 `shiftL` 17) mkVect :: Word -> Vector Double mkVect = U.force . U.map fromIntegral . U.fromList . take 100 . iterate prng foldV :: (Unbox a, Unbox b) => (a -> b -> a) -- componentwise function to fold -> Vector a -- initial accumulator value -> [Vector b] -- data vectors -> Vector a -- final accumulator value foldV fn accum vs = U.modify (\x -> mapM_ (liftV fn x) vs) accum where liftV f acc = fV where fV v = go 0 where n = min (U.length v) (UM.length acc) go i | i < n = step >> go (i + 1) | otherwise = return () where step = {-# SCC "fV_step" #-} do a <- {-# SCC "fV_read" #-} UM.unsafeRead acc i b <- {-# SCC "fV_index" #-} U.unsafeIndexM v i {-# SCC "fV_write" #-} UM.unsafeWrite acc i $! {-# SCC "fV_apply" #-} f a b kahan :: [Vector Double] -> Vector Double kahan [] = U.singleton 0.0 kahan (v:vs) = fst . U.unzip $ foldV kahanStep acc vs where acc = U.map (\z -> (z, 0.0)) v kahanStep :: (Double, Double) -> Double -> (Double, Double) kahanStep (s, c) x = (s', c') where !y = x - c !s' = s + y !c' = (s' - s) - y {-# NOINLINE kahanStep #-} zero :: U.Vector Double zero = U.replicate 100 0.0 myLoop n = kahan $ map mkVect [1..n] main = print $ myLoop 100000 Compiling with ghc-7.0.3 using the llvm backend:
ghc -o Test_hs --make -fforce-recomp -O3 -fllvm -optlo-O3 -msse2 -main-is Test.main Test.hs time ./Test_hs real 0m1.948s user 0m1.936s sys 0m0.008s Profiling information:
16,710,594,992 bytes allocated in the heap 33,047,064 bytes copied during GC 35,464 bytes maximum residency (1 sample(s)) 23,888 bytes maximum slop 1 MB total memory in use (0 MB lost due to fragmentation) Generation 0: 31907 collections, 0 parallel, 0.28s, 0.27s elapsed Generation 1: 1 collections, 0 parallel, 0.00s, 0.00s elapsed INIT time 0.00s ( 0.00s elapsed) MUT time 24.73s ( 24.74s elapsed) GC time 0.28s ( 0.27s elapsed) RP time 0.00s ( 0.00s elapsed) PROF time 0.00s ( 0.00s elapsed) EXIT time 0.00s ( 0.00s elapsed) Total time 25.01s ( 25.02s elapsed) %GC time 1.1% (1.1% elapsed) Alloc rate 675,607,179 bytes per MUT second Productivity 98.9% of total user, 98.9% of total elapsed Thu Feb 23 02:42 2012 Time and Allocation Profiling Report (Final) Test_hs +RTS -s -p -RTS total time = 24.60 secs (1230 ticks @ 20 ms) total alloc = 8,608,188,392 bytes (excludes profiling overheads) COST CENTRE MODULE %time %alloc fV_write Test 31.1 26.0 fV_read Test 27.2 23.2 mkVect Test 12.3 27.2 fV_step Test 11.7 0.0 foldV Test 5.9 5.7 fV_index Test 5.2 9.3 kahanStep Test 3.3 6.5 prng Test 2.2 1.8 individual inherited COST CENTRE MODULE no. entries %time %alloc %time %alloc MAIN MAIN 1 0 0.0 0.0 100.0 100.0 CAF:main1 Test 339 1 0.0 0.0 0.0 0.0 main Test 346 1 0.0 0.0 0.0 0.0 CAF:main2 Test 338 1 0.0 0.0 100.0 100.0 main Test 347 0 0.0 0.0 100.0 100.0 myLoop Test 348 1 0.2 0.2 100.0 100.0 mkVect Test 350 400000 12.3 27.2 14.5 29.0 prng Test 351 9900000 2.2 1.8 2.2 1.8 kahan Test 349 102 0.0 0.0 85.4 70.7 foldV Test 359 1 5.9 5.7 85.4 70.7 fV_step Test 360 9999900 11.7 0.0 79.5 65.1 fV_write Test 367 19999800 31.1 26.0 35.4 32.5 fV_apply Test 368 9999900 1.0 0.0 4.3 6.5 kahanStep Test 369 9999900 3.3 6.5 3.3 6.5 fV_index Test 366 9999900 5.2 9.3 5.2 9.3 fV_read Test 361 9999900 27.2 23.2 27.2 23.2 CAF:lvl19_r3ei Test 337 1 0.0 0.0 0.0 0.0 kahan Test 358 0 0.0 0.0 0.0 0.0 CAF:poly_$dPrimMonad3_r3eg Test 336 1 0.0 0.0 0.0 0.0 kahan Test 357 0 0.0 0.0 0.0 0.0 CAF:$dMVector2_r3ee Test 335 1 0.0 0.0 0.0 0.0 CAF:$dVector1_r3ec Test 334 1 0.0 0.0 0.0 0.0 CAF:poly_$dMonad_r3ea Test 333 1 0.0 0.0 0.0 0.0 CAF:$dMVector1_r3e2 Test 330 1 0.0 0.0 0.0 0.0 CAF:poly_$dPrimMonad2_r3e0 Test 328 1 0.0 0.0 0.0 0.0 foldV Test 365 0 0.0 0.0 0.0 0.0 CAF:lvl11_r3dM Test 322 1 0.0 0.0 0.0 0.0 kahan Test 354 0 0.0 0.0 0.0 0.0 CAF:lvl10_r3dK Test 321 1 0.0 0.0 0.0 0.0 kahan Test 355 0 0.0 0.0 0.0 0.0 CAF:$dMVector_r3dI Test 320 1 0.0 0.0 0.0 0.0 kahan Test 356 0 0.0 0.0 0.0 0.0 CAF GHC.Float 297 1 0.0 0.0 0.0 0.0 CAF GHC.IO.Handle.FD 256 2 0.0 0.0 0.0 0.0 CAF GHC.IO.Encoding.Iconv 214 2 0.0 0.0 0.0 0.0 CAF GHC.Conc.Signal 211 1 0.0 0.0 0.0 0.0 CAF Data.Vector.Generic 182 1 0.0 0.0 0.0 0.0 CAF Data.Vector.Unboxed 174 2 0.0 0.0 0.0 0.0

The equivalent implementation in C:
#include <stdint.h> #include <stdio.h> #define VDIM 100 #define VNUM 100000 uint64_t prng (uint64_t w) { w ^= w << 13; w ^= w >> 7; w ^= w << 17; return w; }; void kahanStep (double *s, double *c, double x) { double y, t; y = x - *c; t = *s + y; *c = (t - *s) - y; *s = t; } void kahan(double s[], double c[]) { for (int i = 1; i <= VNUM; i++) { uint64_t w = i; for (int j = 0; j < VDIM; j++) { kahanStep(&s[j], &c[j], w); w = prng(w); } } }; int main (int argc, char* argv[]) { double acc[VDIM], err[VDIM]; for (int i = 0; i < VDIM; i++) { acc[i] = err[i] = 0.0; }; kahan(acc, err); printf("[ "); for (int i = 0; i < VDIM; i++) { printf("%g ", acc[i]); }; printf("]\n"); }; Compiled with llvm-gcc:
>llvm-gcc -o Test_c -O3 -msse2 -std=c99 test.c >time ./Test_c real 0m0.096s user 0m0.088s sys 0m0.004s Update 1: I un-inlined kahanStep in the C version. It barely made a dent in the performance. I hope that now we can all acknowledge Amdahl's law and move on. As inefficient as kahanStep might be, unsafeRead and unsafeWrite are 9-10x slower. I was hoping someone could shed some light on the possible causes of that fact.
Also, I should say that since I am interacting with a library that uses Data.Vector.Unboxed, so I am kinda married to it at this point, and parting with it would be very traumatic :-)
Update 2: I guess I was not clear enough in my original question. I am not looking for ways to speed up this microbenchmark. I am looking for an explanation of the counter intuitive profiling stats, so I can decide whether or not to file a bug report against vector.
Your issue is likely because of the brackets on your ExternalInface call:
ExternalInterface.call("enter()"); Use this instead:
ExternalInterface.call("enter"); Also, make sure you're allowing script access in the swf embed code:
<param name='AllowScriptAccess' value='always'/>
-16549840 0 Problems with CSP in the manifest.json file the script of my first GC extension doesn't work when loaded as .crx . i've checked the debugging section and this is my error:
Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self' https://www.lolking.net/". popup.html:8
Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self' https://www.lolking.net/". popup.html:9
so i guess the error is from the manifest.json file:
{ "name": "LolKing Searcher", "version": "1.1", "manifest_version": 2, "description": "Search your LoL profile", "content_security_policy": "script-src 'self' https://www.lolking.net/; object-src 'self'", "permissions": [ "tabs", "http://*/*/" ], "content_scripts": [ { "matches": ["http://*/*/","https://*/*/"], "js": ["popup.js"] } ], "browser_action": { "default_title": "LolKing Searcher", "default_icon": "icon.png", "default_popup": "popup.html" } } also every advice is well accepted!
-36310955 0So what your code is doing is the following:
x = '2', which represents 50 as a decimal value in the ASCII table.
then your are basically saying:
x = x - '0', where zero in the ASCII table is represented as 48 in decimal, which equates to x = 50 - 48 = 2.
Note that 2 != '2' . If you look up 2(decimal) in the ASCII table that will give you a STX (start of text). This is what your code is doing. So keep in mind that the subtraction is taking place on the decimal value of the char.
-22915394 0The relative links are returned from the get_template_directory_uri() function.
It probably returns a string that looks like this : "/path/to/file.jpg"
I have no experience in wordpress but making relative links isn't specifically a php thing.
-9416484 0Try with following regex:
(?:^|[^\^])((?:\- *)?\d+) Combine it with preg_match_all function.
Explanation:
It matches all digits
(\d+) with optional negative sign (whitespacesbetween allowed)
(?:\- *)? that are not followed with ^ sign
[^\^] or are on the beggining of the string
^ (so there is ^|[^\^]) matched in non-captured group
(?:^|[^\^])
-40482409 0 I have had issues once or twice with it not skipping blanks, particularly on reports that have blanks that aren't really blank.
To be safe I use
{=AVERAGEIF(IF(ISNUMBER(F:F),A:A)}
-21289587 0 Is there a function conditionally to concatenate cells and delete certain rows? I have an Excel sheet with data arranged like this:

For every row of column A that repeats (by necessity as the database is arranged alphabetically) I need to concatenate the number for the repeating row from column B into the cell above it (inserting, say, a comma between the two strings). Then I need to delete the repeating row to end up with the following:
Breaking this down:
I hope someone will advise me on the possibility of producing a function that would execute these actions. I'm looking for a push in the right direction or confirmation that it isn't possible, rather than someone to solve the issue for me.
-38929212 0Unfortunately that page is quite dated and not correct for Grails 3+.
You can find BootStrap.groovy under grails-app/init, and the settings that were specified in DataSource.groovy are now with the rest of the config settings in application.yml (or application.groovy if you create it).
I have a test that starts up a socket connection and subscribes and joins a topic. I then push a message to the channel which does some work and persist some data. I then use ChannelTest.close/2 on the socket which simulates the client closing the connection. I would then like to modify the manipulated data and create another socket connection to test some behaviour.
My issue is ChannelTest.close/2 causes my test to fail and returns ** (EXIT from #PID<0.558.0>) shutdown: :closed. How can I prevent this from happening?
Here's some relevant code
defmodule PlexServer.EmpireChannelTest do use PlexServer.ChannelCase alias PlexServer.EmpireChannel alias PlexServer.EmpireTemplate alias PlexServer.EmpireInstance setup do ... {:ok, _, socket} = socket("user_id", %{}) |> subscribe_and_join(EmpireChannel, "empire:#{empire.id}", %{"guardian_token" => jwt}) {:ok, socket: socket, empire: empire, jwt: jwt} end test "research infrastructure", %{socket: socket, empire: empire, jwt: jwt} do ... ref = push socket, "command", request assert_reply ref, :ok, _, 1000 close(socket) #fails here ... end end defmodule PlexServer.UserSocket do use Phoenix.Socket use Guardian.Phoenix.Socket ## Channels # channel "rooms:*", PlexServer.RoomChannel channel "empire:*", PlexServer.EmpireChannel channel "user:*", PlexServer.UserChannel ## Transports transport :websocket, Phoenix.Transports.WebSocket def connect(_params,_) do :error end def id(_socket), do: nil end defmodule PlexServer.EmpireChannel do use PlexServer.Web, :channel use Guardian.Channel alias PlexServer.EmpireInstance alias PlexServer.EmpireServer ... def join("empire:" <> empire_id, %{claims: _claims, resource: user}, socket) do ... #Starts a process through a supervisor here end def join("empire:" <> _, _, _socket) do {:error, data_error(:auth, "not authorized, did you pass your jwt?")} end # Channels can be used in a request/response fashion # by sending replies to requests from the client def handle_in("ping", payload, socket) do {:reply, {:ok, payload}, socket} end def handle_in("show", _, socket) do ... end def handle_in("command", request, socket) do ... end def handle_in("remove", _, socket) do ... end def handle_in("ship_templates", _, socket) do ... end end Following the answer linked in the comments I added some code:
Process.flag(:trap_exit, true) monitor_ref = Process.monitor(socket.channel_pid) close(socket) Now I get a different error message: ** (exit) exited in: GenServer.call(PlexServer.EmpireSupervisor, {:terminate_child, :empire4}, :infinity) ** (EXIT) no process
According to Facebook: Parse tutorials 4th Point https://www.parse.com/docs/android/guide#users-facebook-users
I followed it and removed the dependency com.parse:parse-android:1.10.3.
There is nothing in the libs folder as well. But all the code of using Parse library is now red giving an error - Cannot resolve parse
I am unable to understand, if the tutorials are incorrect ?
-23711968 0 Google map cut inside bootstrap modalThis problem is bugging me for few days now. I almost gave up when yesterday I accidentally discovered something. I'm using Google map inside bootstrap modal. Problem is when I call modal, map is cut in half and I can pan and zoom it in the half of div, but strange thing is that when I turn on inspector(in any browser) entire map is shown right away and everything works like it should. Anyone had similar problem?
On calling modal:

After calling inspector:

Suppose I have a shared object of class:
class Shared { private int x = 0 ; private int y = 0 ; private Semaphore s = new Semaphore() ; public int readX() { s.p() ; int x0 = x ; s.v() ; return x0 ; } public void writeX(int x0) { s.p() ; x = x0 ; s.v() ; } public int readY() { s.p() ; int y0 = y ; s.v() ; return y0 ; } public void writeY(int y0) { s.p() ; y = y0 ; s.v() ; } } Here Semaphore is a class that uses synchronized methods to provide mutual exclusion.
Now the following actions happen:
Could thread 0 read from its cache and find that x is 0? Why?
EDIT
Here is the Semaphore class
class Semaphore { private boolean available = true ; public synchronized void v() { available = true ; notifyAll() ; } public synchronized void p() { while( !available ) try{ wait() ; } catch(InterruptedException e){} available = false ; } }
-26934622 0 ui-router has a resolve method that you can use in your routes.
The resolve will tell the routing to wait and resolve something before it moves to the new route.
Here are some examples(Your problem is similar to authentication):
-8581275 0Why not just cast the audioPlayer.currentTime to an integer before you use stringWithFormat?
[NSString stringWithFormat:@"%d", (int)(audioPlayer.currentTime)];
-12685885 0 InnoDB frequently updated table running slow I have a very simple table to track users activity. It's structure is as following:
userId appId lastActivity PRIMARY(userId, appId) Table allows to track, if user is active within a specific application. It's updated once a minute for each user and read as frequently to count number of users online within a specific application.
Lately I've noticed, that updates took a while to perform:
2012-10-01 16:49:10 - WARN --> Heavy query; array ( 'caller' => 'updateActivity', 'query' => 'INSERT INTO user_activity VALUES(4953, 1, 1349095750) ON DUPLICATE KEY UPDATE lastActivity = 1349095750', 'elapsed' => 0.134618, ) 2012-10-01 18:26:06 - WARN --> Heavy query; array ( 'caller' => 'updateActivity', 'query' => 'INSERT INTO user_activity VALUES(4533, 1, 1349101566) ON DUPLICATE KEY UPDATE lastActivity = 1349101566', 'elapsed' => 0.581776, ) 2012-10-01 18:27:16 - WARN --> Heavy query; array ( 'caller' => 'updateActivity', 'query' => 'INSERT INTO user_activity VALUES(5590, 1, 1349101636) ON DUPLICATE KEY UPDATE lastActivity = 1349101636', 'elapsed' => 0.351321, ) 2012-10-01 20:54:32 - WARN --> Heavy query; array ( 'caller' => 'updateActivity', 'query' => 'INSERT INTO user_activity VALUES(3726, 1, 1349110472) ON DUPLICATE KEY UPDATE lastActivity = 1349110472', 'elapsed' => 0.758706, ) Table uses InnoDB as storage engine.
My questions
Is there any problem at all?
Is there any problem in my design?
Where to start to find performace problems in this specific situation?
After generating java classes I received:
public class myClass { @XmlElement(name = "Data", required = true) @XmlSchemaType(name = "date") protected XMLGregorianCalendar data; @XmlElement(name = "Time", required = true) protected XMLGregorianCalendar time; ......... FindBugs warns that myClass defines non-transient non-serializable instance field data. Is it warning acceptable or need to fix? Thanks.
-22433757 0Actually java has many other editions but normally we did not use that in applications ,
list given below :
JavaSE JavaME JavaEE JavaFX JavaCard JavaDB JavaTV JavaEmbeded
and we can have 4 types of files in java :
Jar (Java archive) War (Wep applications archive) Ear (Enterprise application archive) Rar (Resource adapter archive)
sorry for speling mistakes ,,,,
-22010093 0 How do I install the JMF 2.1.1e [2014]So I Downloaded JMF from here:http://www.oracle.com/technetwork/java/javase/download-142937.html installed it(There was only an installation wizard version).
Then what am I meant to do? java had no docs on it the documentation that came with the download just said in a nutshell run the wizard.
Is it just meant to work like some kind of magical java package? I launched eclipses to see If I could use the javax.media.*; package but nope it still does not exist.
I have read many threads on this but they are from 2013 and don't really help.. As I am sure it was different then.
Is eclipse missing something.. Is anyone able to import the JMF packages in eclipse?
Tell me its not just a myth and infact one can use the new JMF in eclipse.
Where should the packadge be installed it once again siad nothing in the documentation about if it should go in a jre bin or jdk bin...
I feel like the underpants gnomes from south park. RunWizard --> ? --> Profit. Like I am missing something important but I cant find that peice of information anywhere.
-12656879 0I did the same as in this http://stackoverflow.com/a/6401135/262462 but edited this part
function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) { // do this or they'll all go to jpeg $image_type=$this->image_type; to this
function save($filename, $image_type="original", $compression=75, $permissions=null) { if ($image_type=="original") $image_type=$this->image_type;
-40976658 0 Looking at the sources of wreq reveals that the Response type comes from the http-client library. That is the same library used by the blog post you link to, and so the solution is the same that, presumably, was used in the post: import Network.HTTP.Client.Internal, which exports the constructor.
elaborating on my comment, the only way the solver learns what the constraints are is by going 'out of bounds' , so you should very much expect out of bounds values and handle them gracefully.
A typical way to do this is:
G(1) = X(1) * x(2) - x(3) ** 2 if(g(1).gt.0)then f=log(g(1)) else f=-10.e30 endif It may not matter what you return in the out of bounds case but check the docs for the imsl routine to see if it says something about that.
just by the way, note since you hard coded active(1)=.true. there is no need for the if(active(1)).. construct.
I think you're trying to construct an array consisting of the names of all zero-length files and directories in $DIR. If so, you can do it like this:
mapfile -t ZERO_LENGTH < <(find "$DIR" -maxdepth 1 -size 0) (Add -type f to the find command if you're only interested in regular files.)
This sort of solution is almost always better than trying to parse ls output.
The use of process substitution (< <(...)) rather than piping (... |) is important, because it means that the shell variable will be set in the current shell, not in an ephimeral subshell.
I use this code to record and play back recorded audio in real time using the AudioTrack and AudioRecord
package com.example.audiotrack; import android.app.Activity; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioRecord; import android.media.AudioTrack; import android.media.MediaRecorder; import android.os.Bundle; import android.util.Log; public class MainActivity extends Activity { private int freq = 8000; private AudioRecord audioRecord = null; private Thread Rthread = null; private AudioManager audioManager = null; private AudioTrack audioTrack = null; byte[] buffer = new byte[freq]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO); final int bufferSize = AudioRecord.getMinBufferSize(freq, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT); audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, freq, AudioFormat.CHANNEL_CONFIGURATION_MONO, MediaRecorder.AudioEncoder.AMR_NB, bufferSize); audioTrack = new AudioTrack(AudioManager.ROUTE_HEADSET, freq, AudioFormat.CHANNEL_CONFIGURATION_MONO, MediaRecorder.AudioEncoder.AMR_NB, bufferSize, AudioTrack.MODE_STREAM); audioTrack.setPlaybackRate(freq); final byte[] buffer = new byte[bufferSize]; audioRecord.startRecording(); Log.i("info", "Audio Recording started"); audioTrack.play(); Log.i("info", "Audio Playing started"); Rthread = new Thread(new Runnable() { public void run() { while (true) { try { audioRecord.read(buffer, 0, bufferSize); audioTrack.write(buffer, 0, buffer.length); } catch (Throwable t) { Log.e("Error", "Read write failed"); t.printStackTrace(); } } } }); Rthread.start(); } } My problem :
1.the quality of audio is bad
2.when I try different frequencies the app crashes
-3422989 0I can't reproduce the issue. I used the following test class:
package com.stackoverflow.q3421918; public class Hello { public static void main( String[] args ) { System.out.println( args[0] + " " + args[1] ); } } And the following pom.xml:
<project> <modelVersion>4.0.0</modelVersion> <groupId>com.stackoverflow.q3421918</groupId> <artifactId>Q3421918</artifactId> <version>1.0-SNAPSHOT</version> <!-- this was a test for a workaround --> <properties> <myprop>${langdir}</myprop> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.2</version> <executions> <execution> <phase>test</phase> <goals> <goal>java</goal> </goals> </execution> </executions> <configuration> <mainClass>com.stackoverflow.q3421918.Hello</mainClass> <arguments> <argument>${myprop}</argument> <argument>${langdir}</argument> </arguments> </configuration> </plugin> </plugins> </build> </project> And here is the output I get:
$ mvn clean package -Dlangdir=C:/somedir [INFO] Scanning for projects... [INFO] ------------------------------------------------------------------------ [INFO] Building Q3421918 [INFO] task-segment: [clean, package] [INFO] ------------------------------------------------------------------------ ... [INFO] Preparing exec:java [WARNING] Removing: java from forked lifecycle, to prevent recursive invocation. [INFO] No goals needed for project - skipping [INFO] [exec:java {execution: default}] Hello c:/somedir c:/somedir [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESSFUL [INFO] ------------------------------------------------------------------------ ... Tested with Maven 2.2.1.
-31905071 0Wasn't sure what you meant by a 'dropdownList'. For this example I used a ComboBox.
Dim StartTime As DateTime = #12:00:00 AM# 'load combo box Do StartTimeDDL.Items.Add(StartTime.ToString("hh:mm tt")) StartTime = StartTime.AddMinutes(30) Loop While StartTime.TimeOfDay.TotalDays > 0 Dim selectTime As DateTime = #2:10:12 PM# 'TEST find this <<<<<<<<<<<<<<<<<<< 'round time to 30 minutes Dim numSecs As Integer = (CInt(selectTime.TimeOfDay.TotalSeconds) \ 1800) * 1800 'the OP said 'les say current time is 12:00:00 AM than I was to select 12:30 AM" 'so.... numSecs += 1800 'round up 30 minutes ???????? 'create 'find' Dim ts As New TimeSpan(0, 0, numSecs) Dim findDate As New DateTime(ts.Ticks) StartTimeDDL.SelectedIndex = StartTimeDDL.FindStringExact(findDate.ToString("hh:mm tt"))
-34865004 0 If you want to select a Node by default, you can do it by setting the node's selected property to true when you initialise the dataSource. Another option would be to call the TreeView select() method after the TreeView completed the data loading. (See the dataBound event for more details since the TreeView initialization may be completed before the data gets fully loaded)
For the selection, there's a findByUid method that can be used in the TreeView. The findByUid function will return the jQuery nodes matching the specified uid. You can then use the results to select a node programatically by using the select() method:
var dataItem = treeview.dataSource.get(10); var node = treeview.findByUid(dataItem.uid); treeview.select(node);
-19980418 0 This will return true for elements that are currently in the document, and selectors which match elements in the document.
function isInDoc(sel) { var $sel = jQuery(sel); return $sel.length && jQuery.contains(document.documentElement, $sel[0]); }
-8082358 0 RegisterStartupScript, Ajax and external script I have a page that is run using AJAX. I have a control that is wrapped in a RadAjaxPanel that has multiple child controls in it. The RadAjaxPanel is updated when new items are selected. I also have a 3rd party javascript that needs to refresh during the callback.
Here is my problem.
When the callback happens, I use
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "RecommendationScript", "<script src='3rdparty.js'></script>, false); This doesn't appear to work after the callback happens since I am not seeing the results. Even if I create a test external script that does a javascript alert, I won't see the alert after the callback. Everything works fine though if I don't use an external script and just put the alert in the RegisterStartupScript. However, that won't work for what I need to do.
Any ideas?
-39248920 0 missing parameter #2 in call error in CGRectIntersectsRectI am writing a small game in swift, in which a boat has to go around obstacles. However, I keep getting this "missing argument for parameter #2 in call" error in CGRectInersectsRect. I have checked how to call it in the directory, and am calling it correctly. What is the issue with my code?. Here it is:
if (CGRectIntersectsRect(boat: CGRect, obstacleImageView: CGRect)) { endGame() } }
-35085553 0 There seems to be a special character between the < and ?. Then it does not recognize it as start of php code.
Maybe your required file has some weird encoding? Which Editor are you using?
-4815002 0 ASP.NET 4 routing questionI am trying to do the following in my Global.asax file:
At the moment i have to define my route like this:
routes.MapPageRoute( "ViewPage", "pages/{slug}", "~/viewpage.aspx", false ); Notice the word pages before the {slug}
Now if i define it like this:
routes.MapPageRoute ( "ViewPage", "{slug}", "~/viewpage.aspx", false ); It does not work.
My CSS and JS files wont load, i get a 404.
But, if i do this:
routes.MapPageRoute ( "ContactPage", "contact", "~/contact.aspx", false ); It works fine??
Basically i want my urls to look like this:
example.com/contact or example.com/about-us and it is all served dynamically from the database based on the {slug}.
Can anyone help?
-34978437 0That library doesn't look like it will easily do bidirectional. But, since DMX512 is a simple serial protocol, there's nothing stopping you from writing your own routines that manipulate the UART directly. The library will be a great guide for this.
Now, having said that: what kind of situation do you have where you want a device to both control and receive? The DMX512 protocol is explicitly unidirectional, and at the physical layer it's a daisy-chain network, which prevents multiple masters on the bus (and inherently creates a unidirectional bus). If you are a slave and you are manipulating the bus, you risk clobbering incoming packets from the master. If you are clever about it, and queue the incoming packets, you could then perhaps safely retransmit both the incoming data and your own data, but be aware that this is a decidedly nonstandard (and almost certainly standards-violating) behavior.
-17311044 0The true C99 way to do this is to have:
int f(int p[static 4]) { p[0] = 1; p[1] = 2; p[2] = 3; p[3] = 4; return c; } The static 4 inside the square brackets indicates to the compiler that the function expects an array of at least 4 elements. clang will issue a warning if it knows at compile-time that the value you are passing to f doesn't contain at least 4 elements. GCC may warn too but I don't use this compiler often.
It's OpenCV-2.4.0
cd opencv mkdir release cd release cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D BUILD_PYTHON_SUPPORT=ON -D BUILD_EXAMPLES=ON .. make Error:
In file included from OpenCV-2.4.0/modules/core/src/system.cpp:460: OpenCV-2.4.0/release/modules/core/version_string.inc:35:1: warning: missing terminating " character In file included from OpenCV-2.4.0/modules/core/src/system.cpp:460: OpenCV-2.4.0/release/modules/core/version_string.inc:35: error: missing terminating " character OpenCV-2.4.0/release/modules/core/version_string.inc:36:11: error: too many decimal points in number OpenCV-2.4.0/release/modules/core/version_string.inc:36:29: error: invalid suffix "st" on integer constant OpenCV-2.4.0/release/modules/core/version_string.inc:40:29: warning: character constant too long for its type OpenCV-2.4.0/release/modules/core/version_string.inc:57: error: stray ‘@’ in program OpenCV-2.4.0/release/modules/core/version_string.inc:57: error: stray ‘@’ in program OpenCV-2.4.0/release/modules/core/version_string.inc:68:10: error: #include expects "FILENAME" or <FILENAME> OpenCV-2.4.0/release/modules/core/version_string.inc:71: error: stray ‘\’ in program OpenCV-2.4.0/release/modules/core/version_string.inc:71:9: warning: missing terminating " character OpenCV-2.4.0/release/modules/core/version_string.inc:71: error: missing terminating " character OpenCV-2.4.0/release/modules/core/version_string.inc:74:23: warning: missing terminating " character OpenCV-2.4.0/release/modules/core/version_string.inc:1515: error: stray ‘\’ in program OpenCV-2.4.0/release/modules/core/version_string.inc:1515:4: warning: missing terminating " character OpenCV-2.4.0/release/modules/core/version_string.inc:1515: error: missing terminating " character OpenCV-2.4.0/release/modules/core/version_string.inc: In function ‘const std::string& cv::getBuildInformation()’: OpenCV-2.4.0/release/modules/core/version_string.inc:36: error: expected ‘,’ or ‘;’ before ‘version’ OpenCV-2.4.0/release/modules/core/version_string.inc:138: error: ‘z_stream’ was not declared in this scope OpenCV-2.4.0/release/modules/core/version_string.inc:140: error: expected ‘;’ before ‘typedef’ OpenCV-2.4.0/release/modules/core/version_string.inc:161: error: ‘gz_header’ was not declared in this scope OpenCV-2.4.0/release/modules/core/version_string.inc:163: error: expected ‘;’ before ‘typedef’ OpenCV-2.4.0/release/modules/core/version_string.inc:1505: error: ‘ZEXTERN’ was not declared in this scope OpenCV-2.4.0/release/modules/core/version_string.inc:1505: error: expected ‘;’ before ‘const’ OpenCV-2.4.0/release/modules/core/version_string.inc:1511: warning: no return statement in function returning non-void OpenCV-2.4.0/release/modules/core/version_string.inc: At global scope: OpenCV-2.4.0/release/modules/core/version_string.inc:1515: error: expected unqualified-id before ‘)’ token OpenCV-2.4.0/modules/core/src/system.cpp:462: error: expected unqualified-id before ‘return’ OpenCV-2.4.0/modules/core/src/system.cpp:465: error: ‘string’ does not name a type OpenCV-2.4.0/modules/core/src/system.cpp:474: error: ‘string’ does not name a type OpenCV-2.4.0/modules/core/src/system.cpp:503: error: ISO C++ forbids declaration of ‘Exception’ with no type OpenCV-2.4.0/modules/core/src/system.cpp:503: error: expected ‘,’ or ‘...’ before ‘&’ token OpenCV-2.4.0/modules/core/src/system.cpp: In function ‘void error(int)’: OpenCV-2.4.0/modules/core/src/system.cpp:506: error: ‘exc’ was not declared in this scope OpenCV-2.4.0/modules/core/src/system.cpp:510: error: ‘exc’ was not declared in this scope OpenCV-2.4.0/modules/core/src/system.cpp:526: error: ‘exc’ was not declared in this scope OpenCV-2.4.0/modules/core/src/system.cpp: At global scope: OpenCV-2.4.0/modules/core/src/system.cpp:543: error: expected declaration before ‘}’ token make[2]: *** [modules/core/CMakeFiles/opencv_core.dir/src/system.cpp.o] Error 1 make[1]: *** [modules/core/CMakeFiles/opencv_core.dir/all] Error 2 make: *** [all] Error 2 What should i do?
-5409418 0 Common Lisp: how to dynamically wrap existing functions, such as for a profiler?I am new at Lisp, and am trying different things out to improve my skills. I want to write a macro that wraps existing functions so that I can set up before and after forms for these functions, kind of like CLOS's auxilliary methods or Elisp's advice package. The trace function's ability to wrap code dynamically has intrigued me, and it seems useful to be able to do this myself.
So, how can I do this? How many ways can I do this? : )
Please note that I am using SBCL, and that, for the purposes of this question, I am not interested so much in the "right" way of doing this as I am in adding to my Lisp trick bag.
-38928553 0 PHP : Allow user to comment and rate only once with their ip adressContext : I'm making a website where users can search for internet forfeit and I want to make a 5 star rating system and a comment system for every internet provider... But the users are only allowed to comment and rate only one time for each provider... I have tough about getting the user ip adress, then put it in a database when they comment and rate...
So i'm asking if some people have clue or idea of how i can do that...
You guys can see what i'm talking about here : http://fournisseursquebec.com/Fournisseurs/Fido.php
-6032228 0 CurrencyManager alternative in vb.NET?I am developing a VB.NET application in which I use a DataGrid; I can't use the newer DataGridView due to version. But now when I try to compile this, I get the error:
BC30002: Type 'CurrencyManager' is not defined.
It errors on line:
Dim CM As New CurrencyManager(dgTable.BindingContext)
What can I replace this line with? I have read on the internet that since my application should be web-based, I cannot use the Windows namespace. I think what I am asking for is a pretty simple solution, but I am a very new VB programmer. More of my code below.
Global.vb file:
Imports System.Data Imports System.Data.OLEDB Imports System.Web Imports System.Math Imports system.data.SqlClient Imports System.Windows.Forms Imports System.Windows.Forms.CurrencyManager Namespace GlobalFunctions Public Class GlobalF Public Shared Function GlobalF_Load(ByVal dgTable As DataGrid) Dim dv As New DataView Dim ds As New DataSet Dim CM As New CurrencyManager(dgTable.BindingContext) dv = New DataView(ds.Tables(0)) dgTable.DataSource = dv dv.Sort = "Part No." 'CM = (System.Windows.Forms.CurrencyManager) dgTable.BindingContext([dv]) Dim sender As New sender() dv.ListChanged += New ListChangedEventHandler(dv_ListChangedEvent) End Function Public Shared Function btnFind_Click(ByVal sender As Object, ByVal e As EventArgs) If (txtFind.Text = "") Then Response.write("Enter some criteria to find.") txtFind.Focus() Else Dim i As Int i = dv.Find(txtFind.Text) If (i > dv.Table.Rows.Count Or i < 0) Then Response.Write("Record Not found") Else CM.Position = i End If End If End Function Private Shared Function dv_ListChangedEvent(ByVal sender As Object, ByVal e As ListChangedEventArgs) Handles btnFind.ListChanged If (dv.Sort.Substring((dv.Sort.Length - 4), 4) = "DESC") Then lblFind.Text = "Enter Search Criteria " + dv.Sort.Substring(0, dv.Sort.Length - 5) Else lblFind.Text = "Enter Search Criteria " + dv.Sort End If End Function and my ASPX file:
Public DSTableData As New System.Data.DataSet Public dv As New DataView
Sub Main() '------------------------- Query database and get arrays for the chart and bind query results to datagrid ---------------------------------------- If check1.Checked Then DSTableData = GlobalFunctions.GlobalF.FillSparePartsTable(1) Else DSTableData = GlobalFunctions.GlobalF.FillSparePartsTable(0) End If 'dv = DataView(DSTableData(0)) dgTable.DataSource = DSTableData dgTable.DataBind() GlobalFunctions.GlobalF.GlobalF_Load(dgTable) End Sub
-34434064 0 each architecture has its own assembly language. and even within architectures there might be extensions which add extra commands (like the SSE extensions). Usually a Compiler can only create code for one architecture, and there might be optional flags which enable optimizations for the extensions. When these flags get enabled the program will usually only run on processors that support these extensions.
For programs and OS it usually means you should only use compiler options that are supported by all processors of the architecture they have to run on. If thats not optimized enough you have to deliver executables/libraries with multiple code paths for he different optimizations, and pick the right one at runtime.
-20072314 0 How to set vertical text from bottom to top in html?It is easy to set text from top to bottom and there are enough resources to do that.
The problem is with bottom to top vertical alignment.
See the image below-

For the second button add
android:id="@+id/button2" and change
android:layout_alignLeft="@+id/button1" to
android:layout_alignLeft="@id/button1" Change your layout as follow:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="start" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <TextView android:id="@+id/textView1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:text="your total is 0" android:textSize="65sp" /> <Button android:id="@+id/button1" android:layout_width="100sp" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView1" android:layout_below="@+id/textView1" android:layout_gravity="center" android:text="add" /> <Button android:id="@+id/button2" android:layout_width="100sp" android:layout_height="wrap_content" android:layout_alignLeft="@id/button1" android:layout_below="@+id/textView1" android:layout_marginLeft="117dp" android:text="subtract" /> </RelativeLayout>
-15284884 0 How to access the local project file using java.nio.file.Path? I am new to java.nio world.
I have a log file app.log inside my Java module. (I am using Intellij 11).
In a module, i have test folder, i have a local file app.jar.
I want to read this file into InputStream using Files.newInputStream(path) method.
The problem is that in windows, i have to give complete value for input path as,
Path path = Paths.get("C:\\Perforce\\depot\\Project\\module\\src\\test\\a\\b\\c\\app.jar"); I am not sure if somebody gets this code and has similar folder structure on their machine to access app.jar
I have kept the file app.jar in local folder where my test is written. Is there a way through which i can generalize this Path? if my Test class is under the same folder where app.jar is residing, is there any mechanism to avoid mentioning the complete local path?
Thanks, Vijay Bhore
-31500034 0 c# socket send fileim trying to use the SendFile method https://msdn.microsoft.com/en-us/library/sx0a40c2(v=vs.110).aspx
TcpClient client; private void Form1_Load(object sender, EventArgs e) { client = new TcpClient(); client.Connect("10.0.0.1", 10); string fileName = @"C:\Users\itapi\Desktop\da.jpg"; Console.WriteLine("Sending {0} to the host.", fileName); client.Client.SendFile(fileName); } server code:
TcpListener listener; TcpClient cl; private void Form1_Load(object sender, EventArgs e) { listener = new TcpListener(IPAddress.Any, 10); listener.Start(); cl = listener.AcceptTcpClient(); } my question is: how i am supposed to get the file in the other side? i dont want to use networkstream only pure socket. any help would be apperciated
-6049179 0 how to pass data from json to a php function?[registration] => Array ( [first_name] => test [location] => Array ( [name] => Santa Ana [id] => 1.08081209215E+14 ) [gender] => female [password] => 123654789 ) and i need to insert that data into a database by using:
$carray = fns_create_talent($login, $pass, $gender, $name); any idea on how to get them from a place to another?
i was thinking that i need to assign the array values to the post vars. maybe:
$login = registration.first_name... any ideas? thanks
-16047252 0 Identifying What Javascript is Running on a through Chrome Inspector or FirebugI am working on a site that has info being generated dynamically into <span></span> tags through jQuery. The span has a class of "Price" and an id of a Product Code and it's being generated from a JSON data sheet according to the ID. The problem is, this is part of a much bigger framework and I can't seem to find where the Javascript is that's accomplishing this so I can troubleshoot it.
I'm trying to figure out how to find that out using Google Chrome Inspector or Firebug. I'm assuming the page records this info when it's loaded but I can't seem to find where that info would lie. I know this may be pretty basic but I new to the Inspectors beyond just reading the HTML and CSS. Thanks for your help!
-33036254 0 Xamarin forms block user back key pressIn my Xamarin forms application I want to show a confirmation message when user clicks the back button from Main-page. Is there any way to achieve this? I overrided the OnBackButtonPressed method in my MainPage. But still the app is closing while back key press. Here is my code
protected override bool OnBackButtonPressed () { //return base.OnBackButtonPressed (); return false; }
-17679183 0 private static List<string> wordsToRemove = "DE DA DAS DO DOS AN NAS NO NOS EM E A AS O OS AO AOS P LDA AND".Split(' ').ToList(); public static string StringWordsRemove(string stringToClean) { return string.Join(" ", stringToClean.Split(' ').Except(wordsToRemove)); } Modification to handle punctuations:
public static string StringWordsRemove(string stringToClean) { // Define how to tokenize the input string, i.e. space only or punctuations also return string.Join(" ", stringToClean .Split(new[] { ' ', ',', '.', '?', '!' }, StringSplitOptions.RemoveEmptyEntries) .Except(wordsToRemove)); }
-33179511 0 Moment js timezone off by 1 hour I can't figure out what I am doing wrong here.
Passing in a string to moment, with the format and calling .toDate().
toDate() ends up returning a time that is off by 1 hour
moment("2015-11-19T18:34:00-07:00", "YYYY-MM-DDTHH:mm:ssZ").toDate() > Thu Nov 19 2015 17:34:00 GMT-0800 (PST) The time should be 18:34, not 17:34. The timezone is showing -08, when it should be showing -07
initial is not supported by IE10
why not use auto?
-11788545 0Please use http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/ link for reference. But if you will tell what specific you are looking for I might be able to help you better. Here is little detail about @GeneratedValue annotation… I love this blog post on same topic http://elegando.jcg3.org/2009/08/hibernate-generatedvalue/. He has done good job explaining.
-32974349 0 How to make a PNG float ontop of other imagesWhat css code should i use to make this transparent png element with a shadow in the png file, float over the upper image to avoid this white stripe?
http://postimg.org/image/ektu4srvn/
http://postimg.org/image/dged2yme3/
-36348763 0 How Do I Call an Async Method from a Non-Async Method?I have the below method:
public string RetrieveHolidayDatesFromSource() { var result = this.RetrieveHolidayDatesFromSourceAsync(); /** Do stuff **/ var returnedResult = this.TransformResults(result.Result); /** Where result gets used **/ return returnedResult; } private async Task<string> RetrieveHolidayDatesFromSourceAsync() { using (var httpClient = new HttpClient()) { var json = await httpClient.GetStringAsync(SourceURI); return json; } } The above does not work and seems to not return any results properly. I am not sure where I am missing a statement to force the await of a result? I want the RetrieveHolidayDatesFromSource() method to return a string.
The below works fine but it is synchronous and I believe it can be improved upon? Note that the below is synchronous in which I would like to change to Asynchronous but am unable to wrap my head around for some reason.
public string RetrieveHolidayDatesFromSource() { var result = this.RetrieveHolidayDatesFromSourceAsync(); /** Do Stuff **/ var returnedResult = this.TransformResults(result); /** This is where Result is actually used**/ return returnedResult; } private string RetrieveHolidayDatesFromSourceAsync() { using (var httpClient = new HttpClient()) { var json = httpClient.GetStringAsync(SourceURI); return json.Result; } } Am I missing something?
Note: For some reason, when I breakpoint the above Async Method, when it gets to the line "var json = await httpClient.GetStringAsync(SourceURI)" it just goes out of breakpoint and I can't go back into the method.
-32401250 0That would allow some kind of proxy-copy like this:
NotCopyable a, b; b = a; // Made a copy of a It is pretty unlikely that you do not want copy construction but copy assignment. Move assignment would be a different deal of course, see e.g. std::unique_ptr.
Singleton is basically the same. Why allow the self assignment? That just does not make sense.
-28526405 0 Remove duplicates according to data in 2 columns by priority in ExcelI am trying to remove duplicates in Excel by comparing 2 columns and by priority, meaning:
I have priority by category such as cat 1 > cat 2 > cat 3 > cat 4
And I want to match if some text that appears in column 2 and 4 matches any other row it will delete the row that has the lower category priority
Here is an image: http://i.imgur.com/aN3cQwL.png
Explanation of the image: Orange cells should be deleted, blue ones should be kept.
Update:
What I am trying to achieve: I have a list of URLs in column B (Source URLs), another list of URLs in column C (which are target URLs of links), anchor text in column D, column A contains the data source to help me identify from where I pulled the data from. I just want to make sure that there aren't any duplicates between all data sources but maintaining a certain priority, which will prefer to delete duplicates from Category 2 if the exact source URL and anchor appear in Category 1 and etc.
-30893418 1 Django runserver from Python scriptThe normal way to start the Django server is to run the following command from a terminal or a bash script:
python manage.py runserver [Ip.addr]:[port] e.g.
python manage.py runserver 0.0.0.0:8000 How can I start a Django server from a Python script?
One option is the following
import os if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings") from django.core.management import execute_from_command_line args = ['name', 'runserver', '0.0.0.0:8000'] execute_from_command_line(args) Is there a better way?
-23560149 0 Android adding information to a table when the alarm startedHi stackoverflow users I have the next problem: I have created a program that compare in a countdown timer 2 values( a feedback and a counter ) The counter is the value I set of the temperature for example and the feedback another value I get from outside.
When the countdown timer reach 0 if the counter is not equal with the feedback value the alarm start and I want to add the feedback and the counter to a log.
Example of a small piece of code is below, here I compare the counter with
if(Integer.parseInt(feedback.getText().toString()) != midvalue) { btnbool.setBackgroundColor(Color.RED); btnbool.setText("FALSE"); showup.setText(""+counter); letme = 2; if(alarmapornita == 0) { alarmapornita = 1; handler.post(thread); } alarma = 1; myhandler.post(mythread); healthy = false; Intent i = new Intent(getApplicationContext(), Log.class); i.putExtra("mymidvalue",midvalue); i.putExtra("myfeedback",Integer.parseInt(feedback.getText().toString())); startActivity(i); } The problem is that with Intent I get only one entry to the table and when I get the alarm on it switch to the other activity. I don't know anything else how to use, is there any option to replace intent ?
-3071774 0 How can I use CodeIgniter's set_value for a field that's an array?I have a dropdown labeled "amenities[]" and it's an array. When I use CodeIgniter's form_validation, I want to re-populate it properly using set_value, but I'm not able to. Anyone have any input on this?
-25268581 0PROBLEM: I had similar problem with a file created from other computer (a css in my case). To solve the problem I read that it is necessary to change the permissions but I don't know to do this on Windows so I try this alternative:
SOLUTION: Open the file, copy the content and paste it in a new file, this makes sure the permissions are ok.
When changing the name by using F2 it didn't work for me, I believe it is because the permissions where still the same.
-3926182 0Yes, it's always good to have a known issues section; if nothing else, to keep your inbox empty of the same emails complaining about the same bugs you already know about.
-34383881 0Turns out that setting .Focusable = False to all the Radio Buttons was the answer :-)
-26561014 0You can use array_slice() for slice and array_sum() to calculate total then average. An example here
$values = array(1,2,3,4,5,6,7,8,9,10); foreach($values as $k=>$v){ if($k > 4){ echo $ave = array_sum(array_slice($values, $k - 5, $k)) / 5 . '<br />'; } }
-38950843 0 You need to you something like:
foreach ($results as $value){ $allValues = implode('", "', $value); //the above line will give us something like ("1", "Henricho"....etc) $query ='Insert into(col1, col2, col3, col4, col5, col6, col7, col8) Values("'.$allValues.'")'; //You can now execute your query echo $query."<BR />"; }
-22795290 0 You're experiencing one-off errors because of the fact that ExcelApp.Cells isn't zero based and you have a header row.
To combat this you can use foreach and separate out your header export to a separate block. It does take a little bit more code but I find it easier to deal with and less error prone
int i = 1; int j = 1; //header row foreach(DataColumn col in dtMainSQLData.Columns) { ExcelApp.Cells[i, j] = col.ColumnName; j++; } i++; //data rows foreach(DataRow row in dtMainSQLData.Rows) { for (int k = 1; k < dtMainSQLData.Columns.Count + 1; k++) { ExcelApp.Cells[i, k] = row[k-1].ToString(); } i++; }
-35138248 0 ActionController known Format I am having an issue with this code. It is for uploading an audio file. When I upload it I get an error saying this:
ActionController::UnknownFormat at /users/1/audios/dfdfdsdsf ============================================================ > ActionController::UnknownFormat app/controllers/audios_controller.rb, line 67 --------------------------------------------- ``` ruby 62 if @audio.errors.empty? && @audio.update_attributes(update_audio_params) 63 respond_to do |format| 64 format.html { redirect_to user_audios_path(@user) } 65 end 66 else > 67 respond_to do |format| 68 format.html { render :edit } 69 format.js { render json: { result: :failed, errors: @audio.errors } } 70 end 71 end 72 end ``` App backtrace ------------- - app/controllers/audios_controller.rb:67:in `update' Full backtrace -------------- - actionpack (4.2.3) lib/action_controller/metal/mime_responds.rb:217:in `respond_to' - app/controllers/audios_controller.rb:67:in `update' - actionpack (4.2.3) lib/action_controller/metal/implicit_render.rb:4:in `send_action' - actionpack (4.2.3) lib/abstract_controller/base.rb:198:in `process_action' - actionpack (4.2.3) lib/action_controller/metal/rendering.rb:10:in `process_action' - actionpack (4.2.3) lib/abstract_controller/callbacks.rb:20:in `block in process_action' - activesupport (4.2.3) lib/active_support/callbacks.rb:115:in `call' - activesupport (4.2.3) lib/active_support/callbacks.rb:553:in `block (2 levels) in compile' - activesupport (4.2.3) lib/active_support/callbacks.rb:503:in `call' - activesupport (4.2.3) lib/active_support/callbacks.rb:88:in `run_callbacks' - actionpack (4.2.3) lib/abstract_controller/callbacks.rb:19:in `process_action' - actionpack (4.2.3) lib/action_controller/metal/rescue.rb:29:in `process_action' - actionpack (4.2.3) lib/action_controller/metal/instrumentation.rb:32:in `block in process_action' - activesupport (4.2.3) lib/active_support/notifications.rb:164:in `block in instrument' - activesupport (4.2.3) lib/active_support/notifications/instrumenter.rb:20:in `instrument' - activesupport (4.2.3) lib/active_support/notifications.rb:164:in `instrument' - actionpack (4.2.3) lib/action_controller/metal/instrumentation.rb:30:in `process_action' - actionpack (4.2.3) lib/action_controller/metal/params_wrapper.rb:250:in `process_action' - activerecord (4.2.3) lib/active_record/railties/controller_runtime.rb:18:in `process_action' - actionpack (4.2.3) lib/abstract_controller/base.rb:137:in `process' - actionview (4.2.3) lib/action_view/rendering.rb:30:in `process' - rack-mini-profiler (0.9.8) lib/mini_profiler/profiling_methods.rb:106:in `block in profile_method' - actionpack (4.2.3) lib/action_controller/metal.rb:196:in `dispatch' - actionpack (4.2.3) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch' - actionpack (4.2.3) lib/action_controller/metal.rb:237:in `block in action' - actionpack (4.2.3) lib/action_dispatch/routing/route_set.rb:76:in `dispatch' - actionpack (4.2.3) lib/action_dispatch/routing/route_set.rb:45:in `serve' - actionpack (4.2.3) lib/action_dispatch/journey/router.rb:43:in `block in serve' - actionpack (4.2.3) lib/action_dispatch/journey/router.rb:30:in `serve' - actionpack (4.2.3) lib/action_dispatch/routing/route_set.rb:821:in `call' - warden (1.2.3) lib/warden/manager.rb:35:in `block in call' - warden (1.2.3) lib/warden/manager.rb:34:in `call' - rack (1.6.4) lib/rack/etag.rb:24:in `call' - rack (1.6.4) lib/rack/conditionalget.rb:38:in `call' - rack (1.6.4) lib/rack/head.rb:13:in `call' - actionpack (4.2.3) lib/action_dispatch/middleware/params_parser.rb:27:in `call' - actionpack (4.2.3) lib/action_dispatch/middleware/flash.rb:260:in `call' - rack (1.6.4) lib/rack/session/abstract/id.rb:225:in `context' - rack (1.6.4) lib/rack/session/abstract/id.rb:220:in `call' - actionpack (4.2.3) lib/action_dispatch/middleware/cookies.rb:560:in `call' - activerecord (4.2.3) lib/active_record/query_cache.rb:36:in `call' - activerecord (4.2.3) lib/active_record/connection_adapters/abstract/connection_pool.rb:653:in `call' - activerecord (4.2.3) lib/active_record/migration.rb:377:in `call' - actionpack (4.2.3) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call' - activesupport (4.2.3) lib/active_support/callbacks.rb:84:in `run_callbacks' - actionpack (4.2.3) lib/action_dispatch/middleware/callbacks.rb:27:in `call' - actionpack (4.2.3) lib/action_dispatch/middleware/reloader.rb:73:in `call' - actionpack (4.2.3) lib/action_dispatch/middleware/remote_ip.rb:78:in `call' - better_errors (2.1.1) lib/better_errors/middleware.rb:84:in `protected_app_call' - better_errors (2.1.1) lib/better_errors/middleware.rb:79:in `better_errors_call' - better_errors (2.1.1) lib/better_errors/middleware.rb:57:in `call' - actionpack (4.2.3) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call' - web-console (2.2.1) lib/web_console/middleware.rb:39:in `call' - actionpack (4.2.3) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call' - railties (4.2.3) lib/rails/rack/logger.rb:38:in `call_app' - railties (4.2.3) lib/rails/rack/logger.rb:20:in `block in call' - activesupport (4.2.3) lib/active_support/tagged_logging.rb:68:in `block in tagged' - activesupport (4.2.3) lib/active_support/tagged_logging.rb:26:in `tagged' - activesupport (4.2.3) lib/active_support/tagged_logging.rb:68:in `tagged' - railties (4.2.3) lib/rails/rack/logger.rb:20:in `call' - actionpack (4.2.3) lib/action_dispatch/middleware/request_id.rb:21:in `call' - rack (1.6.4) lib/rack/methodoverride.rb:22:in `call' - rack (1.6.4) lib/rack/runtime.rb:18:in `call' - activesupport (4.2.3) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call' - rack (1.6.4) lib/rack/lock.rb:17:in `call' - actionpack (4.2.3) lib/action_dispatch/middleware/static.rb:116:in `call' - rack (1.6.4) lib/rack/sendfile.rb:113:in `call' - rack-mini-profiler (0.9.8) lib/mini_profiler/profiler.rb:282:in `call' - railties (4.2.3) lib/rails/engine.rb:518:in `call' - railties (4.2.3) lib/rails/application.rb:165:in `call' - rack (1.6.4) lib/rack/content_length.rb:15:in `call' - puma (2.12.2) lib/puma/server.rb:539:in `handle_request' - puma (2.12.2) lib/puma/server.rb:386:in `process_client' - puma (2.12.2) lib/puma/server.rb:269:in `block in run' - puma (2.12.2) lib/puma/thread_pool.rb:106:in `block in spawn_thread' It might have to do with the respond_to block. Here is the code of that bellow:
def update if params[:audio][:attachment].blank? && update_image_params.present? @audio.update_audio_cover_picture update_image_params["photo"] end if @audio.errors.empty? && @audio.update_attributes(update_audio_params) respond_to do |format| format.html { redirect_to user_audios_path(@user) } end else respond_to do |format| format.html { render :edit } format.js { render json: { result: :failed, errors: @audio.errors } } end end end This is a copy of the same code I use for my other project. It completely works on that app:
def update if params[:book][:attachment].blank? && update_image_params.present? @book.update_book_cover_picture update_image_params["photo"] end if @book.errors.empty? && @book.update_attributes(update_book_params) respond_to do |format| format.html { redirect_to user_books_path(@user) } format.json { render json: { result: :success, url: user_books_url(@user) } } end else respond_to do |format| format.html { render :edit } format.js { render json: { result: :failed, errors: @book.errors } } end end end
-12277308 0 I would suggest you to send a TVP (table value parameter) back to the server. After that your query could be done like:
SELECT p.ProductId, Name, Description, {other columns} FROM Products p left join @ExceptedProducts ep on p.ProductId=ep.ProductId WHERE where ep.ProductId is null This should be the fastest and cleanest way.
-34055291 0 Dropdown in parent div with overflow:autoFor a project, i need to create a view where a drop down menu is at the bottom of a parent div. A short fiddle here : http://jsfiddle.net/Gruck/6owhaa63/, where "move to" item opens some more options, as shown on this mockup 
<div class="job"> <div class="job-main"> <div class="title"> some content </div> <div class="counters"> some other content </div> </div> <div class="ops"> <ul> <li><a href="#">edit</a></li> <li><a href="#">visualize</a></li> <li><a href="#">move to</a> <ul class="move-to"> <li>folder a</li> <li>folder b</li> </ul> </li> </ul> </div> </div> And some css
.job { border-style: solid; border-color: #F2F2F2; border-width: 2px; background-color: #FFFFFF; overflow: auto; } .job-main { border-bottom: 1px solid #F2F2F2; overflow: hidden; } .title { width: calc(100% - 390px); height: 100px; float: left; min-width: 300px; padding:10px; background-color: #EE0000; } .counters { width: 362px; height: 80px; padding: 20px 0px 20px 0px; float: right; background-color: #00EE00; } How to get the options to be displayed on top of the parent div ? is there anyway to do so yet keeping the options inside the div ?
I guess i would have to move the options to outside the parent div and mannualy position them, but i would like to make sure i don't miss a nicer way to do so.
Thanks for any idea you might offer :) Cheers
-10841371 0Re: Ahmad's code - a simpler approach with no recursion or pointers, fairly naive, but requires next to no computational power for anything short of really titanic numbers (roughly 2N additions to verify the Nth fib number, which on a modern machine will take milliseconds at worst)
// returns pos if it finds anything, 0 if it doesn't (C/C++ treats any value !=0 as true, so same end result)
int isFib (long n) { int pos = 2; long last = 1; long current = 1; long temp; while (current < n) { temp = last; last = current; current = current + temp; pos++; } if (current == n) return pos; else return 0; }
-9951356 0 You can put the configuration settings for any library in the main web.config. It's easy!
Connection strings are especially easy. Just add your connection string to the connectionstrings section with the same name it has in the library's app.config, and you're done!
<connectionStrings> <add name="Sitefinity" connectionString="your connection string"/> </connectionStrings> To add configuration settings, at the top of your web config, find the applicationSettings section, and add your section's info. Note: be sure to set your library's settings access modifier to "Public". You can do this in the Properties ui.
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <section name="Your.Assembly" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </sectionGroup> Then, add the section under applicationSettings.
<applicationSettings> <Your.Assembly> <setting name="TestSetting" serializeAs="String"> <value>a test value</value> </setting> </Your.Assembly> </applicationSettings>
-6576281 0 The problem is NOT your texture coordinates.
The problem is that you're loading the texture wrong. You're forgetting to remove the bitmap header, so all the real data is shifted over, and the end of each line is shifted onto the beginning of the next line.
Texture wrapping would wrap pixels from the right back onto the same line, but the out-of-place region is shifted down one row. Texture wrapping also wouldn't occur with the "clamp to edge" mode you've enabled.
-6134230 0 continuously print the last line of a file Linux terminTwo questions, but only stuck on one. Feel that I need the first one so someone can help me make sense of it.
4) Use cat and /dev/null to create an empty file.
5) Start a background process that continuously prints the last line of the file created in #4..
So what i did for number 4 was:
cat /dev/null > emptyfile This created an empty file. Okay so I am happy with that. The next question however confuses me. How can I read the last line of an empty file? Better yet how do I continuously do this? Running it in the background isn't a problem. Anyone have any ideas? We haven't covered scripting yet so I don't think that plays a role. As always, thanks for the help.
-27850603 0To convert from one date format to another, just modify the answer posted at http://stackoverflow.com/a/27659933/1745001 to suit your input format.
-25215043 0The formatted phone number displayed in the infoWindow is returned in the placeDetails response, which happens when the marker is clicked, it isn't available in the nearbySearch response, which is used to create the sidebar.
-23996375 0 Can't resolve a LocaleI have a problem with Locale's. I'm trying to do a simple thing where I can choose english or german. So I have two property files called messages_en and messages_de. So far these files have a single line:
contactbook = Contact Book and
contactbook = Adressbuch respectively.
Now in my JSP view I have this :
<spring:message code="contactbook"/> The idea is that the message in the view changes depending on which locale we're using. Now the locale itself should be changed with this line:
<a href="?language=en">English</a>|<a href="?language=de">German</a> If I remove the everything works great but of course it's not locale specified. So the rest of the view is good.
In my dispatcher-servlet.xml file I have this:
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"> <property name="defaultLocale" value="en" /> </bean> <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"> <property name="paramName" value="language" /> </bean> <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" > <property name="interceptors"> <list> <ref bean="localeChangeInterceptor" /> </list> </property> </bean> Again, without it everything works well. There's something wrong with my understanding here. The localeChangeInterceptor stops any change done to the locale and the ControllerClassNameHandlerMapping does what? I keep on looking at my controller and wondering should I add something to it but it seems to me that all these lines in the dispatcher should be enough.
The exception I get is
No message found under code 'contactbook' for locale 'en' Despite a myriad of examples out there I keep on failing to understand or resolve the problem. Any help would be greatly appreciated.
-31122222 0 Quickfixj not honoring custom fields in a repeating groupI am using FIXT1.1 and FIX Application version 5.0SP2.
I added some custom fields to the QuotSetAckGrp, part of MassQuoteAcknowledgement message. However, when quickfix reads the repeating group, it does not read the custom fields as part of the repeating groups. Instead, it treats the custom fields are regular parent-level fields and throws a "Tag appears more than once" session level reject.
Appreciate any inputs to help resolve the issue.
-34061473 0You can convert with strtotime() to safely date-manipulating and then you can reorder the array:
$dates = array( '2015-02-13', '2015-04-21', '2015-08-18', '2015-11-26', '2015-09-15', '2015-01-07', '2015-02-11', '2015-07-14', '2015-03-02', ); $newArray = array(); foreach($dates as $value) { $newArray[] = strtotime($value); } sort($newArray); var_dump($newArray);
-31258582 0 Replace
x = document.getElementById("show").innerHTML = verse; with
x = document.getElementById("show").innerHTML = document.getElementById("show").innerHTML + verse; I hope this helps.
Thanks, Charles.
-13084499 0I came into this problem today. After some testing, I got this working, without using temorary element.
In IE, it's easy to work it out with offsetLeft and offsetTop property of a TextRange object. Some effort is needed for webkit though.
Here's a test, you can see the result. http://jsfiddle.net/gliheng/vbucs/12/
var getCaretPixelPos = function ($node, offsetx, offsety){ offsetx = offsetx || 0; offsety = offsety || 0; var nodeLeft = 0, nodeTop = 0; if ($node){ nodeLeft = $node.offsetLeft; nodeTop = $node.offsetTop; } var pos = {left: 0, top: 0}; if (document.selection){ var range = document.selection.createRange(); pos.left = range.offsetLeft + offsetx - nodeLeft + 'px'; pos.top = range.offsetTop + offsety - nodeTop + 'px'; }else if (window.getSelection){ var sel = window.getSelection(); var range = sel.getRangeAt(0).cloneRange(); try{ range.setStart(range.startContainer, range.startOffset-1); }catch(e){} var rect = range.getBoundingClientRect(); if (range.endOffset == 0 || range.toString() === ''){ // first char of line if (range.startContainer == $node){ // empty div if (range.endOffset == 0){ pos.top = '0px'; pos.left = '0px'; }else{ // firefox need this var range2 = range.cloneRange(); range2.setStart(range2.startContainer, 0); var rect2 = range2.getBoundingClientRect(); pos.left = rect2.left + offsetx - nodeLeft + 'px'; pos.top = rect2.top + rect2.height + offsety - nodeTop + 'px'; } }else{ pos.top = range.startContainer.offsetTop+'px'; pos.left = range.startContainer.offsetLeft+'px'; } }else{ pos.left = rect.left + rect.width + offsetx - nodeLeft + 'px'; pos.top = rect.top + offsety - nodeTop + 'px'; } } return pos; };
-7255458 0 How can i control output from crontab? I am trying to run a test case via automation testing (sahi) , so I am running the command for it repeatedly after 1 hour (via crontab).
What I want is that is there any solution that whenever my test case fails i should receive the email otherwise not.. Right now I am reciving mail whether it passes or fails.
In short, can i send mail to a person depending upon the output i get in terminal.
I want to send mail when output will be:
1 scenario (1 failed) 4 steps (3 skipped, 1 failed) 0m2.476s
Thanks.
-17747238 0The classpath of javac should refer to directories and jar files containing the root of compiled class files trees. It should not refer to Java files.
Similarly, the source directory should refer to the root of the package tree of the source files. Not to directories corresponding to packages, inside the package tree.
Your compile task should look like
<target name="main-compile"> <javac includeantruntime="false" srcdir="src/main/java" destdir="${gen.bin.main.dir}" debug="on" includes="com/myapp/api/**/*.java, com/myapp/impl/core/FizzImpl/**/*.java"> <classpath refid="lib.main.path"/> </javac> </target>
-32708767 0 I experienced this problem and the fix, for me at least, was to set the HOME variable in the crontab to the path of the home directory of the user that the cronjob was being run as. It was previously being set to '/'.
-23335583 0Its server side problem, its nothing to do with android. For this make sure that your sever code capable to handle multiple request at a time.
-33811276 0You can simply configure profile recognition in Print&Share. This video example uses a profile with a Printer Channel and one with a File Printer Channel: https://www.youtube.com/watch?v=nvTly9qXQMI&list=PLDF2C2AD95B2B2FC2&index=38
You can easily create a profile with only Printer Channels, as you wish. This way you only have to print and the software will select the correct profile or A or B automatically (if you enable "Auto Send & Close" it will also print automatically without showing the user interface).
-23231159 0The second option allows you to do more complex formatting. With a string, there is little advantage, but if you were using a double value, for example, you could use the composite format options to specify the amount of precision to display or other options.
To reorder the items, a basic way could be as follows:
split_line = line.split(" ") column_mapping = [9,6,3,7,3,2,1] reordered = [split_line[c] for c in column_mapping] joined = ",".join(reordered) outfile.write(joined) This splits up the string, reorders it according to column_mapping and then combines it back into one string (comma separated)
(in your code don't include column_mapping in the loop to avoid reinitialising it)
Comparing user-visible strings is generally considered bad practice (and becomes tedious when you need to do i18n), especially with string literals since it's vulnerable to typos.
If you're just going to toggle between two states, the easiest thing to do is to use the UIControl.selected property (corresponding to UIControlStateSelected):
// In init [myButton setTitle:@"test" forState:UIControlStateNormal]; [myButton setTitle:@"test2" forState:UIControlStateSelected]; [myButton setTitle:@"test2" forState:UIControlStateSelected|UIControlStateHighlighted]; // Toggle myButton.selected = !myButton.selected; It also makes the code a lot cleaner when you when you decide to toggle the button image/background/text colours too.
Note the slight gotcha: If you don't set the title for UIControlStateSelected|UIControlStateHighlighted it will use the title for UIControlStateNormal when the button is both selected and highlighted (touched).
I've set up EGit in Eclipse for a few of my projects and find that its a lot easier, faster to use a command line interface versus having to drill down menus and click around windows.
I would prefer something like a command line view within Eclipse to do all the Git duties.
-25733192 0 Batch File - Creating multiple files with different namesI have a batch file and it contains the following code:
@echo off color 0e :initialize set filemaker=1 echo How many files? echo. set /p uservar= echo Creating... for /l %%x in (1, 1, %uservar%) do echo. 2>%CD%\%filemaker%.txt & set /a filemaker=%filemaker%+1 & timeout /t 1 /nobreak >nul echo %filemaker% pause And everytime I execute it, the file that are generated (regardless of the value of %uservar%) is ALWAYS name 2, and there is always ony one file! I would like multiple with different names like, file 1 is name 1, file 2 is name 2, and so on.
Any help is appreciated!
-2204702 0The class defining __slots__ (and not __getstate__) can be either an ancestor class of yours, or a class (or ancestor class) of an attribute or item of yours, directly or indirectly: essentially, the class of any object in the directed graph of references with your object as root, since pickling needs to save the entire graph.
A simple solution to your quandary is to use protocol -1, which means "the best protocol pickle can use"; the default is an ancient ASCII-based protocol which imposes this limitation about __slots__ vs __getstate__. Consider:
>>> class sic(object): ... __slots__ = 'a', 'b' ... >>> import pickle >>> pickle.dumps(sic(), -1) '\x80\x02c__main__\nsic\nq\x00)\x81q\x01.' >>> pickle.dumps(sic()) Traceback (most recent call last): [snip snip] raise TypeError("a class that defines __slots__ without " TypeError: a class that defines __slots__ without defining __getstate__ cannot be pickled >>> As you see, protocol -1 takes the __slots__ in stride, while the default protocol gives the same exception you saw.
The issues with protocol -1: it produces a binary string/file, rather than an ASCII one like the default protocol; the resulting pickled file would not be loadable by sufficiently ancient versions of Python. Advantages, besides the key one wrt __slots__, include more compact results, and better performance.
If you're forced to use the default protocol, then you'll need to identify exactly which class is giving you trouble and exactly why. We can discuss strategies if this is the case (but if you can possibly use the -1 protocol, that's so much better that it's not worth discussing;-) and simple code inspection looking for the troublesome class/object is proving too complicated (I have in mind some deepcopy-based tricks to get a usable representation of the whole graph, in case you're wondering).
If you really mean ASCII, you can't possibly rescue Hebrew characters. ASCII is only the 7-bit character set up to \x7F.
So what kind of strings does this Windows program read? If it's ASCII, or Latin-1, you'll never get Hebrew. More likely it's “the current system code page”, also (misleadingly but commonly) known in Windows as ‘ANSI’.
If that's the case you will have to set the system code page on every machine that runs the Windows program to Hebrew (code page 1255). I believe shp files have no character encoding information at all, so the shapefiles will only ever work correctly on machines with this code page set (the default only in the Israel locale). (Apparently .dbf exports can have an accompanying .cpg file to specify the encoding, but I've no idea if the program you're using supports that.)
Then you'd have to export the data as code page 1255, or the nearest you're going to get in Postgres, ISO-8859-8. Since the export script doesn't seem to have any option to do anything but take direct bytes from the database, you'd have to create a database in the ISO-8859-8 encoding and transfer all the data from the UTF-8 database to the 8859-8 one, either directly through queries or, perhaps easier, using pgdumpall and loading the SQL into Notepad then re-saving it as Hebrew instead of UTF-8 (adjusting any encoding settings listed in SQL DDL as you go).
I wonder if the makers of the Windows program could be persuaded to support UTF-8? It's a bit sad to be stuck with code-page specific software in this century.
-18759997 0 How does iOS handle local Notification in background mode?didReceiveLocalNotification is called when a notification is fired in active mode but how does iOS handles notification in background mode (not active mode, application is terminated may be) before app is active by swiping or clicking the notification.
Or
Mainly I want to know how to conditionally handle local notification to be on/off (off means not to cancel previous notification but just don't fire it) in background Mode?
I am currently checking this condition in didReceiveLocalNotification but that way I am not able to handle it in background mode?
I'm having some problems, when I do my query from my vb.net program to my mysql DB the data is sent, but its missing some things, let me explain.
My query is pretty simple I'm sending a file path to my DB so that after I can have a php website get the data and make a link with the data from my DB, but when I send my data the results look like this...
\server_pathappsInst_pcLicences_ProceduresDivers estCheck_list.doc which should look like
\\server_path\apps\Inst_pc\Licences_Procedures\Divers\test\Check_list.doc I don't know if its my code that's not good or my configurations on my mysql server please help...
Here's my code
'Construct the sql command string cmdString = "INSERT into procedures(Nom, Lien_Nom, Commentaires) VALUES('" & filenameOnly_no_space_no_accent & "', '" & str_Lien_Nom_Procedure & "', '" & str_commentaires_Procedure & "')" ' Create a mysql command Dim cmd As New MySql.Data.MySqlClient.MySqlCommand(cmdString, conn) Try conn.Open() cmd.ExecuteNonQuery() conn.Close() Catch ex As MySqlException MsgBox("Error uppdating invoice: " & ex.Message) Finally conn.Dispose() End Try Sorry I got a call and could continue my comment so here's the rest :X
Well I guess that would work, but my program never uses the same path since in uploading a file on a server, so this time the document I wanted to upload was this path
\\Fsque01.sguc.ad\apps\Inst_pc\Licences_Procedures\Divers\test\Check_list.doc but next time its going to be something else so I can't hard code the paths, I was looking more of a SQL query which that I might not know, since I already thought about searching my string and if it finds a backslash it adds another one, but I feel its not a good way to script the whole thing...
Anyway thanks a lot for your help
-38237010 0Add isEqualTo(:) requirement to JABPanelChangeSubscriber protocol
public protocol JABPanelChangeSubscriber { func isEqualTo(other: JABPanelChangeSubscriber) -> Bool } Extension to JABPanelChangeSubscriber protocol with Self requirement
extension JABPanelChangeSubscriber where Self: Equatable { func isEqualTo(other: JABPanelChangeSubscriber) -> Bool { guard let other = other as? Self else { return false } return self == other } } Remember to make objects conform
Equatableprotocol too
class SomeClass: Equatable {} func == (lhs: SomeClass, rhs: SomeClass) -> Bool { //your code here //you could use `===` operand } struct SomeStruct: Equatable {} func == (lhs: SomeStruct, rhs: SomeStruct) -> Bool { //your code here } Then find the index
func indexOf(object: JABPanelChangeSubscriber) -> Int? { return subcribers.indexOf({ $0.isEqualTo(object) }) } If you want to check the existence of an object before adding them to the array
func addSubscriber(subscriber: JABPanelChangeSubscriber) { if !subscribers.contains({ $0.isEqualTo(subscriber) }) { subscribers.append(subscriber) } }
-32378194 0 the error messages are "expected illegal start of type" on writeUTF method.
The problem is that you have put statements into a class body.
The those statements need to go into a method. Your text book or tutorial should explain this.
-26643484 0So thanks to Guffa I realized that even though I had broken the push statement into different lines, it was treated as one. I had thought the problem was with my .push implementation, but rather it was a problem with one of the variables being pushed.
It turns out I had missed a return on
var callExtData = checkCallExtensions(campaign); and so callExtData was empty, hence undefined.
Thanks!
-18091654 0This is a specific case of the general CSV parsing problem. The general solution is provided by Lorance Stinson (google Stinson awk CSV parser) but IMHO the simplest way to deal with this specific issue is to convert newlines within double quotes to some other character, do whatever you want with the file in single-line-per-record format, then convert back, e.g.:
$ cat file "Test_data1" "Test_data2" "1s" "452" "Test data643" " " "4d" "System" "Institute" "Test_data3" "Test_data4" "2s" "563" "Test data754" " " "5d" "Non System" "Association" To convert to single line:
$ awk -v FS= '{for (i=1;i<=NF;i++) if ($i=="\"") inQ=!inQ; ORS=(inQ?"♥":"\n") }1' file "Test_data1" "Test_data2" "1s" "452" "Test♥data643" "♥" "4d" "System" "Institute" "Test_data3" "Test_data4" "2s" "563" "Test♥data754" "♥" "5d" "Non System" "Association" and to convert back is a simple tr:
$ awk -v FS= '{for (i=1;i<=NF;i++) if ($i=="\"") inQ=!inQ; ORS=(inQ?"♥":"\n") }1' file | tr '♥' ' \n' "Test_data1" "Test_data2" "1s" "452" "Test data643" " " "4d" "System" "Institute" "Test_data3" "Test_data4" "2s" "563" "Test data754" " " "5d" "Non System" "Association" The above uses control-C as a replacement for the newline within quotes, pick whatever character you like (or string if you want to use awk or sed rather than tr to convert back to newlines).
Just insert the command to do whatever you want with your original file in between the awk and the tr, e.g. sort in reverse:
$ awk -v FS= '{for (i=1;i<=NF;i++) if ($i=="\"") inQ=!inQ; ORS=(inQ?"♥":"\n") }1' file | sort -r | tr '♥' '\n' "Test_data3" "Test_data4" "2s" "563" "Test data754" " " "5d" "Non System" "Association" "Test_data1" "Test_data2" "1s" "452" "Test data643" " " "4d" "System" "Institute"
-27767148 0 You have to register the Provider in a javax.ws.rs.core.Application. That Application should be registered as a service with a higher service ranking than the default one created by the Amdatu Wink bundle.
The following is a working example.
The Exception Mapper itself:
@Provider public class SecurityExceptionMapper implements ExceptionMapper<SecurityException>{ @Override public Response toResponse(SecurityException arg0) { return Response.status(403).build(); } } The Application:
import java.util.HashSet; import java.util.Set; import javax.ws.rs.core.Application; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; public class MyApplication extends Application { @Override public Set<Object> getSingletons() { Set<Object> s = new HashSet<Object>(); s.add(new JacksonJsonProvider()); s.add(new SecurityExceptionMapper()); return s; } } Activator setting the service ranking property.
public class Activator extends DependencyActivatorBase{ @Override public void destroy(BundleContext arg0, DependencyManager arg1) throws Exception { } @Override public void init(BundleContext arg0, DependencyManager dm) throws Exception { Properties props = new Properties(); props.put(Constants.SERVICE_RANKING, 100); dm.add(createComponent().setInterface(Application.class.getName(), props).setImplementation(MyApplication.class)); } }
-25863380 0 angularjs Rest API I've read up many articles on angularjs and REST but could not found any solution. Through java script I am calling api method, which is routed method as:
[Route("api/Comments/{docId}/comment/{revId}/get/{size}/getNumber/{number}")] [HttpPost] public IEnumerable<Student> Get(int docId,int revId,int size, int number) { // loadienter code hereng list here return list.ToList(); } //java script code var url='api/students/' + docId + '/student/' + revId + '/get/'+size+'/getNumber/'+number'; $http.get(url).success(function (response) { if (callback) callback(response.result); }; But the method in controller class is not executing..How to solve this issue? P Please give me some suggestions..
-34711110 0 What is causing "The type or namespace name 'UI' does not exist in the namespace" error?I am working on a UWP application and I am trying to do something with the values of a SelectedItem in a GridView. So as I usually do with WPF I went into the XAML and Typed my event name in the XAML and let VS create the event in code for me.
<GridView x:Name="DataGrid1" ItemClick="dg_ItemClick"> <!-- Just --> <!-- Some --> <!-- Normal --> <!-- XAML --> </GridView> and the VS created event looks like this
private void dg_ItemClick(object sender, Windows.UI.Xaml.Controls.ItemClickEventArgs e) { Biz.Customer cust = e.ClickedItem as Biz.Customer; var messageDialog2 = new MessageDialog(cust.Code, cust.Company); messageDialog2.ShowAsync(); } Right away I get a red squiggly line under the UI in the Windows.UI.Xaml.Controls part. There is a using at the top of the page to include that and VS wouldn't let add any other UWP references.
I can get the error to go away as I have in other parts of the application by changing the ItemClickEventArgs to RoutedEvenArgs but in this case I really need the ClickedItem as an argument to be passed to the code behind.
I have just talked to someone else getting started with UWP and they said they are having the same issue on other cLick events. So are we both doing something wrong or is there something missing from our application that is needed for the UI to be recognized?
The full error I am getting is this: Error CS0234 The type or namespace name 'UI' does not exist in the namespace 'app name' (are you missing an assembly reference?)
-32811632 0https://developer.android.com/training/basics/actionbar/styling.html
Here you have everything explained in detail about styling the Action Bar.
Best regards
-32996138 0 Different Layout Managers in an ActivityI have two different kinds of data that one of them needs to be displayed in a grid (the red ones) and the other needs to be displayed linear (the blue ones). the whole page scrolls and the data sources may change so the views should update dynamically. How can I implement this in android and probably with RecyclerView? 
SELECT a.* FROM tableName a INNER JOIN ( SELECT `Cut-off`, COUNT(*) totalCOunt FROM tableName GROUP BY `Cut-off` HAVING COUNT(*) > 1 ) b ON a.`Cut-off` = b.`Cut-off` for faster performance, add an INDEX on column Cut-off
It's very simple.
<div data-role="header" data-position="fixed" data-tap-toggle="false"> </div> It works for me.
-13509500 0Create a ten-branch index tree, record the number of children of each node. Then browse the tree, stop at the node whose child number is ten.
-4343680 0You might want to look into the strchr function which searches a string for a given character:
include <string.h> char *strchr (const char *s, int c); The strchr function locates the first occurrence of c (converted to a char) in the string pointed to by s. The terminating null character is considered to be part of the string.
The strchr function returns a pointer to the located character, or a null pointer if the character does not occur in the string.
Something like:
if (strchr (",.();:-\"&?%$![]{}_<>/#*_+=", curChar) != NULL) ... You'll have to declare curChar as a char rather than a string and use:
curChar = paragraph[subscript]; rather than:
curChar = paragraph.substr(subscript, 1); but they're relatively minor changes and, since your stated goal was I want to change the if statement into [something] more meaningful and simple, I think you'll find that's a very good way to achieve it.
I´m currently working on a dashboard styled project, where i need to have gauges to display current values.
can someone point me to some commercial or open source asp.net ajax controls that include gauges with these capabilities?
Thanks in advance!
-31657146 0Another example in JDK - java.lang.Throwable
private Throwable cause = this; The cause field can be in 3 states - unset; set to null; set to another Throwable.
The implementer uses this to represent the unset state.
A more readable strategy is probably to define a sentinel value for unset
static Throwable UNSET = new Throwable(); private Throwable cause = UNSET; of course, there's a recursive dependency - UNSET.cause=? - which is another fun topic.
I'd just use standard java java.awt.Point. Nothing additional needed.
like
Vector<Point> myVec = new Vector<Point>; you can still use these 2D Points like
int key; int value; Point point = new Point(key, value); myVec.add(point); and if you want to check the entries for a spec element
for(Point p : myVec) { if(p[0] == searchKey) //...do something }
-3342710 0 one of the easier ways is to harden your php.ini config, specifically the open_basedir directive. Keep in mind, some CMS systems do actually use ..\ quite a bit in the code, and when there are includes outside the root folder this can create problems. (i.e. pear modules)
Another method is to use mod_rewrite.
Unless you are using an include file to check each and every URL for injection from $_GET and $_SERVER['request_uri'] variables, you will open doors for this kind of attack. for example, you might protect index.php but not submit.php. This is why hardening php.ini and .htaccess is the preferred method.
I am using Opera and sometimes a page keeps on loading even though all content has already been presented. How do I find out which elements are to be loaded or what causes the ongoing loading process?
-34854760 0 Issue with EdgeNGramFilterFactory filter class and multiple diactric character in a wordI have indexed BLÅBÆRSOMMEREN into Solr and I have added EdgeNGramFilterFactory filter class like this:
<fieldType name="nGramtext" class="solr.TextField" positionIncrementGap="100"> <analyzer type="index"> <charFilter class="solr.HTMLStripCharFilterFactory"/> <charFilter class="solr.MappingCharFilterFactory" mapping="mapping-ISOLatin1Accent.txt"/> <tokenizer class="solr.StandardTokenizerFactory"/> <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" /> <filter class="solr.LowerCaseFilterFactory"/> <filter class="solr.EdgeNGramFilterFactory" minGramSize="3" maxGramSize="15" /> <filter class="solr.EdgeNGramFilterFactory" minGramSize="3" maxGramSize="15" /> <filter class="solr.PorterStemFilterFactory"/> </analyzer> Now, if I search with whole word: BLÅBÆRSOMMEREN it gives me result, but if I search with BLÅB or BLÅBÆRSOMM it does not give me result. Note I have perform edismax query on this field
As per the documentation here I guess, it should work with all these words but it does not.
I have integrated Solr for an eCommerce Site. Initially I have configure that word in Name field and it won't work. Then I have configured that word in Short Description field only(Removed from Name).
After this I have performed query and it works. Note: both fields have same field type.
<field name="Name" type="text" indexed="true" stored="true" required="false" /> <field name="ShortDescription" type="text" indexed="true" stored="true" required="false" /> Moreover, there are copyfield like:
<copyfield source="Name" dest="nGramContent"/> <copyField source="ShortDescription" dest="nGramContent"/> What I did wrong here? Please help! How can I achieve this?
-30125535 0 How do I validate data in a file in SSIS before inserting into a database?What I want to do is take data from a dbf file and insert it in a table. Which I've already done. Since there are many files, a For-Each Container is being used. However, before inserting it into a table, I want to look at the date fields and compare it to a date variable. If the dates match the variable, then move on to the step of the flow. But if any of the dates don't match the variable, then that file and its contents are discarded and the next file is looked at.
How do I accomplish this in SSIS?
-14236753 0Depending on the number of conditional inputs, you might be able to use a look-up table, or even a HashMap, by encoding all inputs or even some relatively simple complex conditions in a single value:
int key = 0; key |= a?(1):0; key |= b?(1<<1):0; key |= (c.size() > 1)?(1<<2):0; ... String result = table[key]; // Or result = map.get(key); This paradigm has the added advantage of constant time (O(1)) complexity, which may be important in some occasions. Depending on the complexity of the conditions, you might even have fewer branches in the code-path on average, as opposed to full-blown if-then-else spaghetti code, which might lead to performance improvements.
We might be able to help you more if you added more context to your question. Where are the condition inputs coming from? What are they like?
And the more important question: What is the actual problem that you are trying to solve?
-40565252 0If you were to use arccos you would need the length from one point to the other and the x distance from one point to the other.
However with arctan you only need the x distance and the y distance.
x and y distances are easy to work out because you just have to minus one coordinate from the other. However the distance between the 2 points is more complicated to work out. This is why it it easier to use arctan instead of arccos, however they can both be used (even arcsin and other inverse trigonometric functions).
-13282983 0It's just syntactic sugar -- the compiler inserts the backing field for you. The effect is the same, except that, of course, there's no way for you to access the backing field from your code.
From the page you linked to:
-2083197 0 keep track of object changes in datagridview using the entity frameworkWhen you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.
I'm using a DataGridView to display EntityObjects from the .NET Entity Framework.
how could I change the formatting of a row of the DataGridView if the corresponding EntityObject has been altered by the user, e.g. displaying the row in bold
greetings
-2837018 0You can use com_print_typeinfo() instead of var_dump(). This should work for COM, VARIANT and DOTNET objects. The output looks similar to this:
class IFile { /* GUID={C7C3F5A4-88A3-11D0-ABCB-00A0C90FFFC0} */ // some PHP-COM internal stuff ... /* DISPID=1610612736 */ function QueryInterface( /* VT_PTR [26] [in] --> ? [29] */ &$riid, /* VT_PTR [26] [out] --> VT_PTR [26] */ &$ppvObj ) { } /* DISPID=1610612737 */ /* VT_UI4 [19] */ function AddRef( ) { } // ... /* DISPID=1610678275 */ function Invoke( /* VT_I4 [3] [in] */ $dispidMember, /* VT_PTR [26] [in] --> ? [29] */ &$riid, /* VT_UI4 [19] [in] */ $lcid, /* VT_UI2 [18] [in] */ $wFlags, /* VT_PTR [26] [in] --> ? [29] */ &$pdispparams, /* VT_PTR [26] [out] --> VT_VARIANT [12] */ &$pvarResult, /* VT_PTR [26] [out] --> ? [29] */ &$pexcepinfo, /* VT_PTR [26] [out] --> VT_UINT [23] */ &$puArgErr ) { } // properties and methods of the COM object // ... /* DISPID=1001 */ /* VT_BSTR [8] */ /* Short name */ var $ShortName; /* DISPID=1004 */ /* VT_PTR [26] */ /* Get drive that contains file */ var $Drive; /* DISPID=1005 */ /* VT_PTR [26] */ /* Get folder that contains file */ var $ParentFolder; // ... /* DISPID=1204 */ function Move( /* VT_BSTR [8] [in] */ $Destination ) { /* Move this file */ } /* DISPID=1100 */ /* VT_PTR [26] */ function OpenAsTextStream( /* ? [29] [in] */ $IOMode, /* ? [29] [in] */ $Format ) { /* Open a file as a TextStream */ } }
-13838071 0 What was said above is right: You can't prevent an auto-implemented property from being serialized by setting an attribute like [NonSerialized]. It just does not work.
But what does work is the [IgnoreDataMember] attribute in case you are working with an WCF [DataContract]. So
[DataContract] public class MyClass { [DataMember] public string ID { get; set; } [IgnoreDataMember] public string MySecret { get; set; } } will get serialized under WCF.
Although since WCF is an opt-in technology, you can also just omit the [IgnoreDataMember] and it will work as well. So maybe my comment is a little academical ;-)
-8603188 0SWI-Prolog library(http/html_write) library builds on DCG a DSL for page layout.
It shows a well tought model for integrating Prolog and HTML, but doesn't attempt to cover the entire problem. The 'residual logic' on the client side remains underspecified, but this is reasonable, being oriented on practical issues 'reporting' from RDF.
Thus the 'small detail' client interaction logic is handled in a 'black box' fashion, and such demanded to YUI components in the published application (the award winner Cliopatria).
The library it's extensible, but being very detailed, I guess for your task you should eventually reuse just the ideas behind.
-26810978 0 background-image with a left and right, the repeat-x of center image makes the right image not show up.news-header { background-image: url(maureske_green_left.gif), url(maureske_green_body.gif), url(maureske_green_right.gif); background-position: left, center, right; background-repeat: no-repeat, repeat-x, no-repeat; height: 31px; } This works good but the repeat-x of maureske_green_body.gif makes maureske_green_right.gif to not show up.
Setting a width doesnt make the right image to show neither.
If I do no-repeat on the center image all images show up but of course theres a gap between all three. So how do I fix without making center image same width as webpage?
Thanks in advance!
Jarosław
-22168426 0 How to display the time on the right footer when inserting a card?I'm using GDK TimelineManager to insert a static card to the timeline, and I noticed that there's no just now or something like that displayed on the right footer.
What am I doing wrong? Is the time just for the Mirror API or am I missing something here?
-22207737 0 using jquery validate plugin in asp.net controls not workingI am trying to use the jquery plugin validate() method to validate a div in my current sharepoint visual webpart. I am not sure why this is not working. it does nothing at all.
Here is the code.
<div id="main" runat="server"> <h3>2. Select your study subject.<span class="red">*</span></h3> <asp:RadioButtonList CssClass="required" ID="rdb_study_popul" runat="server" OnSelectedIndexChanged="rdb_study_popul_SelectedIndexChanged"> <asp:ListItem>Individuals</asp:ListItem> <asp:ListItem>Population</asp:ListItem> </asp:RadioButtonList> </div> <asp:Button ID="btn_studysubject_section" runat="server" CssClass="WBSButtonhide" OnClick="btn_studysubject_section_Click" Text="Next"/> here is the jquery
$("input[type='submit']").click(function () { if ($(this).val() != 'Back') { var names = []; var info = " "; $('#<%= main.ClientID %>').validate({ rules: { <%= rdb_study_popul.ClientID%> : { required: true } }, messages: { <%= rdb_study_popul.ClientID%> : "This field cannot be empty, please enter between" } }); } });
-7856420 0 You can't really ask a question about assembly code without mentioning what kind of processor assembly code you're talking about. For example, many processors have a dedicated instruction for counting number of bits set. For example, see POPCNT
-30332584 0 ListView inside fragment errormy fragment :
public class NewsFragment extends ListFragment { private ProgressDialog pDialog; // URL to get contacts JSON private static String url = "url"; // JSON Node names private static final String TAG_NEWS = "news"; private static final String TAG_ID = "id"; private static final String TAG_JUDUL = "judul"; private static final String TAG_TGL = "tanggal"; private static final String TAG_ISI = "isi"; private static final String TAG_SUMBER = "sumber"; private static final String TAG_GAMBAR = "gambar"; // contacts JSONArray JSONArray news = null; // Hashmap for ListView ArrayList<HashMap<String, String>> newsList; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View newsView = inflater.inflate(R.layout.fragment_news, container, false) ; newsList = new ArrayList<HashMap<String, String>>(); ListView lv = getListView(); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // getting values from selected ListItem String judul = ((TextView) view.findViewById(R.id.judul)) .getText().toString(); String tanggal = ((TextView) view.findViewById(R.id.tglPublish)) .getText().toString(); String sumber = ((TextView) view.findViewById(R.id.sumber)) .getText().toString(); // Starting single contact activity Intent in = new Intent(getActivity().getApplicationContext(), NewsDetailActivity.class); in.putExtra(TAG_JUDUL, judul); in.putExtra(TAG_TGL, tanggal); in.putExtra(TAG_SUMBER, sumber); startActivity(in); } }); // Calling async task to get json new GetNews().execute(); return newsView ; } /** * Async task class to get json by making HTTP call * */ private class GetNews extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); // Showing progress dialog pDialog = new ProgressDialog(getActivity()); pDialog.setMessage("Mohon tunggu..."); pDialog.setCancelable(false); pDialog.show(); } @Override protected Void doInBackground(Void... arg0) { // Creating service handler class instance ServiceHandler sh = new ServiceHandler(); // Making a request to url and getting response String jsonStr = sh.makeServiceCall(url, ServiceHandler.POST); Log.d("Response: ", "> " + jsonStr); if (jsonStr != null) { try { JSONObject jsonObj = new JSONObject(jsonStr); // Getting JSON Array node news = jsonObj.getJSONArray(""); // looping through All Contacts for (int i = 0; i < news.length(); i++) { JSONObject c = news.getJSONObject(i); String id = c.getString(TAG_ID); String judul = c.getString(TAG_JUDUL); String tgl = c.getString(TAG_TGL); String sumber = c.getString(TAG_SUMBER); // String gambar = c.getString(TAG_GENDER); // tmp hashmap for single contact HashMap<String, String> news = new HashMap<String, String>(); // adding each child node to HashMap key => value news.put(TAG_ID, id); news.put(TAG_JUDUL, judul); news.put(TAG_TGL, tgl); news.put(TAG_SUMBER, sumber); // adding contact to contact list newsList.add(news); } } catch (JSONException e) { e.printStackTrace(); } } else { Log.e("ServiceHandler", "Couldn't get any data from the url"); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); // Dismiss the progress dialog if (pDialog.isShowing()) pDialog.dismiss(); /** * Updating parsed JSON data into ListView * */ ListAdapter adapter = new SimpleAdapter( getActivity().getApplicationContext(), newsList, R.layout.list_item, new String[] { TAG_JUDUL, TAG_TGL, TAG_SUMBER }, new int[] { R.id.judul, R.id.tglPublish, R.id.sumber }); setListAdapter(adapter); } } } my xml :
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:layout_marginLeft="12dp" android:layout_marginRight="12dp"> <!-- Main ListView Always give id value as list(@android:id/list) --> <ListView android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="wrap_content"/> </LinearLayout> list_item.xml :
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="10dp" android:paddingLeft="10dp" android:paddingRight="10dp" > <!-- Judul --> <TextView android:id="@+id/judul" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingBottom="2dip" android:paddingTop="6dip" android:textColor="#43bd00" android:textSize="16sp" android:textStyle="bold" /> <!-- Tgl Publish --> <TextView android:id="@+id/tglPublish" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingBottom="2dip" android:textColor="#acacac" /> <!-- Sumber --> <TextView android:id="@+id/sumber" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="left" android:textColor="#5d5d5d" android:textStyle="bold" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> and error log :
05-20 00:24:41.091 20376-20376/com.emaszda.nutrisibunda E/AndroidRuntime﹕ FATAL EXCEPTION: main java.lang.IllegalStateException: Content view not yet created at android.support.v4.app.ListFragment.ensureList(ListFragment.java:328) at android.support.v4.app.ListFragment.getListView(ListFragment.java:222) at com.emaszda.nutrisibunda.NewsFragment.onCreateView(NewsFragment.java:58) at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:953) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1136) at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739) at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1499) at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:488) at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141) at android.support.v4.view.ViewPager.populate(ViewPager.java:1073) at android.support.v4.view.ViewPager.populate(ViewPager.java:919) at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441) at android.view.View.measure(View.java:15891) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5035) at android.widget.FrameLayout.onMeasure(FrameLayout.java:310) at android.view.View.measure(View.java:15891) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5035) at android.support.v7.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:453) at android.view.View.measure(View.java:15891) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5035) at android.widget.FrameLayout.onMeasure(FrameLayout.java:310) at android.view.View.measure(View.java:15891) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5035) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404) at android.widget.LinearLayout.measureVertical(LinearLayout.java:695) at android.widget.LinearLayout.onMeasure(LinearLayout.java:588) at android.view.View.measure(View.java:15891) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5035) at android.widget.FrameLayout.onMeasure(FrameLayout.java:310) at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2208) at android.view.View.measure(View.java:15891) at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1957) at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1156) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1336) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1056) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5542) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749) at android.view.Choreographer.doCallbacks(Choreographer.java:562) at android.view.Choreographer.doFrame(Choreographer.java:532) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735) at android.os.Handler.handleCallback(Handler.java:730) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:5162) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:525) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:756) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:572) at miui.dexspy.DexspyInstaller.main(DexspyInstaller.java:171) at dalvik.system.NativeStart.main(Native Method)
-33095149 0 You pass JSON like that. ArrayList does not accept key and value pair. Then add your keys
JSON: [ "1", "2", "3", "4" ] @RequestMapping(method = RequestMethod.POST, value = "/read/ids/",headers="Accept=application/json") public ArrayList<String> test(@RequestBody ArrayList<String> ids) throws Exception { return ids; }
-17084600 0 $(document).ready(function() { $("a").click(function() { alert('............'); }); });
-16621600 0 Get the result for the last Task<> ( continuation)? I have this sample code :
Task<int> t1= new Task<int>(()=>1); t1.ContinueWith(r=>1+r.Result).ContinueWith(r=>1+r.Result); t1.Start(); Console.Write(t1.Result); //1 It obviously return the Result from the t1 task. ( which is 1)
But how can I get the Result from the last continued task ( it should be 3 {1+1+1})
Try this code,
private class MYWEBCLIENT extends WebViewClient { private ProgressDialog prDialog; @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); prDialog = ProgressDialog.show(activity, "", "Please wait..."); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); if (prDialog != null && prDialog.isShowing()) prDialog.dismiss(); } } Load webview code,
webViewInfo.getSettings().setJavaScriptEnabled(true); webViewInfo.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); webViewInfo.setWebViewClient(new MYWEBCLIENT()); webViewInfo.loadData("YOUR_URL_OR_HTML_FILE", "text/html", "UTF-8");
-28668605 0 If you are using some UI Terminal like SQLDeveloper or TOAD, you can achieve it using below code:
CREATE OR REPLACE INPUTPROCEDURE (LV_CHOICE IN VARCHAR2) AS BEGIN DBMS_OUTPUT.PUT_LINE('Enter Y to display Unauthorized records OR N to skip the display'); --SELECT &1 INTO lv_choice FROM DUAL; IF lv_choice <> 'Y' THEN DBMS_OUTPUT.PUT_LINE ('RECORDS WILL NOT BE DISPLAYED'); ELSE DBMS_OUTPUT.PUT_LINE ('RECORDS TO BE DISPLAYED ARE:'); END INPUTPROCEDURE; And Invoke the above Procedure like below:
DECLARE dyn_stmt VARCHAR2(200); b BOOLEAN := TRUE; BEGIN dyn_stmt := 'BEGIN INPUTPROCEDURE(:LV_CHOICE); END;'; EXECUTE IMMEDIATE dyn_stmt USING b; END;
-16028349 0 Your mistake is in translating 0 based to 1 based indexing. The arrays are 0 based. You're having them enter in a 1 based row. Then you want to add the 8 numbers around it. If they entered 0 based numbers and entered N, you'd want to sum [n-1], n, and n+1 for each row/column. To deal with 0 based, you want to do n-2, n-1, and n. But you're doing n-2 and n+2. You're also not calculating the middle of the rows anywhere near right.
Best practice is not even to do the math like that. It would be to read in the row/column number, then immediately subtract 1 to make it 0 based, and deal with it as 0 based from then on.
-11920400 0There are powerpoint presentaion slides on the following link:
http://aplcenmp.apl.jhu.edu/~davids/605741/handouts/6_SWT_Programming.pdf
Also you may have a look on pdf given on the following link:
http://www.loria.fr/~dutech/DDZ/SWT.pdf
-30434253 0 Cron job to identify multiple visits in the same url?using a PHP cron job, how can I output the users who visited the same page over 2 times ?
Here is the mySQL table
id - user - page - timestamp 340 - 1 - page1 - 2009-05-18 22:11:11 339 - 1 - page1 - 2009-05-18 22:10:01 337 - 1 - page1 - 2009-05-18 22:06:00 336 - 2 - page3 - 2009-05-18 22:00:00 335 - 2 - page3 - 2009-05-18 21:56:00
-33039602 0 Do not reinvent the wheel. There is already a tool that creates an executable package. See the documentation of Oracle: https://docs.oracle.com/javase/8/docs/technotes/guides/deploy/self-contained-packaging.html With this you can create native bundles (.exe on Windows) for different OS. From the page mentioned:
javapackager -deploy -native -outdir packages -outfile BrickBreaker -srcdir dist -srcfiles BrickBreaker.jar -appclass brickbreaker.Main -name "BrickBreaker" -title "BrickBreaker demo" The same can also be accomplished with an Ant task which might be easier to integrate. There is also the Maven plugin javax-maven-plugin.
-11258573 0I guess you could break it down
var row = cell.Row; var cell = wksheet.Cells(row, "J"); var value = cell.Value;
-7874928 0 One of the alternative ways you can do that (if you actually care much about space) is to store the hash in the binary form. Some details of how to do that may be found here; you'd probably want BINARY(32) for a SHA-256 hash.
-9906007 0Use the following code to convert content of file (text or csv) in String.
InputStream in; String str = ""; try { in = new URL(url).openStream(); int size = in.available(); for (int i = 0; i < size; i++) { char ch = (char) in.read(); str = str.concat(ch + ""); } in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
-8789496 0 Are you using the Timer in daemon mode? Please see this documentation which says what's a daemon thread.
/** * Creates a new timer whose associated thread may be specified to * {@linkplain Thread#setDaemon run as a daemon}. * A daemon thread is called for if the timer will be used to * schedule repeating "maintenance activities", which must be * performed as long as the application is running, but should not * prolong the lifetime of the application. * * @param isDaemon true if the associated thread should run as a daemon. */ public Timer(boolean isDaemon) { this("Timer-" + serialNumber(), isDaemon); } If you are using a daemon thread, application will not wait for this thread to finish so any pending operation in this thread is not guaranteed to finish. However, if it's not a daemon thread, the application will shutdown only after this thread finishes its last operation.
Coming to the closing of file handles, why don't you do that in the timer thread itself? If that cannot be done, Shudown hooks are the ideal way to do something at the application shutting down time.
So, you can have a common lock, which can be acquired by the timer for every task execution and the same lock can be acquired by the shutdown task to close the open file handles.
I hope that makes things clear.
-40360429 0According to Laravel's Documentation
Make sure to place the $HOME/.composer/vendor/bin directory (or the equivalent directory for your OS) in your $PATH so the laravel executable can be located by your system. In case of Windows you should ad that $PATH to your enviornment variables.
On processing get request to my @Controller method i get
2013-01-10 18:16:44,871 INFO [STDOUT] 2013-01-10 18:16:44 [http-0.0.0.0-8080-53] DEBUG org.springframework.web.servlet.DispatcherServlet.processRequest - Could not complete request org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.NoClassDefFoundError: java/util/Deque at org.springframework.web.servlet.DispatcherServlet.triggerAfterCompletionWithError(DispatcherServlet.java:1259) ~[spring-webmvc-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945) ~[spring-webmvc-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856) ~[spring-webmvc-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:915) [spring-webmvc-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:811) [spring-webmvc-3.2.0.RELEASE.jar:3.2.0.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:734) [javaee.jar:9.1] at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796) [spring-webmvc-3.2.0.RELEASE.jar:3.2.0.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) [javaee.jar:9.1] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.5.0_25] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) ~[na:1.5.0_25] I use spring 3.2, java 5, jboss 4.2
EDIT Problem was in thymeleaf and not in spring
-29422721 0 testing client bandwidth with asp.net mvcI want calculating client bandwidth in asp.net mvc and already I used JavaScript
<script language="javascript" type="text/javascript"> time = new Date(); time1 = time.getTime(); </script> <!-- Dummy Text to measure transfer speed --> <script language="javascript" type="text/javascript"> time = new Date(); time2 = time.getTime(); ttime = time2 - time1; if (ttime == 0) ttime = .1; ttime = ttime / 1000; //thousand mili seconds kbps = 45 / ttime; kbps = kbps * 8; // multiply by 8 to make kiloBITS instead of kiloBYTES kbps = Math.round (kbps); document.getElementById("lblBandwidth").innerHTML=kbps + " kbps"; </script> you can see this on http://www.whoismaster.ir/Home/BandwidthMeter but this is not accurate
how can used accurate code for this? I like used asp.net mvc with c# for exactly bandwidth
-24327662 0Post it as a string?
byte[] array = new byte[n]; array[0] = .. array[n] = .. String dataToSend = ""; For(int i = 0; i < array.length -1; i++){ dataToSend += (char) array[0]; } // your post code here ... pairs.add(new BasicNameValuePair("key1", dataToSend));
-27031291 0 Making table rows generated via JQuery act as onClick page redirects So I am pretty new to JQuery/HTML development of all kinds. Basically I am working on a project where I make an AJAX call that gets a bunch of usernames, dates, etc. regarding Craiglist-like sales that I put into a table format dynamically using JQuery and DOM.
I want to be able to make these elements in the table act as links so that if I click on a certain username, it will take me to their profile. I've tried different suggestions out there but none of them are for tables that are generated with JQuery and I think this is causing problems (but I don't think there is any way around that either). Some snippets of my code are as follows:
function displayCurrentSales(description, seller, date) { var sale = document.createElement("p"); var table = document.getElementById("currentSalesTable"); var row = table.insertRow(-1); var descriptionRow = row.insertCell(0); var userRow = row.insertCell(1); var dateRow = row.insertCell(2); descriptionRow.innerHTML = description; userRow.innerHTML = seller; userRow.onClick = "window.location.href = '../profilePage/index.html?username=' + seller;"; dateRow.innerHTML = date; } This is my code that I started with except for the userRow.onClick part which I added to try and make it work.
Any help is appreciated, Thanks.
-1353675 0 Standard Property Dialog/Browser for ActiveX - ControlI am looking for a property browser/editor for generic activeX controls.
It must work for controls that just expose an IDispatch interface, no proeprty pages of their own.
Best would be something that comes with the OS (like the "All properties" property page VC6 used). It is only for testing, so comfort is not important, modal property sheet or embedded activeX control. The test application is an MFC project.
I thought there was something like that, but the best I can find right now is OleCreatePropertyFrame (which is only the dialog, but not the page i'm after)
Thanks!
-7723292 0In my experience it is not a good practice. assign the null where it needs
-1858654 0I guess you mean ASP.Net GridView? GridView sends javascript postback (__dopostback(...) navigate cursor to edit link and note in status bar) when edit link is clicked, to solve your problem you should send that postback in other js event
-17446449 0I do not know how to change chainde transation mode, but I want you to try "clear" JDBC and CallableStatemet. Such code looks like (I do not have Sybase so I cannot test it):
db = DriverManager.getConnection(db_url, usr, passwd) proc = db.prepareCall("{ ? = call usp_find(?) }"); proc.registerOutParameter(1, Types.INTEGER) proc.setString(2, "Apples"); proc.execute(); r = proc.getInt(1) print('result: %d' % (r))
-24607245 0 Can we use Asp.Net Membership and Role Provider in MVC 5 I'm converting a MVC 3 application to MVC 5. I've been reading on web that MVC 5 comes with Asp.Net Identity for security. My question is that is possible, feasible and good to use old membership and role provider in MVC 5 application. Can anyone give any useful link where I can learn conversion from membership and role provider to Identity.
-37982225 0FindSync<> does not return a single object. The answer to the question below may help you as well. Difference between Find and FindAsync
Just like UIApplication.openURL.
Is there an API to launch iBooks with an ISBN?
-14893669 0Your question now seems to focus on a object oriented cryptographic library for C++. For that question I can recommend Botan. It does seem to focus on modern computing algorithms and includes PBKDF2.
Note that I cannot vouch for the security of this library, I haven't used or evaluated it personally.
-12593367 0Here's a simple JSON encoder in Qt -- should be relatively easy to recast into Java. All you really need to do is to make sure the keys are sorted when writing out -- can read in with another JSON package.
QString QvJson::encodeJson(const QVariant& jsonObject) { QVariant::Type type = jsonObject.type(); switch (type) { case QVariant::Map: return encodeObject(jsonObject); case QVariant::List: return encodeArray(jsonObject); case QVariant::String: return encodeString(jsonObject); case QVariant::Int: case QVariant::Double: return encodeNumeric(jsonObject); case QVariant::Bool: return encodeBool(jsonObject); case QVariant::Invalid: return encodeNull(jsonObject); default: return encodingError("encodeJson", jsonObject, ErrorUnrecognizedObject); } } QString QvJson::encodeObject(const QVariant& jsonObject) { QString result("{ "); QMap<QString, QVariant> map = jsonObject.toMap(); QMapIterator<QString, QVariant> i(map); while (i.hasNext()) { i.next(); result.append(encodeString(i.key())); result.append(" : "); result.append(encodeJson(i.value())); if (i.hasNext()) { result.append(", "); } } result.append(" }"); return result; } QString QvJson::encodeArray(const QVariant& jsonObject) { QString result("[ "); QList<QVariant> list = jsonObject.toList(); for (int i = 0; i < list.count(); i++) { result.append(encodeJson(list.at(i))); if (i+1 < list.count()) { result.append(", "); } } result.append(" ]"); return result; } QString QvJson::encodeString(const QVariant &jsonObject) { return encodeString(jsonObject.toString()); } QString QvJson::encodeString(const QString& value) { QString result = "\""; for (int i = 0; i < value.count(); i++) { ushort chr = value.at(i).unicode(); if (chr < 32) { switch (chr) { case '\b': result.append("\\b"); break; case '\f': result.append("\\f"); break; case '\n': result.append("\\n"); break; case '\r': result.append("\\r"); break; case '\t': result.append("\\t"); break; default: result.append("\\u"); result.append(QString::number(chr, 16).rightJustified(4, '0')); } // End switch } else if (chr > 255) { result.append("\\u"); result.append(QString::number(chr, 16).rightJustified(4, '0')); } else { result.append(value.at(i)); } } result.append('"'); QString displayResult = result; // For debug, since "result" often doesn't show Q_UNUSED(displayResult); return result; } QString QvJson::encodeNumeric(const QVariant& jsonObject) { return jsonObject.toString(); } QString QvJson::encodeBool(const QVariant& jsonObject) { return jsonObject.toString(); } QString QvJson::encodeNull(const QVariant& jsonObject) { return "null"; } QString QvJson::encodingError(const QString& method, const QVariant& jsonObject, Error error) { QString text; switch (error) { case ErrorUnrecognizedObject: text = QObject::tr("Unrecognized object type"); break; default: Q_ASSERT(false); } return QObject::tr("*** Error %1 in QvJson::%2 -- %3").arg(error).arg(method).arg(text); }
-25277657 0 Look carefully at this line of code:
s.send("".join(["NICK",NICK,"\r\n"]).encode()) If you replaced s.send with print, you’d realize it was sending strings like this:
NICKnick<CR><LF> There’s no space! That makes it an invalid command, and makes registration fail. At some point, the server gives up on receiving a valid registration from you, and so sends you an error and closes the connection. So make sure you include a space:
s.send("".join(["NICK ",NICK,"\r\n"]).encode()) At least then you’d be sending a valid registration.
-12451312 0That's because ~/ is supported by the command shell, not the file system APIs.
A simple code:
$source = "JTNDJTNGcGhwJTIwVGhpcyUyMGlzJTIwdGhlJTIwUEhQJTIwY29kZSUyMCUzRiUzRQ=="; $code = base64_decode($source); eval($code); or even shorter:
eval(base64_decode("JTNDJTNGcGhwJTIwVGhpcyUyMGlzJTIwdGhlJTIwUEhQJTIwY29kZSUyMCUzRiUzRQ==")); Do you want to encrypt your code? If so, this is not the right way. Use a accelerator like this one or this one. They will crypt your codes and make them even faster!
-36384376 0 Passing contents of file to extglob command terminalI have a list of files that I don't want to remove from a location, I have found that by using extglob I am able to keep a pre-defined list of files using:
rm -r !(one.txt|Folder) This will remove everything except one.txt and the folder Folder, however the list of files that I want to keep isn't always the same.
Is there a way to pass a list of files/folders from a file e.g. whitelist.txt which won't be removed?
I have managed to reformat whitelist.txt to have the contents:
one.txt|two.txt|Folder However I am unsure of how to pass that into the command
Just a note I am running OSX 10.11.
Thanks,
-21357346 0 I´m using a modal to see my contact info in which there are 4 btn´s which doesn´t always work (Page=UNDEFINED). Can someone help me understand why?<!--Kontakt modal--> <li><a data-toggle="modal" href="#myModal">Kontakta mig</a></li> <div id="myModal" class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <!--Titeln i modal--> <h2 class="modal-title" id="myModalLabel">Kontakta mig</h2> </div> <div class="modal-body"> <a class="btn btn-default table-responsive glyphicon glyphicon-map-marker" href="https://maps.google.com/maps?q=Moldegatan+1C%2c+Bor%C3%A5s%2c+Sweden&hl=en&ie=UTF8&sll=38.882147%2c-76.99017&sspn=0.014866%2c0.027874&oq=Mo&hnear=Moldegatan+1C%2c+504+32+Bor%C3%A5s%2c+Sweden&t=m&z=16&source=gplus-ogsb" role="button">Moldegatan 1C 50432 BORÅS</a> <hr /> <a class="btn btn-default table-responsive glyphicon glyphicon-earphone" href="tel:+0735451624" role="button">Telefonnummer: 0735451624</a> <hr /> <a class="btn btn-default table-responsive glyphicon glyphicon-envelope" href="mailto:mr_clavijo@hotmail.com" role="button">E-mail: mr_clavijo@hotmail.com</a> <hr /> <div class="intent"> <img src="Content/Bilder/facebook.png" alt="Facebook" /> <a class="btn btn-default" href="http://facebook.com/carlos.clavijo.77" data-scheme="fb://profile/555447256">Facebook</a> </div> </div> <div class="modal-footer"> <div class="btn-group"> <button class="btn btn-danger" data-dismiss="modal">Stäng</button> </div> </div> </div> <!-- /modal-content --> </div> <!-- /modal-dialog --> </div> <!-- /myModal --> // JavaScript. I´m using this so that when using a smartphone or tablet it will open up the aplication istead of the explorer. I´m kind of new to this so please bare with me.
When using this function and press one of the buttons in the kontakt modal it works sometimes, but sometimes it shows up as page undefined. What am I missing?
(function() { // tries to execute the uri:scheme function goToUri(uri, href) { var start, end, elapsed; // start a timer start = new Date().getTime(); // attempt to redirect to the uri:scheme // it'll stutter for a split second, causing the timer to be off document.location = uri; // end timer end = new Date().getTime(); elapsed = (end - start); // if there's no elapsed time, then the scheme didn't fire, and we head to the url. if (elapsed < 1) { document.location = href; } } $('a.btn-default').on('click', function(event) { goToUri($(this).data('scheme'), $(this).attr('href')); event.preventDefault(); }); })();
-25680571 0 Create a getter method in counter class. Then call that method in register class when you need number of students.
-19128066 0Thanks to Steve Howard, The problem can be solved by changing SHELL to /bin/bash
-25710837 0 How to write an HTML button which can run both onclick and onserverclick?I have a HTML button which is connected to some external JS and on its onclick events my JavaScript functions would run. The functions consist of some alerts. Now I would like to write my main code which is in C# language but as soon as I write onserverclick event in my button, my onclick events don't work anymore.
My button code is:
<input runat="server" type="button" id="btn_submit" class="btn_submit" value ="ثبت" onclick="mail_valid()" onserverclick="BtnRegister_Click"/> How can I make both the "onclick" and "onserverclick" event handlers work?
Edit: I want to avoid from postback in the button thats why i used html button .
-24252801 0To iterate through ENABLE once you have it you should use a simple while loop:
while(<ENABLE>){ chomp; //each line read from ENABLE will be stored in $_ per loop } This way you do not need a for loop to iterate. So in essence you would run the "server hostname" command in this while loop:
... while(<ENABLE>) { chomp; $ssh->exec("server $_"); } ... Check here for details.
-11975159 0 Command Line Tool to Disable PDF PrintingDoes anyone know of a "FREE" command line tool that can lock a pdf from a user being able to print it. I need to be able to put this in a batch to loop through a folder and disable printing from adobe standard and reader. Is this possible to do it from command line with any tool?
-38598518 0 Word extraction multiline text fileHere I have created a code to: Extract indivisual words from a text file, Append only the words with no duplicates into a blank list and Sort them by alphabetical order.
fname = raw_input("Enter file name: ") fhandle = open(fname) wordlist = list() counter = 0 for line in fhandle: line = line.split() length = len(line) if line not in wordlist: wordlist.append(line[counter]) counter += 1 if counter == length: break print wordlist.sort() -33804930 0Checking this in Pycharm still gives result 'None' although looking at live execution shows the words sorted in alphabetically ordered list but with duplicated words intact (see figures). I would love to decipher difference between append from file 1 and from a variable 2.
I am very late for this question, but anyway... My guess is that you want to use the Application Factory pattern and use the Flask-Admin. There is a nice discussion about the underlying problems. I used a very ugly solution, instantiating the Flask-Admin in the init.py file:
from flask_admin.contrib.sqla import ModelView class UserModelView(ModelView): create_modal = True edit_modal = True can_export = True def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) db.init_app(app) # import models here because otherwise it will throw errors from models import User, Sector, Article admin.init_app(app) admin.add_view(UserModelView(User, db.session)) # attach blueprints from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/auth') return app
-19505287 0 var jamie = someVarThatCanBeUndefined || 'or maybe not'; You can use the above to do coalescing
Here is an answer with more details Is there a "null coalescing" operator in JavaScript?
If you wanted short hand notation for if
Try this instead:
boolCondition ? "OneStringForTrue" : "AnotherForFalse" This is often called the
Conditional (Ternary) Operator (?:) (JavaScript)
-29776864 0 The RegEx is working as written:
/^[^t]{2,2}st$/ You also don't need to do {2,2} as that is a range, you can do {2} for exactly 2 matches, or {1,2} for 1 upto 2 matches.
This example should serve as a good illustration of what is occurring within that RegEx.
If you are looking for a solution to: Match any word that does not start with tt (case sensitive) you can use the following:
/^(?!tt)\w+$/ Hope this helps.
-10987821 0 Two columns equal height only css (no display: table, table-row, table-cell)In CSS, I can do something like this: 
But I've no idea how to change that to something like: 
The height is not fixed
Please help me do it! Thank you all in advance!
-955823 0Using a state pattern is an approach you can take for this, but honestly what your describing is part of what the MVC framework was designed to accomplish.
Edit:
MVP/MVC
Since the MVC Framework isn't an option then I would take a look at Model View Presenter pattern (MVP) with either the passive view approach or superviser approach as described here: http://www.martinfowler.com/eaaDev/SupervisingPresenter.html
We found that the passive view approach worked with a little adaptation for our legacy code to work out good for us.
Edit: Patterns:
In that case then which pattern you choose really depends upon what the business needs are.
State pattern:
State pattern is typically used for when you need to change the behavior of an object based upon its current state or the state of a relation to the object. A common usage of this pattern is with games when the behavior of the object depends upon which mouse cursor button is pressed.
http://en.wikipedia.org/wiki/State_pattern
Strategy pattern:
This pattern is good for when you need different implementation based upon a configuration. For example say you are defining an email system and you need to have a different implimentation based upon which email provider is being used to send the email.
http://en.wikipedia.org/wiki/Strategy_pattern
So State pattern could definetly be the right direction it just comes down to what the objective is and what behavior's your trying to meet.
What you'll often find with patterns is that they work well with eachother and you'll use multiple patterns in conjuction with eachother.
-10889536 0In cBase you should use @Override with the onCreate(Bundle savedInstanceState) method and it MUST also call through to super.onCreate(Bundle savedInstanceState)
If I have two types of models that each reference each other, whichever one I try to define first says it does not recognize the referenced other type (because it is defined further down in the file). For example:
class Author(db.Model): most_recent_book = db.ReferenceProperty(Book) class Book(db.Model): author = db.ReferenceProperty(Author) This will claim that the referenced "Book" model is not recognized. If I flip the order, I run into the same issue (except it will say that "Author" is not recognized). How do I get around this?
-21716317 0its simple in Xcode5
select project file from project navigator on the left side
then look at the right side utilities navigator, select file navigator
now 2nd group should be "project document"
HTH
-23957246 0 Apache derby plugin for eclipseAfter installing the JavaDB plugin for eclipse version 4.3.2, I unzipped the core and ui folders and put their contents under eclipse/plugin directroy.
unfortunately, clicking on a project, and adding apache derby nature lead for nothing! No packages is added to the project, and no control panel is available for the apache derby! I can repeat the process 10s times and nothing happened.
I'm new with the environment, help me out!
Ps; you should be able to see packages added to eclipse java ee kepler.

I will be very direct with my question. I have been developing web applications for a while, but one thing I haven't been able to overcome is this; Where is the most appropriate location to have an admin page. For instance, How are company like Facebook, Google, Yahoo, BOA, etc doing it? am sick and tired of
http://weblink/admin, or http://weblink/administration
Thanks in advance
-36192700 0I got the solution. The reason why y didn't increase was because the value of x didn't get reset from 1000. It just automatically skipped that chunk of code because the value of x was already 1000. This is my improved code which also sorts the array in order.
def Problem4(): y = 100 a = [] x1 = [] y1 = [] while y < 1000: y = y + 1 x = 100 while x < 1000: z = x*y if str(z) == str(z)[::-1]: a.append(z) x = x + 1 a.sort() print(a) Problem4()
-21515056 0 I suggest that you give your bottom colorful panels a preferredDimension based on the screen resolution, the font size, etc. That way, it may stay the way you want it to stay.
Also, try setting the Insets for these components, see if that helps.
Inheritance is not the answer to everything, and here is is not the answer at all. Inheritance should model "is-a", and by no stretch of the imagination is an Account a UseAccount.
Instead, just change the signature of display() to take a JTextArea as an argument; then in the display() code you'll have a JTextArea to work with. When you call display(), pass the JTextArea in.
In other words:
void display(JTextArea ta) { ta.append(name); ... and then
// "frame" is the UseAccount object that contains the JTextArea variable `output` myAccount.display(frame.output); Most of the time, the right question is not "How can X get access to part of Y", but rather "How can Y give access to part of itself to X?"
One final note: small effort put into naming variables well really pays off.
-33514581 0I also had this same issue before, So you need to create a pipeline in your settings.py to update facebook user data. This code will help you to get facebook user data; http://django-social-auth.readthedocs.org/en/latest/pipeline.html
def update_user_social_data(request, *args, **kwargs): user = kwargs['user'] if not kwargs['is_new']: return user = kwargs['user'] if kwargs['backend'].__class__.__name__ == 'FacebookBackend': fbuid = kwargs['response']['id'] access_token = kwargs['response']['access_token'] url = 'https://graph.facebook.com/{0}/' \ '?fields=email,gender,name' \ '&access_token={1}'.format(fbuid, access_token,) photo_url = "http://graph.facebook.com/%s/picture?type=large" \ % kwargs['response']['id'] request = urllib2.Request(url) response = urllib2.urlopen(request).read() email = json.loads(response).get('email') name = json.loads(response).get('name') gender = json.loads(response).get('gender')
-18080612 0 Swing application won't display in unity when second monitor is on the left I am developing an application in Swing. When I have two monitors connected, the application will not display. The icon appears in the unity side bar but the window is nowhere to be seen.
I went back to basics and ran HelloWorldSwing.java from the Oracle tuorials
and the same problem exists. Then I find that if I put Monitor 1 on the left, HelloWorld appears in the top left hand corner.
How can I get HelloWorldSwing (and Swing apps in general) to display in Unity when the main monitor is on the right?
My display configuration: Monitor 1 (Laptop Screen) 1280x800 Monitor 2 ("unknown") 1440x900
Monitor 2 is on the left. I have the following in my ~/.xprofile:
xrandr --newmode "1680x1050" 146.25 1680 1784 1960 2240 1050 1053 1059 1089 -hsync +vsync xrandr --addmode VGA1 1680x1050 xrandr --newmode "1440x900" 106.50 1440 1528 1672 1904 900 903 909 934 -hsync +vsync xrandr --addmode VGA1 1440x900
-38407861 0 How do I get 'id' from database to update a particular row? I am trying to update a row which is already in database, and i am using above code for that but it gives me error as 'undefined id', so how can i do this.....please help me!!!
if(isset($_POST['sub'])) { $getid="select id from login"; $res=mysql_query($getid); $ids=$_GET[$row['id']]; $about=$_POST['desc']; $pri=$_POST['price']; $ride=$_POST['fly']; $city=$_POST['ct']; $flt=""; foreach($ride as $entry) { $flt .= $entry.","; } $ct=""; foreach($city as $entry) { $ct .= $entry.","; } $query ="UPDATE login SET rides='$flt',price=$pri,about='$about',city='$ct' WHERE id='$ids'"; $result = mysql_query($query); echo $result; if(!$result) { echo '<script language="javascript">'; echo 'alert("something went Wrong...:("); location.href="edit.php"'; echo '</script>'; } else { echo '<script language="javascript">'; echo 'alert("successfully updated!!!"); location.href="edit.php"'; echo '</script>'; } }
-35223269 0 Multiple Fact Tables-Kylin I am aware that Apache Kylin only allows one Fact Table per OLAP cube.
Is there a way to analyse a database with multiple Fact Tables using OLAP?
Alternatively, Can we query from multiple cubes simultaneously in a single job on Apache Kylin?
Regards Anish Dhiman
-32302123 0The script was all correct, my problem was that my parent "FPSController" object didn't have a Rigidbody applied to it and should be the only object (as opposed to the "FirstPersonCharacter" object I had nested inside of it) that the scripts are applied to. That seemed to fix the problem.
The correct code is:
/* coincollect.cs */ using UnityEngine; using System.Collections; using UnityEngine.UI; public class coincollect : MonoBehaviour { private int _score; [SerializeField] private Text _text; void OnTriggerEnter ( Collider collision ){ if(collision.gameObject.tag == "coin"){ Destroy(collision.gameObject); _score++; _text.text = "Score: " + _score; } } } and:
/* warp.js */ var warptarget001 : GameObject; var warptarget002 : GameObject; function OnTriggerEnter (col : Collider) { if (col.gameObject.tag == "warp001") { this.transform.position = warptarget002.transform.position; } if (col.gameObject.tag == "warp002") { this.transform.position = warptarget001.transform.position; } }
-15996410 0 I think the problem is how you are putting the origname and newname in the ajax request. Try this:
var origname = $('#NameDiv').find('input[name="myName"]').first().val(); var newname = $('#NameDiv').find('input[name="updatedName"]').first().val(); $.ajax({ url: 'Home/ChangeName', type: "POST", data: $("#form1").serialize() + "&origname =" + origname + "&newname =" + newname, success: function (result) { success(result); } });
-4169038 0 As mentioned by bosmacs, to accomplish this you need to let MonoTouch know that you need to link against the EventKit framework "weakly". Weak bindings ensure that the framework is only loaded on demand the first time a class from the framework is required.
To do this you should take the following steps:
In addition to this you will need to guard your usage of the types from running on older versions of iOS where they may not exist. There are several methods to accomplish this, but one of which is parsing UIDevice.CurrentDevice.SystemVersion.
-12178205 0 Grouping objecs in PostgreSQL databaseI inherited a project with a large Postgres database (over 150 tables, over 200 custom types, almost 1000 functions, triggers, etc.) Unfortunately, everything is dumped into one schema (public). It works just fine from the point of view of the application, however it's a major nightmare to maintain.
The obvious thing would be to split these objects into separate schemas by function (e.g. all supplier-related stuff goes into supplier schema, all admin related stuff into admin schema, etc.). Once this is done, of course, some changes (ok, a lot of changes) to the code would be required to refer to the new schemas. Considering that the web application contains about 2000 php files, it may be quite a task. Again, as every php in the system already starts with require_once('controller/config.php'); I could add a call there to set search path to include all the new schemas: SET search_path = 'public, supplier, admin, ...', yet somehow subconsciously I don't like this solution.
Is there any other way to deal with issue? I don't want to spend more effort than absolutely necessary on reorganising the database. I also can barely incur any downtime on the main web site, as it's used by clients across the world (Australia, Europe, North America).
What would your recommend I do?
-1979965 0If you set cookieless="true" (or UseDeviceProfile and browser has cookies disabled) in your web.config file, authentication information is appended to the URL and this url will be valid across other browsers. If you use cookies to identify users, then only the current browser will have the user authenticated.
I have 2 tables like this. For a given attribute (in table doc_attribute) and a given 'word' in file (in document), I want to find the count of distinct doc_id that do not contain that particular attribute but contain that 'word' in file.
For example if the attribute given is camera and 'word' is mobile, then the result should be 2. (ie., 2nd, 3rd and 5th doc_id does not contain camera and among them only 2nd and 3rd contain the 'word' mobile in file)
table doc_attribute +--------+-----------+--------+ | doc_id | attribute | value | +--------+-----------+--------+ | 1 | product | mobile | | 1 | model | lumia | | 1 | camera | 5mp | | 2 | product | mobile | | 2 | model | lumia | | 2 | ram | 1gb | | 3 | product | mobile | | 3 | year | 2014 | | 3 | made-in | china | | 4 | brand | apple | | 4 | model | iphone | | 4 | camera | 5mp | | 5 | product | camera | | 5 | brand | canon | | 5 | price | 20000 | table document +--------+-----------------------------+ | doc_id | file | +--------+-----------------------------+ | 1 | lumia 5mp mobile 1gb 2014 | | 2 | lumia 8mp mobile 1gb 2015 | | 3 | galaxy mobile fullhd 2gb | | 4 | iphone apple 5mp 2013 new | | 5 | canon 20000 new dslr 12mp | Current query:
select count(doc_id) from document where doc_id not in (select doc_id from doc_attribute where attribute = 'camera') and file REGEXP '[[:<:]]mobile[[:>:]]';
-18625274 0 I was in the same boat you were. What I found most helpful was to slightly change the bundle identifier.
Example: Your bundle identifier is com.company.app. If you need to test enabling push notifications change the identifier to com.company.app1. It will install as a new app and have new push notification permission settings.
Just make sure to change it back when you're done testing.
-117534 0LINQ requires .NET v3.5
An excellent tool for getting to know and practice LINQ is Joseph Albahari's LINQPad
-6857457 0I think this is a job for a modular approach: https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc/wiki/Home
Q. What is Modular HMVC, why should I use it?
A. Modular HMVC = Multiple MVC triads
This is most useful when you need to load a view and its data within a view. Think about adding a shopping cart to a page. The shopping cart needs its own controller which may call a model to get cart data. Then the controller needs to load the data into a view. So instead of the main controller handling the page and the shopping cart, the shopping cart MVC can be loaded directly in the page. The main controller doesn’t need to know about it, and is totally isolated from it.
In CI we can’t call more than 1 controller per request. Therefore, to achieve HMVC, we have to simulate controllers. It can be done with libraries, or with this “Modular Extensions HMVC” contribution.
The differences between using a library and a “Modular HMVC” HMVC class is: 1) No need to get and use the CI instance within an HMVC class 2) HMVC classes are stored in a modules directory as opposed to the libraries directory.
Bonfire also uses HMVC.
-27804975 0I was looking for quite a bit for a complete working example of a custom wx Python control which subclasses wx.Panel and does custom drawing on itself, and I couldn't find any. Thanks to this (and other) questions, I finally managed to come to a minimal working example - which I'm going to post here, because it does show "drawing to Panel inside of a Frame"; except, unlike the OP, where the Frame does the drawing on the Panel - here the Panel draws on itself (while sitting in the Frame).
The code produces something like this:

... and basically the red rectangle will be redrawn when you resize the window.
Note the code comments, especially about the need to Refresh() in OnSize to avoid corrupt rendering / flicker.
The MWE code:
import wx # tested on wxPython 2.8.11.0, Python 2.7.1+, Ubuntu 11.04 # http://stackoverflow.com/questions/2053268/side-effects-of-handling-evt-paint-event-in-wxpython # http://stackoverflow.com/questions/25756896/drawing-to-panel-inside-of-frame-in-wxpython # http://www.infinity77.net/pycon/tutorial/pyar/wxpython.html # also, see: wx-2.8-gtk2-unicode/wx/lib/agw/buttonpanel.py class MyPanel(wx.Panel): #(wx.PyPanel): #PyPanel also works def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, name="MyPanel"): super(MyPanel, self).__init__(parent, id, pos, size, style, name) self.Bind(wx.EVT_SIZE, self.OnSize) self.Bind(wx.EVT_PAINT, self.OnPaint) def OnSize(self, event): print("OnSize" +str(event)) #self.SetClientRect(event.GetRect()) # no need self.Refresh() # MUST have this, else the rectangle gets rendered corruptly when resizing the window! event.Skip() # seems to reduce the ammount of OnSize and OnPaint events generated when resizing the window def OnPaint(self, event): #~ dc = wx.BufferedPaintDC(self) # works, somewhat dc = wx.PaintDC(self) # works print(dc) rect = self.GetClientRect() # "Set a red brush to draw a rectangle" dc.SetBrush(wx.RED_BRUSH) dc.DrawRectangle(10, 10, rect[2]-20, 50) #self.Refresh() # recurses here! class MyFrame(wx.Frame): def __init__(self, parent): wx.Frame.__init__(self, parent, -1, "Custom Panel Demo") self.SetSize((300, 200)) self.panel = MyPanel(self) #wx.Panel(self) self.panel.SetBackgroundColour(wx.Colour(10,10,10)) self.panel.SetForegroundColour(wx.Colour(50,50,50)) sizer_1 = wx.BoxSizer(wx.HORIZONTAL) sizer_1.Add(self.panel, 1, wx.EXPAND | wx.ALL, 0) self.SetSizer(sizer_1) self.Layout() app = wx.App(0) frame = MyFrame(None) app.SetTopWindow(frame) frame.Show() app.MainLoop()
-14880691 0 RewriteEngine On RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} -d [OR] RewriteCond %{REQUEST_URI} !^blog.*$ RewriteRule ^.*$ - [NC,L] RewriteRule ^.*$ index.php [NC,L]
-13735521 0 How can I find the index of an array element? I have this class and it displays the value of arrays after preferred input:
class MyArrayList { private int [] myArray; private int size; public MyArrayList (int value, int seed, int inc){ myArray = new int [value]; size = value; for (int i = 0; i < size; i++) { myArray [i] = seed; seed += inc; } } } public class JavaApp1 { public static void main(String[] args) { MyArrayList a = new MyArrayList(5, 2, 1); a.printList(); } } this program displays an output of: 2 3 4 5 6 now I want to find the index of 4 so that would be 2 but how can I put it into program?
-33518786 0try changing this:
$sql = mysql_query("SELECT id FROM admin WHERE username='$manager' AND password=$password' LIMIT 1"); to this:
$sql = "SELECT id FROM admin WHERE username='$manager' AND password='$password' LIMIT 1"; $result = mysqli_query($conn, $sql); or this:
$sql = "SELECT id FROM admin WHERE username='$manager' AND password='$password' LIMIT 1"; $result = $conn->query($sql); ($conn is the connection variable change it if it different.) hope this helps out.
also change mysql_fetch_array($sql) to mysqli_fetch_array($sql)
With the default options, it will not delete tables A, B and C. It will however overwrite (delete current data that is not in the backup) tables D, E and F.
To see the list of available options see here.
-4439571 0Hey, I know this is a bit old, but I've found the EditorialReview part of the response contains the product description. I guess the cravet that Tom talks about still applies, but at least its a way to get to the description without reverting to screen scraping (which is never a good thing!) :)
See this page of the Amazon product API: http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/
EditorialReview Response Group
For each item in the response, the EditorialReview response group returns Amazon's review of the item, which, on the Detail page, is labeled the Product Description.
No nasty screen scraping required! :)
Andy.
-26067489 0 send html form with php can't solveI have big problem with sending easy html form with php. My problem is when all fields are empty it still send message. I don't why this code still send empty form??
<form id="form1" name="form1" method="post" action="forma.php"> <p> <label for="ime">Ime:</label> <input type="text" name="ime" id="ime" /> </p> <p> <label for="prezime">Prezime:</label> <input type="text" name="prezime" id="prezime" /> </p> <p> <label for="email">e-mail:</label> <input type="text" name="email" id="email" /> </p> <p> <label for="poruka">Poruka:</label> <textarea name="poruka" cols="40" rows="10" id="poruka"></textarea> </p> <p> <input type="submit" name="submit" value="submit" /> </p> </form> My php code:
<?php if (isset($_POST['submit'])) { $ime= $_POST['ime']; $prezime= $_POST['prezime']; $email= $_POST['email']; $poruka= $_POST['poruka']; $email_from = 'neki@email.com'; $email_subject = "forma sa sajta"; $email_body = "Ime: $ime. \n". "Prezime: $prezime \n". "email: $email \n". "poruka: $poruka" ; $to = "myemail@gmail.com"; mail ($to, $email_subject, $email_body); echo "Message is sent"; } else { echo "Message is not sent"; } ?> So again, when i fill fields message is sent. It is ok, i received email. But when i just click submit (without filling fields) it still send message to my email.
What is wrong with this code? I try everything i know, but without success.
Thank you.
-8170150 0 Http redirect in Tomcat or web service proxyI got a web service running on 127.0.0.1:8080/test/mywebservice
This web service (port:8080) is created dynamically by another web service (port:80) that is hosted in Tomcat. All web services that are created by Tomcat directly can use port 80, however, not those that are created dynamically.
I have to do this since I need to share objects between these two web services.
The problem is that the client can only make requests to port 80, and I can't host my web service on port 80.
Does anyone know how to redirect requests to
127.0.0.1:80/test/mywebservice
to
127.0.0.1:8080/test/mywebservice
Is the code property of authResponse.signedRequest (in the Facebook JavaScript API) useful? I'm generating one like this:
FB.login({ scope: "email" }, function(r) { console.log([ function(d){ return d.split('.')[1]; }, function(d){ return atob(d.replace('-', '+').replace('_', '/')); }, JSON.parse, function(d){ return d.code; } ].reduce( function(acc, f) { return f(acc); }, r.authResponse.signedRequest )); }); The docs say this:
code: an OAuth Code which can be exchanged for a valid user access token via a subsequent server-side request
…but that link redirects to Facebook Login home page. I found the /oauth/access_token endpoint documented here, but it requires a redirect_uri parameter, and there isn't one in this case.
Is there any 2 known valued of input for sha1 which gives the same hash?
since sh1 takes the any length input and output 128/256/512 , so it is possible to find any 2 string of any known length which can produce same hash .
-23499514 0 looping over the lines of a file spliiting each line in columns and creating an array of each columnSorry if my question is too obvious, I´m new in perl.
My code is the following:
open (FILE1, "$ARG[0]") or die @lines1; $i=1; while (<FILE>) { chomp; push (@lines1, $_); my @{columns$1}= split (/\s+/, $lines1[$i]); $i++; } It gives an error saying
Can´t declare array dereference at the line my @{columns$1}= split (/\s+/, $lines1[$i]); I wanted to create columns1, columns2, columns3... and each one of them would have the columns of the corresponding line (columns1 of the line 1, columns2 of line 2 and so on...)
Because before I tried to do it this way (below) and every time it was splitting the lines but it was overwriting the @columns1 array so only the last line was saved, at the end I had the values of the 10th line (because it starting counting at 0)
for my $i (0..9) { @columns1 = split (/\s+/, $lines1[$i]); }
-876656 0 Difference between Dictionary and Hashtable Possible Duplicate:
Why Dictionary is preferred over hashtable in C#?
What is the difference between Dictionary and Hashtable. How to decide which one to use?
-18842936 1 Qt Pyside displaying results in widgetsI am going through a lot of data in a loop, and updating status into a textedit widget on my mainwindow. The thing is, the textedit widget only gets update, after all my data in the loop is processed. I want to display it in the textedit widget as its processing.
for i in data: ... textedit.settext(i) <<---- this part is not updated "fast" enough to textedit widget .. what can i do about this? Do i have to look in the direction of some form of multithreading? thanks
Update: Actually the whole scenario is i am doing some file operations, going through directories, connecting to databases, selecting stuff and then displaying to GUI. While my code runs in the background, i would also like to display results found to the QT textedit widget in "realtime". Right now, my widget shows the result after my file operations are done. And the GUI "hangs" while the file operations are being done. thanks
-27510000 0Within a Tasklet, the responsibility for exception handling is on the implementation of the Tasklet. The skip logic available in chunk oriented processing is due to the exception handling provided by the ChunkOrientedTasklet. If you want to skip exceptions in your own Tasklet implementation, you need to write the code to do so in within your own implementation.
You mention that somebody else encountered the problem and didn't receive a response, however the linked forum thread does contain a response and an answer to this issue. In that particular case a Javascript error had occurred on the page which prevented the dropdown from initializing correctly and I believe this is also the case for yourself.
Although not completely working because there isn't a valid datasource, I took your example code and dumped it into a jsFiddle and (after fixing some JS errors) you can see that the dropdown appears absolutely fine.
In particular, there were errors regarding grid and sitePath not being defined that prevented the dropdown from initializing.
var grid; var sitePath = ''; $().ready(function () { grid = $('#listDiv').kendoGrid({ dataSource: { type: 'json', serverPaging: true, pageSize: 10, transport: { read: { url: '', data: { ignore: Math.random() } } }, schema: { model: { id: 'Id', fields: { Id: { type: 'number' }, Name: { type: 'string' }, Ex: { type: 'string' }, Date: { type: 'string' }, Check1: { type: 'string' }, Check2: { type: 'string' }, Check3: { type: 'string' }, Check4: { type: 'string' }, Check5: { type: 'string' }, Edit: { type: 'string' } } }, data: "Data", total: "Count" } }, scrollable: false, toolbar: kendo.template($("#template").html()), columns: [ { field: 'Name' }, { field: 'Ex' }, { field: 'Date' }, { template: '#=Template1#' + sitePath + '#=Patient1#', field: 'Patient1', title: 'Patient 1', width: 50 }, { template: '#=Template2#' + sitePath + '#=Patient2#', field: 'Patient2', title: 'Patient 2', width: 50 }, { template: '#=Template3#' + sitePath + '#=Patient3#', field: 'Patient3', title: 'Patient 3', width: 50 }, { template: '#=Template4#' + sitePath + '#=Patient4#', field: 'Patient4', title: 'Patient 4', width: 50 }, { template: '#=Template5#' + sitePath + '#=Patient5#', field: 'Patient5', title: 'Patient 5', width: 50 } ], pageable: true }); var dropDown = grid.find("#external").kendoDropDownList({ dataTextField: "ExName", dataValueField: "ExId", autoBind: false, optionLabel: "All", dataSource: { type: "json", severFiltering: true, transport: { url: '@Url.Action("_Ex", "Entry")', data: { ignore: Math.random() } } }, change: function () { var value = this.value(); if (value) { grid.data("kendoGrid").dataSource.filter({ field: "ExId", operator: "eq", value: parseString(value) }); } else { grid.data("kendoGrid").dataSource.filter({}); } } }); theGrid = $('#listDiv').data('kendoGrid'); });
-11643125 0 You must treat all data coming from the client as suspect. This includes the URL. You should check that this client is indeed authenticated and that he is authorized to perform whatever action is indicated (by the URL, post data, etc). This is true even if you are only displaying data, not changing it.
It is not important if the record id is easily seen or modifiable in the URL. What matters is what can be done with it. Unless the id itself imparts some information (which would be surprising), there is no need hide it or obfuscate it. Just make sure you only respond to authenticated and authorized requests.
-6627922 0 500 Internal Server Error when trying to access .ashx fileI have recently ran into a problem that would not allow me to use DELETE and PUT requests into my .ashx file, so I added the proper verbs in order to allow that access. Now I am getting a 500 Internal Server Error. Here is my web.config for the handlers:
<handlers> <remove name="OPTIONSVerbHandler" /> <remove name="WebServiceHandlerFactory-Integrated" /> <remove name="svc-Integrated" /> <remove name="WebDAV" /> <add name="svc-Integrated" path="*.svc" verb="*" type="System.ServiceModel.Activation.HttpHandler, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="integratedMode" /> <add name="OwssvrHandler" scriptProcessor="C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\isapi\owssvr.dll" path="/_vti_bin/owssvr.dll" verb="*" modules="IsapiModule" preCondition="integratedMode" /> <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> <add name="JSONHandlerFactory" path="*.json" verb="*" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" resourceType="Unspecified" preCondition="integratedMode" /> <add name="ReportViewerWebPart" verb="*" path="Reserved.ReportViewerWebPart.axd" type="Microsoft.ReportingServices.SharePoint.UI.WebParts.WebPartHttpHandler, Microsoft.ReportingServices.SharePoint.UI.WebParts, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" /> <add name="ReportViewerWebControl" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> <add name="ashxhandler" path="*.ashx" verb="*" type="System.Web.UI.SimpleHandlerFactory" validate="True" /> </handlers> Here is the httpHandlers:
<httpHandlers> <add path="*.ashx" verb="*" type="System.Web.UI.SimpleHandlerFactory" validate="True" /> </httpHandlers> Any ideas? I already went to IIS 7, went to Request Filtering, added .ashx file extension, set it to true and then in the HTTP Verbs section I added DELETE, POST, GET, HEADER, PUT.
EDIT:
Here is my .ashx file:
<%@ WebHandler Language="C#" Class="jQueryUploadTest.Upload" %> using System; using System.Collections.Generic; using System.IO; using System.Security.AccessControl; using System.Web; using System.Web.Script.Serialization; namespace jQueryUploadTest { public class Upload : IHttpHandler { public class FilesStatus {/* public string thumbnail_url { get; set; } public string name { get; set; } public string url { get; set; } public int size { get; set; } public string type { get; set; } public string delete_url { get; set; } public string delete_type { get; set; } public string error { get; set; } public string progress { get; set; } */ private string m_thumbnail_url; private string m_name; private string m_url; private int m_size; private string m_type; private string m_delete_url; private string m_delete_type; private string m_error; private string m_progress; public string thumbnail_url { get { return m_thumbnail_url; } set { m_thumbnail_url = value; } } public string name { get { return m_name; } set { m_name = value; } } public string url { get { return m_url; } set { m_url = value; } } public int size { get { return m_size; } set { m_size = value; } } public string type { get { return m_type; } set { m_type = value; } } public string delete_url { get { return m_delete_url; } set { m_delete_url = value; } } public string delete_type { get { return m_delete_type; } set { m_delete_type = value; } } public string error { get { return m_error; } set { m_error = value; } } public string progress { get { return m_progress; } set { m_progress = value; } } } private readonly JavaScriptSerializer js = new JavaScriptSerializer(); private string ingestPath; public bool IsReusable { get { return false; } } public void ProcessRequest (HttpContext context) { //var r = context.Response; ingestPath = @"C:\temp\ingest\"; context.Response.AddHeader("Pragma", "no-cache"); context.Response.AddHeader("Cache-Control", "private, no-cache"); HandleMethod(context); } private void HandleMethod (HttpContext context) { switch (context.Request.HttpMethod) { case "HEAD": case "GET": ServeFile(context); break; case "POST": UploadFile(context); break; case "DELETE": DeleteFile(context); break; default: context.Response.ClearHeaders(); context.Response.StatusCode = 405; break; } } private void DeleteFile (HttpContext context) { string filePath = ingestPath + context.Request["f"]; if (File.Exists(filePath)) { File.Delete(filePath); } } private void UploadFile (HttpContext context) { List<FilesStatus> statuses = new List<FilesStatus>(); System.Collections.Specialized.NameValueCollection headers = context.Request.Headers; if (string.IsNullOrEmpty(headers["X-File-Name"])) { UploadWholeFile(context, statuses); } else { UploadPartialFile(headers["X-File-Name"], context, statuses); } WriteJsonIframeSafe(context, statuses); } private void UploadPartialFile (string fileName, HttpContext context, List<FilesStatus> statuses) { if (context.Request.Files.Count != 1) throw new HttpRequestValidationException("Attempt to upload chunked file containing more than one fragment per request"); Stream inputStream = context.Request.Files[0].InputStream; string fullName = ingestPath + Path.GetFileName(fileName); using (FileStream fs = new FileStream(fullName, FileMode.Append, FileAccess.Write)) { byte[] buffer = new byte[1024]; int l = inputStream.Read(buffer, 0, 1024); while (l > 0) { fs.Write(buffer,0,l); l = inputStream.Read(buffer, 0, 1024); } fs.Flush(); fs.Close(); } FilesStatus MyFileStatus = new FilesStatus(); MyFileStatus.thumbnail_url = "Thumbnail.ashx?f=" + fileName; MyFileStatus.url = "Upload.ashx?f=" + fileName; MyFileStatus.name = fileName; MyFileStatus.size = (int)(new FileInfo(fullName)).Length; MyFileStatus.type = "image/png"; MyFileStatus.delete_url = "Upload.ashx?f=" + fileName; MyFileStatus.delete_type = "DELETE"; MyFileStatus.progress = "1.0"; /* { thumbnail_url = "Thumbnail.ashx?f=" + fileName, url = "Upload.ashx?f=" + fileName, name = fileName, size = (int)(new FileInfo(fullName)).Length, type = "image/png", delete_url = "Upload.ashx?f=" + fileName, delete_type = "DELETE", progress = "1.0" }; */ statuses.Add(MyFileStatus); } private void UploadWholeFile(HttpContext context, List<FilesStatus> statuses) { for (int i = 0; i < context.Request.Files.Count; i++) { HttpPostedFile file = context.Request.Files[i]; file.SaveAs(ingestPath + Path.GetFileName(file.FileName)); string fileName = Path.GetFileName(file.FileName); FilesStatus MyFileStatus = new FilesStatus(); MyFileStatus.thumbnail_url = "Thumbnail.ashx?f=" + fileName; MyFileStatus.url = "Upload.ashx?f=" + fileName; MyFileStatus.name = fileName; MyFileStatus.size = file.ContentLength; MyFileStatus.type = "image/png"; MyFileStatus.delete_url = "Upload.ashx?f=" + fileName; MyFileStatus.delete_type = "DELETE"; MyFileStatus.progress = "1.0"; statuses.Add(MyFileStatus); } } private void WriteJsonIframeSafe(HttpContext context, List<FilesStatus> statuses) { context.Response.AddHeader("Vary", "Accept"); try { if (context.Request["HTTP_ACCEPT"].Contains("application/json")) { context.Response.ContentType = "application/json"; } else { context.Response.ContentType = "text/plain"; } } catch { context.Response.ContentType = "text/plain"; } string jsonObj = js.Serialize(statuses.ToArray()); context.Response.Write(jsonObj); } private void ServeFile (HttpContext context) { if (string.IsNullOrEmpty(context.Request["f"])) ListCurrentFiles(context); else DeliverFile(context); } private void DeliverFile (HttpContext context) { string filePath = ingestPath + context.Request["f"]; if (File.Exists(filePath)) { context.Response.ContentType = "application/octet-stream"; context.Response.WriteFile(filePath); context.Response.AddHeader("Content-Disposition", "attachment, filename=\"" + context.Request["f"] + "\""); } else { context.Response.StatusCode = 404; } } private void ListCurrentFiles (HttpContext context) { List<FilesStatus> files = new List<FilesStatus>(); string[] names = Directory.GetFiles(@"C:\temp\ingest", "*", SearchOption.TopDirectoryOnly); foreach (string name in names) { FileInfo f = new FileInfo(name); FilesStatus MyFileStatus = new FilesStatus(); MyFileStatus.thumbnail_url = "Thumbnail.ashx?f=" + f.Name; MyFileStatus.url = "Upload.ashx?f=" + f.Name; MyFileStatus.name = f.Name; MyFileStatus.size = (int)f.Length; MyFileStatus.type = "image/png"; MyFileStatus.delete_url = "Upload.ashx?f=" + f.Name; MyFileStatus.delete_type = "DELETE"; files.Add(MyFileStatus); /*files.Add(new FilesStatus { thumbnail_url = "Thumbnail.ashx?f=" + f.Name, url = "Upload.ashx?f=" + f.Name, name = f.Name, size = (int)f.Length, type = "image/png", delete_url = "Upload.ashx?f=" + f.Name, delete_type = "DELETE" });*/ } context.Response.AddHeader("Content-Disposition", "inline, filename=\"files.json\""); string jsonObj = js.Serialize(files.ToArray()); context.Response.Write(jsonObj); context.Response.ContentType = "application/json"; } } } The error:
XML Parsing Error: no element found Location: http://nbcddmsps01:87/_layouts/IrvineCompany.SharePoint.CLM/aspx/Upload.ashx?f=test.txt Line Number 1, Column 1: I ONLY got this error AFTER i added verbs to my web.config so I could call DELETE and PUT requests into the httphandler
-12882757 0The evaluation mode is likely triggered for each user on the system. Invoke NDepend manually on your build server with the user identity you use to run your CruiseControl.NET instance, dismiss the evaluation dialog, and then try your build again.
-16534013 0 Using Db::getInstance() in a CLI scriptI've been wanting to create a add-on cron script that utilises Prestashop's DB class instead of instantiating the database handle directly, but I can't seem to figure out where did the "Db" class commonly referenced by "Db::getInstance()" calls get defined.
classes/Db.php defines an abstract DbCore class. MySQLCore extends Db as you can see, however Db is never defined anywhere:
[/home/xxxx/www/shop/classes]# grep -r "extends Db" ../ ../classes/MySQL.php:class MySQLCore extends Db According to another thread on Prestashop forums, the abstract DbCore class is implemented in a class located in override/classes/db, however that directory does not exist.
[/home/xxxx/www/shop/override]# cd ../override/ [/home/xxxx/www/shop/override]# ls ./ ../ classes/ controllers/ [/home/xxxx/www/shop/override]# cd classes/ [/home/xxxx/www/shop/override/classes]# ls ./ ../ _FrontController.php* _Module.php* _MySQL.php* Our shop is working, so obviously I am missing something. We are running Prestashop 1.4.1, so perhaps the docs are no longer applicable.
Quite clearly in many places in the code base functions from the Db class are being used, but this last grep through the code found nothing:
grep -rwI "Db" . | grep -v "::" ./modules/productcomments/productcommentscriterion.php:require_once(dirname(__FILE__).'/../../classes/Db.php'); ./classes/MySQL.php:class MySQLCore extends Db ./classes/Db.php: * Get Db object instance (Singleton) ./classes/Db.php: * @return object Db instance ./classes/Db.php: * Build a Db object Is there something I am missing? Where did this magical Db class come from?
-21141842 0 A query to get me specifique alphabetic orderI have a table called telephone_contacts that contain two columns:
telephone_contacts ( Name varchar(100) Numbers number(20) ) the column name contains about 20,000 rows.
I want to filter the name by alphabetic , example:
I want a query that get me only the first 6 alphabetic (A , B, C , D ,E ,F G)
Then, a query that get me the last 6 alphabetic (U,V,W,X,Y,Z)
Edit:
example: the column name contains the following data:
Abe, car, night, range, chicken, zoo, whatsapp,facebook, viber Adu , aramt, Bike, Male, dog,egg
I want a query that get me only (A , B, C , D ,E ,F G) so the results will be
abe ,care ,chicken facebook,adu,aramt,bike, dog, egg
the rest are ignored
This has regular expression checking to make sure your data is formatted well.
fid = fopen('data.txt','rt'); %these will be your 8 value arrays val1 = []; val2 = []; val3 = []; val4 = []; val5 = []; val6 = []; val7 = []; val8 = []; linenum = 0; % line number in file valnum = 0; % number of value (1-8) while 1 line = fgetl(fid); linenum = linenum+1; if valnum == 8 valnum = 1; else valnum = valnum+1; end %-- if reached end of file, end if isempty(line) | line == -1 fclose(fid); break; end switch valnum case 1 pat = '(?\d{4})-(?\d{2})-(?\d{2})'; % val1 (e.g. 1999-01-04) case 2 pat = '(?\d*[,]*\d*[,]*\d*[.]\d{2})'; % val2 (e.g. 1,100.00) [valid up to 1billion-1] case 3 pat = '(?\d*[,]*\d*[,]*\d*[.]\d{2})'; % val3 (e.g. 1,060.00) [valid up to 1billion-1] case 4 pat = '(?\d*[,]*\d*[,]*\d*[.]\d{2})'; % val4 (e.g. 1,092.50) [valid up to 1billion-1] case 5 pat = '(?\d+)'; % val5 (e.g. 0) case 6 pat = '(?\d*[,]*\d*[,]*\d+)'; % val6 (e.g. 6,225) [valid up to 1billion-1] case 7 pat = '(?\d*[,]*\d*[,]*\d+)'; % val7 (e.g. 1,336,605) [valid up to 1billion-1] case 8 pat = '(?\d+)'; % val8 (e.g. 37) otherwise error('bad linenum') end l = regexp(line,pat,'names'); % l is for line if length(l) == 1 % match if valnum == 1 serialtime = datenum(str2num(l.yr),str2num(l.mo),str2num(l.dy)); % convert to matlab serial date val1 = [val1;serialtime]; else this_val = strrep(l.val,',',''); % strip out comma and convert to number eval(['val',num2str(valnum),' = [val',num2str(valnum),';',this_val,'];']) % save this value into appropriate array end else warning(['line number ',num2str(linenum),' skipped! [didnt pass regexp]: ',line]); end end
-21559305 0 I'm reasonably certain nothing built into iostreams supports this directly.
I think the cleanest way to handle it is to round the number before passing it to an iostream to be printed out:
#include <iostream> #include <vector> #include <cmath> double rounded(double in, int places) { double factor = std::pow(10, places); return std::round(in * factor) / factor; } int main() { std::vector<double> values{ 0.000000095123, 0.0095123, 0.95, 0.95123 }; for (auto i : values) std::cout << "value = " << 100. * rounded(i, 5) << "%\n"; } Due to the way it does rounding, this has a limitation on the magnitude of numbers it can work with. For percentages this probably isn't an issue, but if you were working with a number close to the largest that can be represented in the type in question (double in this case) the multiplication by pow(10, places) could/would overflow and produce bad results.
Though I can't be absolutely certain, it doesn't seem like this would be likely to cause an issue for the problem you seem to be trying to solve.
-6677926 0 Entity Framework Code First Linq MVC 3 RazorThis is my model;
namespace AtAClick.Models { public class LocalBusiness { public int ID { get; set; } public string Name { get; set; } public int CategoryID { get; set; } public string address { get; set; } public string desc { get; set; } public int phone { get; set; } public int mobile { get; set; } public string URL { get; set; } public string email { get; set; } public string facebook { get; set; } public string twitter { get; set; } public string ImageUrl { get; set; } public virtual Category Category { get; set; } } public class Category { public int CategoryID { get; set; } public string Name { get; set; } public virtual ICollection<LocalBusiness> Businesses { get; set; } } } I have a view which lists the categories and one which lists the businesses. I want another which list all the business in a certain category My question is, what would my Linq query in my controller look like? Something like..
var companyquery = from c in db.LocalBusiness where c.Category = Category.Name select c; But obvioulsy this isn't working. I'm new to all this so thanks in advance for the help, and if you need anymore detail just ask. Thanks!!
My controller, is this what you mean?
public ViewResult Browse(int id) { int categoryID = id; var companyquery = from c in db.LocalBusinesses where c.Category.CategoryID == categoryID select c; return View(companyquery); }
-4429256 0 What's the name of jQuery plugin which auto arranges div/image elements on page? That plugin was able to arrange elements to remove empty spaces between them.
Example:

You probably shouldn't be calling glLookAt at all. You sure don't want every object drawn in the middle of the screen. Do you have a problem with the objects changing the modelview matrix and not putting it back? Use glPushMatrix and glPopMatrix instead of repeating the look-at calculation.
The point of lazy init is to defer allocating resources since you don't know when or if you need them.
In your case, this doesn't really make sense: As soon as the image is uploaded, the server will need the thumbnail -- the user wants to see the new image immediately, right? Therefore deferring the creation of the thumbnail has no positive ROI.
-3509650 0Like most (all, maybe) C compilers, the size of an enumerated type can vary. Here's an example program and its output:
#include <stdio.h> typedef enum { val1 = 0x12 } type1; typedef enum { val2 = 0x123456789 } type2; int main(int argc, char **argv) { printf("1: %zu\n2: %zu\n", sizeof(type1), sizeof(type2)); return 0; } Output:
1: 4 2: 8 All that the standard requires is:
The choice of type is implementation-defined, but shall be capable of representing the values of all the members of the enumeration.
A quick web search didn't turn up a clang manual that specified its behaviour, but one is almost certainly out there somewhere.
-39461129 0Change unusedCap() to this?
public double unusedCap() { double fuelLeft=(fuelCapacity - fuelAmount); return fuelLeft; }
-23199426 0 You have an extra "," after Description.
Just remove that comma and add ")" and a space.
-17528653 0Alert the DATA you are getting in response from your ajax page. Try to print in console.log to check. It will print the Object in console
-40711410 0 SpamCop is blocking the emails sent through sparkpostI am using laravel with the famous and popular laravel framework.
I sent a couple emails to my gmail address and a clients email address, I received all of them. A client complaint that he didn't receive them, so I looked it up and saw this in
550-"JunkMail rejected - mta65a.sparkpostmail.com [54.244.48.142]:58459 is in 550 an RBL, see Blocked - see http://www.spamcop.net/bl.shtml?54.244.48.142"
SpamCop's blocking list works on a mail-server level. If your mail was blocked incorrectly it may be due to the actions of other users or technical flaws with the mail system you use. If you are not the administrator of your email system, please forward this information to them.
I opened the detailed message and it said it is in the process of getting unblocked.
When i checked again to write this post it stated that sparkpost was not any more blocked, but before it stated it was reported as spam 10 times in the last 8 or 80 days, something like that
Now: what can I do about this? stop using sparkpost? I guess all mail services have the exact same problem
what can my client do about this?
-36170983 1 Using global variables in python in a functiondef foo(): global a a = 10 vs
a = 0 def foo(): a = 10 What is the use of declaring global in a function instead of declaring variables right at the top. It should be cleaner this way ?
-15235011 0Couple of ideas:
If the rows in the text files have a modification timestamp, you could update your script to keep track of when it runs, and then only process the records that have been modified since the last run.
If the rows in the text files have a field that can act as a primary key, you could maintain a fingerprint cache for each row, keyed by that id. Use this to detect when a row changes, and skip unchanged rows. I.e., in the loop that reads the text file, calculate the SHA1 (or whatever) hash of the whole row, and then compare that to the hash from your cache. If they match, the row hasn't changed, so skip it. Otherwise, update/insert the MySQL record and the store the new hash value in the cache. The cache could be a GDBM file, a memcached server, a fingerprint field in your MySQL tables, whatever. This will leave unchanged rows untouched (and thus still cached) on MySQL.
Perform updates inside a transaction to avoid inconsistencies.
Not really sure what the issue is here, sounds pretty simple though. I guess I'll add my 2 cents. First, unless youre looking for perform Inserts, Updates, or Deletes for these work times, I think a database is overkill for this.. look at using XML instead.
Secondly, ASP.NET offers some pretty simple controls to display data like this. Check out the ASP.NET Repeater Control, which allow you to create a formatted header and footer, and repeate a templated item layout. Its pretty fast and effective, and definately in line for what youre looking for here.
Best of luck
-25824662 0 Where are are views controllers in the storyboard initiated?I have a main view controller in the main story board. I want this controller to have a state when it is initiated. I need to know where this view controller is initiated so that I can change its constructor to the following custom constructor. Can someone help me out?
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{ self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { self.state= @"login";} return self;}
-15046902 0 The current working directory in ST can be opened in the Finder by right-clicking anywhere in an open file and selecting "Reveal in Finder".
At any rate, the concept of a 'current working directory' is meaningful in ST only in the context of a project which itself is a folder and all the files in it (except the ones filtered out by the project file). That would preclude the possibility of changing the working directory straight away, I should think
-38031842 0In short, the less work you do in the onBindViewHolder() method, the better the performance of your list view scrolling.
The most efficient implementation would simply take the data from the model that is passed and simply set it to the view holder.
Since all of this work in the onBindViewHolder() method is done on the UI thread, offloading any additional work either prior to the binding or offloaded to anthoer thread is beneficial to list view performance.
For example, lets say that you have a list that contains a bunch of tasks as below:
class Task { Date dateDue; String title; String description; // getters and setters here } Each task has a title, description and a due date associate with it. As a requirement for your app, if the today's date is before the due date, the row should be green and if passed the due date, it should be red. Also the Task object associated with it requires some special date formatting before setting it to the view.
There are two things that will be done in this onBindViewHolder() as each row is rendered onto the screen:
e.g.
class MyRecyclerView.Adapter extends RecyclerView.Adapter { static final TODAYS_DATE = new Date(); static final DATE_FORMAT = new SimpleDateFormat("MM dd, yyyy"); public onBindViewHolder(Task.ViewHolder tvh, int position) { Task task = getItem(position); if (TODAYS_DATE.compareTo(task.dateDue) > 0) { tvh.backgroundView.setColor(Color.GREEN); } else { tvh.backgroundView.setColor(Color.RED); } String dueDateFormatted = DATE_FORMAT.format(task.getDateDue()); tvh.dateTextView.setDate(dueDateFormatted); } } In the above, for every row that is rendered, a date comparison is being made. While we were at it, we even took the liberty to make today's date a constant – object creation is possibly one of the most expensive things you can do in a onBindViewHolder() so any optimization is appreciated. Additionally, the date that is passed in the Task object was not in the proper format so it is formatted that on-the-fly as well.
Although this example is trivial, this can quickly balloon into halting the list view scrolling to a crawl. The better way of doing this is to pass an intermediary object, such as a view model that represents the state of the view instead of the actual business model instead.
Instead of passing your Task as the model to the adapter, we create an intermediatary model called TaskViewModel that is created and set to the adapter. Now before setting any information is sent to the adapter, all of the work is done before any view rendering is applied. This comes at the cost of longer initialization time prior to sending data to your RecyclerView but at the better trade-off of list view performance.
This view model instead could be:
public class TaskViewModel { int overdueColor; String dateDue; } Now when tasked to bind the data to the view, we have the actual view state being represented in the view model and our UI thread can continue to be jank free.
public onBindViewHolder(Task.ViewHolder tvh, int position) { TaskViewModel taskViewModel = getItem(position); tvh.backgroundView.setColor(taskViewModel.getOverdueColor()); tvh.dateTextView.setDate(taskViewModel.getDateDue()); }
-541312 0 You could do this, and you can do it in several ways.
1) (simple) copy the file to your server, and rename it. Point your download links to this copy.
2) (harder) Create a stub php file, called , read the file from the remote server within php, and stream the content to the script output. This will need you to set appropriate headers, etc. as well as setting up your webserver to parse through PHP.
Seriously, I'd go with option 1. (assumes you have a legal right to serve the content, etc.)
-28477244 0 Why does Ansible fail to execute this simple shell script?I came across a very strange problem with Ansible (1.8.2) that boils down to executing this simple command in a shell script:
#!/bin/sh # transform a String into lowercase chars: echo "TeSt" | tr [:upper:] [:lower:] When I log into the remote Solaris machine, this script seems to work no matter in which shell I am (e.g., /bin/sh, /bin/bash):
# ./test.sh test Also when I execute this script using a remote ssh command, it works:
# ssh root@<remote-host> '/tmp/test.sh' test However, when I execute the same script with the Ansible command or shell modules, I get a "Bad String" error no matter what shell I specify:
- shell: executable=/bin/sh /tmp/test.sh [FATAL stderr: Bad string] - shell: executable=/bin/bash /tmp/test.sh [FATAL stderr: Bad string] - command: /tmp/test.sh [FATAL stderr: Bad string] It took me ages to figure out that it works with the raw module:
- raw: executable=/bin/sh /tmp/test.sh [OK] Does anyone have a clue why the shell and command modules produce this error?
Some more info about the remote host on which the script fails:
/bin/sh, /bin/bash, /bin/ksh) are GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)The locale differs! When I log in or execute a remote ssh command, the locale looks like this:
LANG= LC_CTYPE="C" LC_NUMERIC="C" LC_TIME="C" LC_COLLATE="C" LC_MONETARY="C" LC_MESSAGES="C" LC_ALL= However, with Ansible, I get this:
LANG=en_US.UTF-8 LC_CTYPE=en_US.UTF-8 LC_NUMERIC="en_US.UTF-8" LC_TIME="en_US.UTF-8" LC_COLLATE="en_US.UTF-8" LC_MONETARY="en_US.UTF-8" LC_MESSAGES="en_US.UTF-8" LC_ALL=
-30445119 0 If you have an text/textarea attribute named my_attr you can get it by: product->getMyAttr();
Check the javadoc for the set method. You'll see the following:
Parameters:
year - the value used to set the YEAR calendar field.
month - the value used to set the MONTH calendar field. Month value is 0-based. e.g., 0 for January.
date - the value used to set the DAY_OF_MONTH calendar field.
So your code should become the following:
private static int getWeekOfYear(int y, int m, int d) { Calendar cal = Calendar.getInstance(); cal.setMinimalDaysInFirstWeek(4); cal.set(y, m - 1, d); // Note the change here return cal.get(Calendar.WEEK_OF_YEAR); }
-39925758 0 Getting duplicate rows on subquery So this has been bothering me for some time because I feel like in MSSQL this query would run just fine but at my new job I am forced to use Oracle. I have a subselect in a query where I want to find all of the people not assigned to a survey. My query is as follows:
Select distinct * From GetAllUsers, getperms Where id not in (getperms.users) and Survey_ID = '1' If there are three users in the getperms table I get three rows for each person in the the GETALLUsers table.
I guess I could do some kind of join and that's no problem, it's just really bothering me that this doesn't work when i think that it should.
-9376341 0 how to tag people in a facebook album via the graph API (php)Possible Duplicate:
How can I tag a user in a photo using the Facebook Graph API?
As title says, how can i tag people via the Facebook graph API on an existing album?
-39269948 0The shell builtin kill or the external one /bin/kill does not take Process ID (or Job ID) via standard input stream. You need to pass them as argument to kill, so:
kill -- $(<ff) should do.
If you want to kill them one by one and doing something in between, you can create an array with the pids and iterate over them:
pids=( $(<file.txt) ) && for i in "${pids[@]}"; do echo "killing $i"; kill -- "$i"; done
-11226039 0 Your ItemsSource is a simple binding to a collection of [something] that will fill out the combolist, here's a quick sample:
public class MyDataSource { public IEnumerable<string> ComboItems { get { return new string[] { "Test 1", "Test 2" }; } } } <ComboBox Height="23" Name="status" IsReadOnly="False" ItemsSource="{Binding Path=ComboItems}" Width="120"> </ComboBox> That's not a complete sample, but it gives you the idea.
It's also worth noting that you don't have to use the ItemsSource property, this is also acceptable:
<ComboBox Height="23" Name="status" IsReadOnly="False" Width="120"> <ComboBox.Items> <ComboBoxItem>Test 1</ComboBoxItem> <ComboBoxItem>Test 2</ComboBoxItem> </ComboBox.Items> </ComboBox>
-35055284 0 Closing curly bracket } is misplaced to bottom for function volcano_theme_options(). Check and fix that.
I tried your initial way with the following:
use strict; use warnings; use Time::Piece; my $time = Time::Piece->strptime( "07/26/2014 00:23:09", "%m/%d/%Y %H:%M:%S"); print $time;
-23083876 0 You can attach session with socket and get in connection event. Get the user session in authorization, if you're using express then do this:
var sessionStore = new express.session.MemoryStore(); io.set('authorization', function (handshake, accept){ var cookies = require('express/node_modules/cookie').parse(handshake.headers.cookie); var parsed = require('express/node_modules/connect/lib/utils').parseSignedCookies(cookies, 'SESSION_SECRET'); sessionStore.get(parsed.sid, function (error, session){ if (session != null && session.user != null){ accept(null, true); handshake.session = session; } }); }); And in your connection event you can get it like:
socket.handshake.session
-32141404 0 Here is a solution i found with your markup.
Used CSS to beautify it.
Jquery:
What did you do?
when .menu_link is hovered i find what index it has.
The index finds if its the first child or second etc.
When we have this magic index number var nthNumber
we can use it to find its corresponding .submenu_panel (I'm guessing here since i cant see all your code) and hide or show this panel
Eg. when we hover the first .menu_link,
we will show the first .submenu_panel
And we do the same for the second and third etc.
$(".menu_link, .submenu_panel").hover(function() { //Hover inn function var nthNumber = $(this).index() + 1; $("[id$=Submenu]").show(); $("[id$=Submenu] .submenu_panel:nth-of-type(" + nthNumber + ")").show(); }, function() { //Hover out function $("[id$=Submenu]").hide(); var nthNumber = $(this).index() + 1; $("[id$=Submenu] .submenu_panel:nth-of-type(" + nthNumber + ")").hide(); }); #menu [id$=Menu] { border: 2px solid #2980b9; border-radius: 5px; background-color: #3498db; } #menu [id$=Menu] .menu_link { padding: 10px 10px; display: inline-block; font-size: 1.2em; } #menu [id$=Menu] .menu_link:hover { background-color: #45a9ec; //border: 2px solid #2980b9; border-radius: 2px; cursor: pointer; //Visual only (REMOVE)! } #menu [id$=Submenu] { display: none; } #menu [id$=Submenu] .submenu_panel { display: none; background-color: #45a9ec; border: 2px solid #2980b9; border-top: none; border-bottom-right-radius: 2px; border-bottom-left-radius: 2px; } #menu [id$=Submenu] .submenu_panel .submenu_link { position: relative; display: block; text-indent: 15px; font-size: 1.1em; padding: 4px 0px; border-bottom: 1px solid #2980b9; } #menu [id$=Submenu] .submenu_panel .submenu_link:hover { background-color: #56bafd; cursor: pointer; //ONLY FOR VISUAL(REMOVE)! } #menu [id$=Submenu] .submenu_panel .submenu_link:first-child { border-top: 1px solid #2980b9; margin-top: -5px; padding-top: 5px; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <nav id="menu"> <div id="pn1Menu"> <a class="menu_link">Lorem</a> <a class="menu_link">Ipsum</a> <a class="menu_link">Dollar</a> <a class="menu_link">Si</a> <a class="menu_link">Amet</a> </div> <div id="pn1Submenu"> <div class="submenu_panel"> <a class="submenu_link">100</a> <a class="submenu_link">200</a> <a class="submenu_link">300</a> <a class="submenu_link">400</a> <a class="submenu_link">500</a> <a class="submenu_link">600</a> </div> <div class="submenu_panel"> <a class="submenu_link">010</a> <a class="submenu_link">020</a> <a class="submenu_link">030</a> <a class="submenu_link">040</a> <a class="submenu_link">050</a> <a class="submenu_link">060</a> </div> <div class="submenu_panel"> <a class="submenu_link">1001</a> <a class="submenu_link">2002</a> <a class="submenu_link">3003</a> <a class="submenu_link">4004</a> <a class="submenu_link">5005</a> <a class="submenu_link">6006</a> </div> </div> </nav> The function is marked const, so the developer used a rather ugly const_cast to cast the const away in order to call sort.
ASSERT appears to be a macro (due to it being in capital letters) that most likely calls assert, which terminates the program if the expression evaluates to zero.
For a summary of what trimmed mean means, refer to this page.
-5370594 0 Highly customizable Listview for .Net?The 10% trimmed mean is the mean computed by excluding the 10% largest and 10% smallest values from the sample and taking the arithmetic mean of the remaining 80% of the sample ...
do you guys know a .net ListView-Replacement which can be highly customized? I am developing an app which is similar to a "todo" list. I want to be able to customize almost every visual detail of the list so I get something like this:

I want also to be able to reorder items by mouse + I need drag&drop. If you don't know any ListView, maybe you know how I could make my own listview like this one from scratch?
Thanks for your ideas!
-26388560 0$apply is necessary to tell angular that changes happened to the scope. Built-in directives and services like ngClick or $http do that internally. If you apply (sic!) changes to the scope and don't use the aforementioned built-in services, then you are responsible for calling $apply yourself.
So if show isn't called within an ngClickhandler, e.g., then you need to call $apply yourself.
guest.TABLE2.keyfield belongs to the updated table which does not exists in this query
This is a query with the same logic as the update.
For each record of T2 you are going to get the value for update based on T1.
select guest.TABLE2.* ,(SELECT count(T1.key_field) FROM ThisDB..TABLE1 T1 WHERE T1.key_field = guest.TABLE2.keyfield AND T1.date_field between (DATEADD(DAY, -7, guest.TABLE2.other_date)) and guest.TABLE2.other_date) from guest.TABLE2
-7050629 0 The observer is notified when an observed key path changes it's value. The ´change` dictionary contains information related to how the observed key path has changed. This dictionary is only filled with the values according to the options that you provide when setting
NSKeyValueObservingOptionNew - Specifies that you want to have access to the new value that the key path changed into. NSKeyValueObservingOptionOld - Specifies that you want to have access to the old value that the key path changed from.If specified to be sent these old and/or new values are accessible from the change dictionary using these keys:
NSKeyValueChangeNewKey - To access the new value.NSKeyValueChangeOldKey - To access the old/previous value.This is driving me round the bend at the moment. As a homebrew exercise I wanted to template a recursive call in a class. in the .h file I have:
template <typename T1> class BinaryTree { public: BinaryTree(T1 element); ~BinaryTree(); BinaryTree* addLeftLeaf(BinaryTree<T1>* node); etc...
then in the .cpp
template <typename T1> BinaryTree* BinaryTree<T1>::addLeftLeaf(BinaryTree<T1>* node) { return node; } I've tried seemingly loads of ideas but thus far nothing. Just errors like error C2955: 'BinaryTree' : use of class template requires template argument list
Any suggestions would be kindly appreciated.
Thanks
Mark
-38530394 0Update your controller:
var controller = ['$scope',function ($scope) { ... $scope.$on('my-tpl-ready', function() { $('#firstId').datepicker({ format: 'dd-mm-yyyy' }); }); }]; Also add this to your template:
<div ... ng-init="$emit('my-tpl-ready')"> ... </div>
-28548343 0 I could not find a way to scroll through the length of my output so what I did is a loop that is gradually increasing by increments of 0.1 the value of ${maxnoise} (with a condition on the number of line output) because this variable is actually the one conditioning how big is the output. It works fine this way so I consider my question answered.
-32331720 0 Getting Error.code = 0 in db.transaction functionI am creating a project in Phonegap with Ionic.I am inserting and fetching dynamic content with sqlite and local storage.
I created a Dashboard contoller below are my dashboard controller code
angular.module('myWallet').controller('dashCtrl', function($scope,$state,$ionicPopup,$ionicHistory,AuthService){ $scope.data = {}; //goBack $scope.myGoBack = function() { $ionicHistory.goBack(); }; //********** error code function ************ function errorDashFunction(err) { alert("Error Code: "+error.code); } //********** Success code function ************ function successDashFunction() { var totalCashInHand = Coming_totalIncome - Coming_totalExpenses; alert(totalCashInHand ); } var current_user_id=window.localStorage.getItem('userid'); var Coming_totalIncome = 0; var Coming_totalExpenses= 0; var Coming_totalCashInHand = 0; //********** Fetching Values from DB ************ db.transaction(function (tx) { tx.executeSql("SELECT SUM(amount) as Totalincome FROM WALLET_INCOMES WHERE user_id ='"+current_user_id+"'", [], function(tx,results){ console.log(results); if(results.rows[0].Totalincome != null) { Coming_totalIncome = results.rows[0].Totalincome; } }); tx.executeSql("SELECT SUM(amount) as Totalexpenses FROM WALLET_EXPENSES WHERE user_id ='"+current_user_id+"'", [], function(tx,results){ if(results.rows[0].Totalexpenses != null) { Coming_totalExpenses = results.rows[0].Totalexpenses; } }); return true; },errorDashFunction,successDashFunction); }) When i run this code on Ripple then it is alerting TotalCashInHand Price. BUT when i am running this code on my mobile then it is always showing Error code "0".
-10086312 0 Launch home screen chooserI have defined my app as home screen but I have to change the home screen during my app execution. I know it is not possible to change the home screen, it is only possible to launch the home screen selector. How could I launch the home screen selector when I need to do it?
I'm using:
PackageManager pm = getPackageManager(); pm.clearPackagePreferredActivities("com.dm.prado");
I have two problems:
The selector is only showed when I press home button, I want to show it when I want.
The selector is never showed again when I Selecthome screen first time
-31881799 0"Errors" in Rx can be a a little difficult to grasp at first, because they have a slightly different meaning from what most people expect.
From the Error Handling documentation (emphasis mine):
An Observable typically does not throw exceptions. Instead it notifies any observers that an unrecoverable error has occurred by terminating the Observable sequence with an onError notification.
onError() is supposed to be used when an Observable encounters an unrecoverable error- that is when your Observable cannot continue emitting items. When you are subscribing, you might use something like onErrorResumeNext to try some recovery action, but that should be the end of the source Observable.
Instead, you may want to adjust what your Observable emits to support emitting an error item, or include a flag indicating that an error was encountered.
If your error truly is unrecoverable, then you may want to revisit your recovery strategy and try a slightly different approach.
-24361805 0 Should I instantiate MatlabControl from withing Matlab or Java?It is not obvious from here http://www.cs.virginia.edu/~whitehouse/matlab/JavaMatlab.html, how to use MatlabControl class.
On one hand it is given an example:
First, instantiate a MatlabControl object
MatlabControl mc = new MatlabControl();
On the other hand it is said
Snag 1: MatlabControl objects must be instantiated from within your Matlab session! (or by other java objects that were instantiated by your matlab session). This is because Matlab runs its own JVM, and you need to run MatlabControl in the same JVM that matlab is using. (this is why you need to make sure that MatlabControl is in your matlab classpath.) More specifically, if your program is defined in "mypackage/MyClass.java", you need to type
mypackage.MyClass.main({'param1','param2',...})
What is correct? Where to execute
MatlabControl mc = new MatlabControl(); ?
In my java code?
Or at matlab command prompt?
-10830563 0 Stop the Music in WebView when Screen Time-OutI am programming that allow users can listen music in WebView via the URL web link. But I wonder why when the android phone user screen Time-Out my music in WebView also stop. Do you have any solution to solve this problem?
public class PlayMusicActivity extends Activity { WebView mWebView; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.playlist); mWebView = (WebView) findViewById(R.id.webView1); mWebView.setWebViewClient(new HelloWebViewClient()); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setPluginsEnabled(true); mWebView.getSettings().setAllowFileAccess(true); mWebView.loadUrl("http://www.myweb.com/music.html"); } private class HelloWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) { mWebView.goBack(); return true; } return super.onKeyDown(keyCode, event); } @Override public void onPause() { mWebView.setVisibility(View.GONE); mWebView.destroy(); super.onPause(); } } Appreciate for your help.
Best regards, Virak
-1945777 0 C++ Array vs vectorwhen using C++ vector, time spent is 718 milliseconds, while when I use Array, time is almost 0 milliseconds.
Why so much performance difference?
int _tmain(int argc, _TCHAR* argv[]) { const int size = 10000; clock_t start, end; start = clock(); vector<int> v(size*size); for(int i = 0; i < size; i++) { for(int j = 0; j < size; j++) { v[i*size+j] = 1; } } end = clock(); cout<< (end - start) <<" milliseconds."<<endl; // 718 milliseconds int f = 0; start = clock(); int arr[size*size]; for(int i = 0; i < size; i++) { for(int j = 0; j < size; j++) { arr[i*size+j] = 1; } } end = clock(); cout<< ( end - start) <<" milliseconds."<<endl; // 0 milliseconds return 0; }
-12131897 0 use remove_if found under algorithm
Given a begin and end iterator along with a predicate, you can remove any element that results in the predicate evaluating to true. I'll include both C++03 and C++11 examples.
C++03:
#include <algorithm> #include <iostream> #include <iterator> #include <vector> #include <cstdlib> #include <ctime> template <typename T> struct is_equal { T val; is_equal (const T& v) : val (v) { } bool operator() (const T& test) { return (val == test); } }; struct is_odd { bool operator() (int test) { return (test % 2 == 1); } }; template <typename T> std::ostream& operator<< (std::ostream& os, const std::vector <T>& v) { typedef typename std::vector <T>::const_iterator itr; for (itr i = v.begin (); i != v.end (); ++i) os << *i << " "; return os; } int main (int argc, char* argv[]) { srand (time (NULL)); std::vector <int> vec (10); // vector has size of 10 std::generate (vec.begin (), vec.end (), rand); // populate with random numbers std::cout << vec << std::endl; vec.erase (std::remove_if (vec.begin (), vec.end (), is_odd ()), // removes all odd elements vec.end ()); std::cout << vec << std::endl; return 0; } C++11:
#include <algorithm> #include <iostream> #include <iterator> #include <numeric> #include <vector> #include <cstdlib> template<typename T> std::ostream& operator<< (std::ostream& os, const std::vector <T>& v) { for (auto i : v) os << i << " "; return os; } int main(int argc, char* argv[]) { std::vector <int> vec(10); // vector has size of 10 std::iota (vec.begin(), vec.end(), 1); // populate with [1, 2, 3, ...] std::cout << vec << std::endl; vec.erase (std::remove_if (vec.begin(), vec.end(), [](int i){ return (i == 3); }), vec.end ()); std::cout << vec << std::endl; return 0; } For any questions on using the STL, I personally consult http://en.cppreference.com/w/ and http://www.cplusplus.com/reference/
-30490112 0Do this:
$cats = get_the_category(); if(count($cats)){ $cat = $cats[0]; $cat = sprintf('<a href="%s" id="cat-%s">%s</a>',get_category_link($cat->cat_ID), $cat->cat_ID, $cat->cat_name ); }
-525567 0 I've worked on a Drupal project with about 1 million nodes. We added transactional support and it wasn't too hard. You'll need to patch the core of course but this shouldn't be a major concern for an enterprise application with good support and documentation. I was working as the observing pair programmer on the transactional support. I think it took us about a day.
Edit:
I've been working as a Drupal Developer for a few years now. And recently, I have revised my position on Drupal in relation to best practices and enterprise application.
I don't think Drupal is particularly suited to the Enterprise space because:
Also: The enterprise Drupal Application I was once working on has now been ported into Rails.
-16734729 0Absolutely. For example, MySQL does not have hash and merge joins. Certain query patterns will suffer greatly there.
The notion that the RDBMS used does not matter is strange to me. Different databases have very non-uniform performance characteristics. Performance very much varies with workload.
If you want to exclude the RDBMS as much as possible from your tests you have to carefully make sure that you are not testing any RDBMS-specific performance features by accident. This is very hard.
-6892968 0 Insert data from custom PHP function into MySQL databaseI'm having problems inserting a particular line of code into my MySQL database. It inserts three rows just fine, but the "html_href" row isn't going in for whatever reason. Here is my code:
function html_path() { $title = strtolower($_POST['title']); // convert title to lower case $filename = str_replace(" ", "-", $title); // replace spaces with dashes $html_href = $filename . ".html"; // add the extension } And my MySQL query code:
$query = "INSERT INTO work (title, logline, html_href, synopsis) VALUES"; $query .= "('".mysql_real_escape_string($_POST['title'])."',"; $query .= "'".mysql_real_escape_string($_POST['logline'])."',"; $query .= "'".html_path()."',"; $query .= "'".mysql_real_escape_string($_POST['synopsis'])."')"; $result = mysql_query($query); The title, logline, and synopsis values go in just fine, but the html_href() function inserts a blank row.
Use the Neo4jPHP driver from Josh Adell, there are also sample projects listet on
I think there are no built-in ways to access the shell from Neo4jPHP but if you can use its http facilities, you can do something like I did here.
-20204669 0Use the chunk option fig.show='hold'.
I don't know much about Ocracoke, but why don't you look into Visual Studio?
-6990135 0 What other hidden variables (pre-defined using macros) do I have access to in g++?note: I am using g++ version 4.3.4
So I was learning about assert statements and came across a homebrew assert macro that uses that variables __LINE__ and __FILE__ which (cleverly) give the line number and the file name from where they were called -- in this case, from where the assertation failed. These are epic pieces of information to have!
I was able to infer that the variable __FUNCTION__ will give you the function name that you are inside of... amazing!! However, when assert.h is at work, you also get the arguments to the function (i.e. function: int main(int, char**) and all I can do currently is get the function name...
Generally speaking, where can I learn more about these wonderful hidden variables and get a complete list of all of them?
p.s. I guess I understand now why you aren't supposed to use variable names starting with __
My technique for this is to write a shell script that does the job, and then run it via find. For example, your actions could be written into a script munger.sh:
#!/bin/sh for file in "$@" do output="output_dir/$(basename "$file")" sed -e 's:foo:bar:g' "$file" > "$output" done The find command becomes:
find input_dir -name "PATTERN" -exec sh munger.sh {} + This runs the script with the file names as arguments, bundling conveniently large number of file names into a single invocation of the shell script. If you're not going to need it again, you can simply remove munger.sh when you're done.
Yes, you can do all sorts of contortions to execute the command the way you want (perhaps using find … -exec bash -c "the script to be executed" arg0 {} +) but it is often harder than writing a relatively simple script and using it and throwing it away. There tend to be fewer problems with quoting, for example, when you run an explicit script than when you try to write the script on the command line. If you find yourself fighting with single quotes, double quotes and backslashes (or back-quotes), then it is time to use a simple script as shown.
I found the solution!
it was simpler than it seems! just use comma (,) as seprator!
https://itunes.apple.com/lookup?id=1st_APP_ID,2nd_APP_ID,3rd_APP_ID
-1549527 0 dups = {} newlist = [] for x in biglist: if x['link'] not in dups: newlist.append(x) dups[x['link']] = None print newlist produces
[{'link': 'u2.com', 'title': 'U2 Band'}, {'link': 'abc.com', 'title': 'ABC Station'}] Note that here I used a dictionary. This makes the test not in dups much more efficient than using a list.
I'm experiencing a very strange problem with Rails and ajax using jQuery (although I don't think it's specific to jQuery).
My Rails application uses the cookie session store, and I have a very simple login that sets the user id in the session. If the user_id isn't set in the session, it redirects to a login page. This works with no problems. JQuery GET requests work fine too. The problem is when I do a jQuery POST - the browser sends the session cookie ok (I confirmed this with Firebug and dumping request.cookies to the log) but the session is blank, i.e. session is {}.
I'm doing this in my application.js:
$(document).ajaxSend(function(e, xhr, options) { var token = $("meta[name='csrf-token']").attr('content'); xhr.setRequestHeader('X-CSRF-Token', token); }); and here is my sample post:
$.post('/test/1', { _method: 'delete' }, null, 'json'); which should get to this controller method (_method: delete):
def destroy respond_to do |format| format.json { render :json => { :destroyed => 'ok' }.to_json } end end Looking at the log and using Firebug I can confirm that the correct cookie value is sent in the request header when the ajax post occurs, but it seems that at some point Rails loses this value and therefore loses the session, so it redirects to the login page and never gets to the method.
I've tried everything I can think of to debug this but I'm coming around to the idea that this might be a bug in Rails. I'm using Rails 3.0.4 and jQuery 1.5 if that helps. I find it very strange that regular (i.e. non-ajax) get and post requests work, and ajax get requests work with no problems, it's just the ajax posts that don't.
Any help in trying to fix this would be greatly appreciated!
Many thanks,
Dave
First of all, a service does not imply that a separate thread is running, but I guess this is what you want to do. If you run several threads, there is no way of the AndroidOS to terminate them besides killing the whole Dalvik VM. And this means that you have no way of knowing when you are about to be terminated. If you have a service with a thread and use proper life-cycle management, i.e. kill the thread when Android notifies the service that it is about to stop it, then it is easy to maintain state.
Regarding your question: use several services with one thread each
-12749679 0When you change your submit to this it won't submit if RequiredFields returns false.
<input type="submit" value="Login" onsubmit="return RequiredFields();"/>
-7159977 0 No a handler is a separate object class and so one would not need to be defined if you were making an Activity.
A handler would be used if you wanted to go do something in another thread/class and call back to the activity/ui.
-12801510 0It's still a regular many-to-many relationship, and it should get mapped correctly by default. Specific business (validation) rules do not change its nature.
You can implement IValidatableObject if you want to enforce specific cardinalities when saving.
-10392488 0You need an instance of an object that implements Runnable to pass to the Thread constructor; the call new HelloRunnable() gives that to you.
You need a Thread object to run; the call to new Thread() gives that to you.
You call start() on that new Thread instance; it calls the run() method on the Runnable instance you gave to its constructor.
If you define your endpoint within a resource block, for example:
module MyApiModule class MyApiClass < Grape::API resource :foo do get :time do {epoch_time: Time.now.to_i.to_s} end end resource :bar do get :bar_time do {epoch_bar_time: Time.now.to_i.to_s} end end end end ... you will see this nice separators:

You never check for 'eof' in your read loop in readInput(). This means you have garbage values (perhaps 0) for these lines after you hit eof:
inputFile >> data[i].name; inputFile >> data[i].idNum; inputFile >> data[i].testNum; Then what do you suppose is going to happen here, if data[i].testNum is zero?
data[i].average = total / data[i].testNum; You might consider checking inputFile.good() before each read from the stream, and handle it appropriately when it returns false.
Look at your RIFF header. This will tell you the endianness of the Wav file.
Use that endian-ness to read in your 32-bit floats correctly. For example: If your system is little endian (say, based on an x86 processor) and your wav file is big endian(say, created on an old PPC mac), you will need to do a 32-bit endian swap after you read in the data so that your float variable actually contains data that makes sense (this is usually a value between -1.0f and 1.0f )
-27164649 0if i am getting you right, you can call the following function on your desired event to switch between the markers without clicking.
marker1.showInfoWindow(); marker2.showInfoWindow(); marker3.showInfoWindow(); Mark as right if it works for you .:)
P.S: An info window can be hidden by calling hideInfoWindow().
-20108569 0You need this in your CSS:
#nav-wrap .container .wsite-menu-default { display:table; margin:auto; } Here is your fiddle working http://jsfiddle.net/58sqQ/2/
-24837331 0you need to add a var as xmlhttp; on starting to get the status result please use below code i modify it,
<script> //Ajax to send request.. function sendPayment() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { alert(xmlhttp.readyState);// this always returns = 1 alert(xmlhttp.responseText) ; //this is always empty. if (xmlhttp.readyState==4 && xmlhttp.status==200) { if (xmlhttp.responseText=='1') { alert('success'); } } } xmlhttp.open("POST","payments/callSSL.php",true); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlhttp.send(Id=100); return false; } </script>
-3468788 0 The HTML5 spec has an interesting take on the issue of valid email addresses:
A valid e-mail address is a string that matches the ABNF production 1*( atext / "." ) "@" ldh-str 1*( "." ldh-str ) where atext is defined in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section 3.5.
The nice thing about this, of course, is that you can then take a look at the open source browser's source code for validating it (look for the IsValidEmailAddress function). Of course it's in C, but not too hard to translate to JS.
You could use one of the following methods:
float:left; on .menudisplay:inline-block; + vertical-align:top; on .menuposition:absolute; on #changetitleWith the float and vertical-align methods, you'll need to remove the margin-right on .menu ul (float will also work if you give the menu a width). With position:absolute you're goning to spend a whole lot of time getting the left and top values right :P
Probably inline-block. It's the easiest to set up, and just works. Best of all, it's dynamic. If you want to add another menu item at a later date and have to make the .menu div bigger, you don't have to change the CSS, whereas float usually would require you to set a width on .menu and position:absolute definitely requires that (as it is telling the browser exactly at what pixel to put #changetitle. If you're going to have more columns continue this design throughout the rest of the page, you may want to consider using column or display:table (never an actual <table> :P)
Long story short, use inline-block.
Here's a working demo: https://jsfiddle.net/mnfgo32g/12/
-13974721 0I developed a set of configurable utility functions for Riak mapreduce in Erlang. As I wanted to be able to specify sets of critera, I decided to allow the user to pass configuration in as a JSON document as this works well for all client types, although other text representations should also work. Examples of how these functions are used from curl are available in the README.markdown file.
You can pass an argument to each individual map or reduce phase function through the 'arg' parameter. Whatever you specify here will be passed on as the final parameter to the map or reduce phase, see the example below:
"query":[{"map":{"language":"erlang","module":"riak_mapreduce_utils", "function":"map_link","keep":false, "arg":"{\"bucket\":\"master\"}"}},
-26117708 0 There is no PRINT command. Use raise notice instead.
create function f() returns void as $$ begin FOR i IN 1..10 LOOP raise notice '%', i; -- i will take on the values 1,2,3,4,5,6,7,8,9,10 within the loop END LOOP; end; $$ language plpgsql; http://www.postgresql.org/docs/current/static/plpgsql.html
-27097738 0Your question raises some interesting issues. I will try to explain how you can fix it, but, as @Uri mentions, there may be better ways to address your problem.
I've assumed @tranfee is to be set equal to the first value in the hash whose key begins with "tran" and that @rate is to be set equal to the first value in the hash whose key begins with "rate". If that interpretation is not correct, please let me know.
Note that I've put initialize in the PaymentType module in a class (Papa) and made TranFee and Rate subclasses. That's the only way you can use super within initialize in the subclasses of that class.
Code
class Transaction attr_reader :tranfee, :rate def initialize(hash={}) o = PaymentType::TranFee.new(hash) @tranfee = o.instance_variable_get(o.instance_variables.first) o = PaymentType::Rate.new(hash) @rate = o.instance_variable_get(o.instance_variables.first) end end .
module PaymentType class Papa def initialize(hash, prefix) key, value = hash.find { |key,value| key.start_with?(prefix) && value } (raise ArgumentError, "No key beginning with #{prefix}") unless key instance_variable_set("@#{key}", value) self.class.singleton_class.class_eval { attr_reader key } end end class TranFee < Papa def initialize(hash) super hash, "tran" end end class Rate < Papa def initialize(hash) super hash, "rate" end end end I believe the method Object#singleton_class has been available since Ruby 1.9.3.
Example
reg_debit = {"name" => "reg_debit", "rate_base" => 0.0005, "tran_fee" => 0.21, "rate_basis_points" => 0.002, "tran_auth_fee" => 0.10} a = Transaction.new reg_debit p Transaction.instance_methods(false) #=> [:tranfee, :rate] p a.instance_variables #=> [:@tranfee, :@rate] p a.tranfee #=> 0.21 p a.rate #=> 0.0005
-37496393 0 <android.support.v4.widget.NestedScrollView android:id="@+id/nested_scrollbar" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="fill_vertical" app:layout_behavior="@string/appbar_scrolling_view_behavior" android:scrollbars="none" > <LinearLayout android:id="@+id/nested_scrollbar_linear" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <android.support.v7.widget.CardView android:id="@+id/flexible.example.cardview" android:layout_width="match_parent" android:layout_height="wrap_content"> </android.support.v7.widget.CardView> <android.support.v7.widget.RecyclerView android:id="@+id/list_view" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_behavior="@string/appbar_scrolling_view_behavior" /> </LinearLayout> </android.support.v4.widget.NestedScrollView> and apply .setNestedScrollingEnabled to recyclerview and set it to false
P.s: for Api lower 21 :
ViewCompat.setNestedScrollingEnabled(recyclerView, false);
I want to connect windows phone with remote server.
I trying to connect that time the below error occurred. How to solve it.
An exception of type 'System.Net.WebException' occurred in System.Windows.ni.dll and wasn't handled before a managed/native boundary
Here mycode
C# code
ProgressIndicator prog;
private void btnLogin_Click(System.Object sender, System.Windows.RoutedEventArgs e) { try { string url = "http://192.168.2.112/check_login/check.php"; //string url = "http://localhost/sam.php"; Uri uri = new Uri(url, UriKind.Absolute); StringBuilder postData = new StringBuilder(); postData.AppendFormat("{0}={1}", "sUsername", HttpUtility.UrlEncode(this.txtUsername.Text)); postData.AppendFormat("&{0}={1}", "sPassword", HttpUtility.UrlEncode(this.txtPassword.Password.ToString())); WebClient client = default(WebClient); client = new WebClient(); client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; client.Headers[HttpRequestHeader.ContentLength] = postData.Length.ToString(); client.UploadStringCompleted += client_UploadStringCompleted; client.UploadProgressChanged += client_UploadProgressChanged; client.UploadStringAsync(uri, "POST", postData.ToString()); } catch (Exception ex) { MessageBox.Show(ex.Message); } prog = new ProgressIndicator(); prog.IsIndeterminate = true; prog.IsVisible = true; prog.Text = "Loading...."; SystemTray.SetProgressIndicator(this, prog); } private void client_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e) { //Me.txtResult.Text = "Uploading.... " & e.ProgressPercentage & "%" } private void client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e) { if (e.Cancelled == false & e.Error == null) { prog.IsVisible = false; MessageBox.Show(e.Result.ToString()); } } PHP code
<?php $hostname_localhost ="localhost"; $database_localhost ="androidlogin"; $username_localhost ="root"; $password_localhost =""; $localhost=mysql_connect($hostname_localhost,$username_localhost,$password_localhost) or trigger_error(mysql_error(),E_USER_ERROR); mysql_select_db($database_localhost, $localhost); $username = $_POST['username']; $password = $_POST['password']; $query_search = "select * from user where username = '".$username."' AND password = '".$password. "'"; $query_exec = mysql_query($query_search) or die(mysql_error()); $rows = mysql_num_rows($query_exec); //echo $rows; if($rows == 0) { echo "No Such User Found"; } else { echo "User Found"; } ?> Please help me. Thanks in advance.
-5969274 0For others who are in the same requirement, you may consider my columnchooser implementation. My Dialog Form Declaration. (Dialog box which will be shown when columnchooser button is clicked.
All required fields will not be allowed to remove.Creating the ColumnChooser Button for my Grid.
jq("#grid").jqGrid('navButtonAdd','#pager',{ caption: "Columns", title: "Customize Columns", onClickButton : function (){ /*jq("#grid").jqGrid('columnChooser',{ height:columnChooserHt });*/ createDialogDiv(); jq( "#dialog-form" ).dialog('open'); } }); Adding Save(OK) and Cancel Buttons to my Div.
jq(function(){ jq( "#dialog-form" ).dialog({ autoOpen: false, height: 300, width: 350, modal: true, buttons: { "OK": function() { changeColView(); jq( "#dialog-form" ).dialog('close'); }, Cancel: function() { jq( "#dialog-form" ).dialog('close'); } }, close: function() { } }); }); Function which inserts the column names with the select boxes which needed to be displayed on the ColumnChooser Dialog Box.
function createDialogDiv(){ var colModelDiv = jq("#grid").jqGrid('getGridParam','colModel'); var colNamesDiv = jq("#grid").jqGrid('getGridParam','colNames'); //alert(JSON.stringify(colModelDiv)); //alert(JSON.stringify(colNameDiv)); var container = document.getElementById('dialog-form'); //alert(colNamesDiv.length); var chckBox=""; for(i=0;i<colNamesDiv.length;i++){ if(colModelDiv[i].hidden && colModelDiv[i].hidden == true ){ chckBox+="<input type='checkbox' id='"+colNamesDiv[i]+"' name='"+colNamesDiv[i]+"' value='"+colModelDiv[i].name+"'>"+colNamesDiv[i]+"</input><br/>"; }else{ if(colModelDiv[i].editrules && colModelDiv[i].editrules.required){ chckBox+="<input type='checkbox' id='"+colNamesDiv[i]+"' name='"+colNamesDiv[i]+"' value='"+colModelDiv[i].name+"' disabled>"+colNamesDiv[i]+"</input><br/>"; } else chckBox+="<input type='checkbox' id='"+colNamesDiv[i]+"' name='"+colNamesDiv[i]+"' value='"+colModelDiv[i].name+"' checked>"+colNamesDiv[i]+"</input><br/>"; } } container.innerHTML=chckBox; } Finally the actual method which changes the Columns chosen from Columnchooser.
function changeColView(){ var colModelDiv = jq("#grid").jqGrid('getGridParam','colModel'); var colNamesDiv = jq("#grid").jqGrid('getGridParam','colNames'); for(i=0;i<colNamesDiv.length;i++){ var chckBox=document.getElementById(colNamesDiv[i]); if(chckBox && chckBox.value && (!(chckBox.checked || chckBox.disabled))){ jq("#grid").jqGrid('hideCol',chckBox.value); } if(chckBox && chckBox.checked){ jq("#grid").jqGrid('showCol',chckBox.value); } } jq("#grid").trigger('reloadGrid'); } Plz let me know your thoughts on this one.
-23273433 0 javascript/jquery ignore or override :hover styleShort Description: I want to use JS/JQuery to take precedence over the CSS :hover psuedo-class for specific brief moments without removing the CSS rule for the other majority of cases. Since the site is already script-heavy enough I'm trying to find a solution that doesn't require me to nuke the CSS interaction and rely on mouseover/mouseout events. In my case there's a marked performance difference between the two.
Details: I've created a CSS-based dropdown shopping cart viewer. I rigged up some JQuery to force the cart open when the user triggers certain page interactions like adding an item to the cart. When the cart is "programmatically opened" an 8 second timer is used to close it. All that works. The Problem: I also want to add a click handler to the cart so that when the user clicks on it it will be explicitly closed whether the 8second timeout has expired or not. However, when they click on the cart they are - by definition - hovering over it, kicking in the :hover state and keeping it from closing. Is there a way to temporarily disable the :hover rule and then once the cart has closed reinstate it.
HTML:
<span class="minicart-wrapper"> <a class="minicart-anchor" href="...">Shopping Cart</a> <div id="minicart"> ... </div> </span> CSS:
.minicart-wrapper #minicart { display: none; } .minicart-wrapper:hover #minicart, .minicart-wrapper #minicart.open { display: block; } JQuery:
function openMinicart() { var minicart = jQuery('#minicart'); minicart.addClass('open'); minicart.bind('click', {}, closeMinicart); window.setTimeout(closeMinicart, 8000); } function closeMinicart() { var minicart = jQuery('#minicart'); minicart.removeClass('open'); minicart.unbind('click', closeMinicart); } I've tried: a few suggestions I found here like changing .minicart-wrapper:hover #minicart to .minicart-wrapper:hover #minicart.canhover. I then added removeClass(canhover) to the beginning of closeMinicart() and setTimeout(function(){jQuery('#minicart').addClass('canhover')},500); to the end of it. However it seems that this is too short a timeout for the browser to refresh it's hover-state and before it's done rendering the hover re-triggers and the cart stays put.
Thanks for any suggestions.
Edit: Thanks Jedison. Here's the JSFiddle: http://jsfiddle.net/WJS3h/ . Also fixed some bugs in the sample.
Edit 2: Turns out I had a code error (oops) and the can-not-hover class method is the way to go. Thanks to everyone who commented.
-20623296 0The issue is that the images change the height of the div. You can keep them from doing that by floating them. Also, if you want them to always fit within the container, you'll need to adjust the width of the images. So, something like this might work:
#cool img { float:left; width:25%; height: auto; } In the interest of creating semantic HTML, you may want to change your markup to something more like the following:
<nav> <ul> <li><a href="#"><img src="/my/cool/image.png" alt="Menu item 1"/></a></li> <li><a href="#"><img src="/my/cool/image.png" alt="Menu item 2"/></a></li> <li><a href="#"><img src="/my/cool/image.png" alt="Menu item 3"/></a></li> </ul> </nav>
-37824729 1 How to use random.randint to find random 0 and 1 with not equal propbability I am using DEAP toolbox in Python for Genetic Algorithm.
toolbox.register("attr_bool", random.randint, 0, 1) is a function randomly chooses 0 and 1 for populations in GA. I want to force GA to choose 0 and 1 randomly but with for example 80% one and the rest zero.
I think srng.binomial(X.shape, p=retain_prob) is a choice, but I want to use random.randint function. Wondering how we can do that?
interface TestInterface { void work(); } class TestClass { public void work(){ System.out.println("Work in CLASS"); } } public class Driver extends TestClass implements TestInterface { public static void main(String[] args) { new TestClass().work(); } } Can any one explain to me, why just because the same work method signature exists in TestClass this class compiles fine?
-8074650 0$('#show_existing_suggestions').live('click',function(){});
-23604821 0 If you simply want to squash all commits into a single, initial commit, just reset the repository and amend the first commit:
git reset hash-of-first-commit git add -A git commit --amend Git reset will leave the working tree intact, so everything is still there. So just add the files using git add commands, and amend the first commit with these changes. Compared to rebase -i you'll lose the ability to merge the git comments though.
-27137862 0 DIV is not displaying in IE8 onwards due to CSS classWhen I create a div like below, it is displaying in IE7, but not displaying on IE8 and later versions. When I view source code, I can see this div in all IE versions, but not displaying in IE8 and plus.
My Aspx code:
<div runat="server" id="divLoginImage" class="loginImage"> </div> CSS:
.loginImage { position: absolute; left: -500px; top: 10px; } Please note that if I remove class attribute as show below, this is working fine.
<div runat="server" id="divLoginImage" > </div> What is wrong with my CSS?
-38876686 0If you want to avoid forwarding landing page then use:
RewriteEngine On RewriteBase / RewriteCond %{REQUEST_URI} !\.(gif|jpg|png|swf|css|html|js|ico|pdf)$ RewriteCond %{REQUEST_URI} !^/app\.php(/.*)?$ [NC] RewriteRule ^(.+)$ app.php/$1 [L] .+ will match anything but not the landing page.
In case you want to exclude all the top level domain URLS then use:
RewriteCond %{HTTP_HOST} !^(www\.)?example\.com$ [NC] RewriteCond %{REQUEST_URI} !\.(gif|jpg|png|swf|css|html|js|ico|pdf)$ RewriteCond %{REQUEST_URI} !^/app\.php(/.*)?$ [NC] RewriteRule ^(.*)$ app.php/$1 [L]
-33903608 0 It looks like you're not selecting the current slide's image. I found the current slide by looping through the slides and checking their opacity.
var sr = $(this).attr('src'); var sr; $(this).closest('.slides').find('.slide-container').each(function(index) { if ($(this).find('.slide').css("opacity") === 1) { sr = $(this).find('img').attr('src'); } });
-24610631 0 This is what the ValidationGroup property is for. Suppose you have the following controls:
<asp:RequiredFieldValidator ID="rfv1" runat="server" ValidationGroup="Group1" /> <asp:RequiredFieldValidator ID="rfv2" runat="server" ValidationGroup="Group1" /> <asp:RequiredFieldValidator ID="rfv3" runat="server" ValidationGroup="Group2" /> <asp:Button ID="btn1" runat="server" ValidationGroup="Group1" Text="Button 1" /> <asp:Button ID="btn2" runat="server" ValidationGroup="Group2" Text="Button 2" /> In the example above, btn1 will only cause validation for the controls validated by rfv1 and rfv2, whilst btn2 will only cause validation for the control validated by rfv3.
I suggest you to get more information about Data modeling in Cassandra. I've read A Big Data Modeling Methodology for Apache Cassandra and Basic Rules of Cassandra Data Modeling as useful articles in this case. They will help you understanding about modelling the tables based on your queries (Query-Driven methodology) and data duplication and its advantages/disadvantages.
-5640101 0Edit
I just found this jQuery plugin - http://markdalgleish.com/projects/tmpload/ Does exactly what you want, and can be coupled with $.tmpl
I have built a lightweight template manager that loads templates via Ajax, which allows you to separate the templates into more manageable modules. It also performs simple, in-memory caching to prevent unnecessary HTTP requests. (I have used jQuery.ajax here for brevity)
var TEMPLATES = {}; var Template = { load: function(url, fn) { if(!TEMPLATES.hasOwnProperty(url)) { $.ajax({ url: url, success: function(data) { TEMPLATES[url] = data; fn(data); } }); } else { fn(TEMPLATES[url]); } }, render: function(tmpl, context) { // Apply context to template string here // using library such as underscore.js or mustache.js } }; You would then use this code as follows, handling the template data via callback:
Template.load('/path/to/template/file', function(tmpl) { var output = Template.render(tmpl, { 'myVar': 'some value' }); });
-40020062 0 Standard method would be to use numpy.linalg.eig.
from numpy import linalg as LA w, v = LA.eig(np.diag((1, 2, 3))) # w: # array([ 1., 2., 3.]) # v: # array([[ 1., 0., 0.], # [ 0., 1., 0.], # [ 0., 0., 1.]]) Obviously, if your matrix is very specific (let's say very large and sparse), usually you want to use iterative approach (e.g. Krylov subspace method) to find most dominant eigenvalues. See discussion for more details.
-5475890 0You are using the wrong overload for the .ActionLink. Try this instead...
<%= Html.ActionLink(item.venue, "Details", "Venues", new { name = item.venue }, new {}) %> It is currently selecting string, string, object, object overload. Your "Venues" string is being used for routing data.
I am implementing a text-based version of Scrabble for a College project.
My dictionary is quite large, weighing in at around 400.000 words (std::string).
Searching for a valid word will suck, big time, in terms of efficiency if I go for a vector<string> ( O(n) ). Are there any good alternatives? Keep in mind, I'm enrolled in freshman year. Nothing TOO complex!
Thanks for your time!
Francisco
-33282185 0The first thing to point out is that there is nothing like racing condition. The right terminology is just race condition. Keep this in mind for the future ;-)
I suppose you are using a BroadcastReceiver to receive messages and that you have created the object and tell it to run in a separate thread because of the animation. This means that your showFab method can be called twice in one time. To handle this, define the method as synchronized.
-29436119 0There is no built-in NSString method available to do what you want. You need to write your own method. Objective-C does let you "extend" classes with new methods to cover cases like this.
This is how I would do it:
@interface NSString(Extend) -(NSInteger)proximity:(NSString*)otherString; @end @implementation NSString(Extend) -(NSInteger)proximity:(NSString*)otherString { NSUInteger length = [otherString length]; if(length != [self length]) return -1; NSUInteger k; NSUInteger differences = 0; for(k=0;k<length;++k) { unichar c1 = [self characterAtIndex:k]; unichar c2 = [otherString characterAtIndex:k]; if(c1!=c2) { ++differences; } } return differences; } @end Then in my code at the place I wanted to check I would say something like
-6289011 0Keys inside appSettings are retrieved as NameValueCollection which by definition
Represents a collection of associated String keys and String values that can be accessed either with the key or with the index.
So you can have only the data type string as value for an AppSettings key
And yes, AppSettings is the only place where you can store your settings.
MSDN defines AppSettings like this.
-6755697 0Contains custom application settings, such as file paths, XML Web service URLs, or any information that is stored in the.ini file for an application.
$result = mysql_query("SELECT * FROM stores where StoreID=$id order by city"); if (!$result) { die('Invalid query: ' . mysql_error()); }else{ while($row = mysql_fetch_assoc($result)){ echo $row['city']." : ".$row['street']."<br />"; } } while() is fetching results step by step, so it will give it your result
-38237320 0 Header Troubles on my WebsiteBefore I posted anyone question, and I got some criticism, so I'm trying to format a better question now. Yeah. So, I'm making a website, and I have a header for navigation. However, in CSS, I put the header with div class = "header" to color:black;. I don't know why the background isn't black and is not there. I made a jsfiddle. As you can see when you go on the jsfiddle , the header is non-existent, and when you scroll down, as you can see, the header is not white. Does anyone know how to make the header solid, or is there inconsistencies in the hierarchy?
.header { position:relative; top:-20px; left:0px; width:100%; background-color:#000000; border-left: 5px solid white; } .header ul li a { color: black; position: fixed; top: 13px; font-weight: bold; text-decoration: none; //background: #000000; } ul { list-style-type: none; } a#strawpoll { right: 215px; } a#previousblogs { right: 95px; } a#aboutme { right: 15px; } h1 { text-align: left; position: fixed; left: 10px; top: -10px; color: black; } body { position: relative; top: 60px; font-family: 'Raleway', sans-serif; background-image: //url('https://cms-images.idgesg.net/images/article/2015/11/black-100630491-orig.jpg'); background-size: cover; color: white; text-align: center; color: black; } a:link { color: black; text-decoration: none; } .header a:hover { text-decoration: underline; } a:visited { color: black; text-decoration: none; } <title>My Blog</title> <meta charset="utf-8"/> <link rel="stylesheet" type="text/css" href="blog.css"> <link rel="icon" href="http://images4.fanpop.com/image/photos/22600000/Smiley-Face-smiley-faces-22608094-1000-1000.png"> <link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet"> <link type="text/css" rel="stylesheet" href="jquery.mmenu.css" /> <body> <div class="header"> <div class = "navbar"> <ul> <li><a id = "strawpoll" href ="#"> Strawpoll </a></li> <li><a id = "previousblogs" href ="#"> Previous Blogs </a></li> <li><a id = "aboutme" href ="#"> About Me </a></li> </ul> </div> <script src="app.js"></script> <h1><a href ="#">My Life</a></h1> </div> <p> texttext, yeah, I put this here to increase the page length, so that I can show you guys the header is not filled in. starting from here its all reandom stuff. <p> bopbopbopbopbopbopbob </p> <p> bopbopbopbopbopbopbob </p><p> bopbopbopbopbopbopbob </p><p> bopbopbopbopbopbopbob </p><p> bopbopbopbopbopbopbob </p><p> bopbopbopbopbopbopbob </p><p> bopbopbopbopbopbopbob </p><p> bopbopbopbopbopbopbob </p><p> bopbopbopbopbopbopbob </p><p> bopbopbopbopbopbopbob <p> bopbopbopbopbopbopbob </p><p> bopbopbopbopbopbopbob </p> </p><p> bopbopbopbopbopbopbob </p> sapodksadksa daa </p> Here is the jsfiddle
Add in the comments if I'm unclear. Hopefully I am.
-13274720 0 Handle Trailing slashes at the end of URLThere is clear cut advantage of using consistent URL structure for wordpress website.
I want all of my URL's to end with / (the homepage and internal page URL's). Let me give an example website which is handling it very efficiently so that the URL's without ending with slash or ending with multiple slashes are 301 redirected to URL with single slash.
http://viralpatel.net/blogs 301 redirect to viralpatel.net/blogs/
http://viralpatel.net/blogs// 301 redirect to viralpatel.net/blogs/
http://viralpatel.net/blogs/ 200 OK
http://viralpatel.net/blogs/check-string-is-valid-date-java 301 redirect to http://viralpatel.net/blogs/check-string-is-valid-date-java/
http://viralpatel.net/blogs/check-string-is-valid-date-java// 301 redirect to http://viralpatel.net/blogs/check-string-is-valid-date-java/
http://viralpatel.net/blogs/check-string-is-valid-date-java/ 200 OK
Any idea what .htaccess rules can help achieve this. My current .htaccess looks like:
RewriteEngine On RewriteCond %{HTTP_HOST} ^javaexperience.com [NC] RewriteRule ^(.*)$ http://www.javaexperience.com/$1 [R=301,L] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L]
-3268493 0 When you build with the DLL version of the CRT (/MDd for example), errno is a macro. Translating it to a function call to obtain the shared value of errno. Fix it like this:
int err = errno; so you can inspect the value of err.
-5735389 0Logically, that copy/paste is exactly what happens. I'm afraid there isn't any more to it. You don't need the ;, though.
Your specific example is covered by the spec, section 6.10.2 Source file inclusion, paragraph 3:
-36190743 0A preprocessing directive of the form
# include"q-char-sequence"new-linecauses the replacement of that directive by the entire contents of the source file identified by the specified sequence between the
"delimiters.
RecyclerView setLayoutManager expects RecyclerView.LayoutManager type as input so change
final LinearLayoutManager layoutManager = new LinearLayoutManager(this); with
final RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this); and remove
layoutManager.setOrientation(LinearLayoutManager.VERTICAL); layoutManager.generateDefaultLayoutParams(); take a look at developer page for proper usage http://developer.android.com/training/material/lists-cards.html
-38716459 0 Make a variable unusable/unaccessible in scope halfwayLet's say I have this code:
for (int i = 0; i < x.size(); i++) { auto &in = input[i]; auto &func = functions[i]; auto &out = output[i]; // pseudo-code from here: unaccessiable(i); i = func(in); // error, i is not declared out = func(i); // error, i is not declared // useful when you mistake in/out for i } I need to achieve effect that a variable is not accessible or usable after a certain line in the code. (in this code, after the unaccessiable(i)) Specifically I want to disable the iterator of a for's loop.
NOTE: This is only for code correctness, and nothing beyond that. So lambdas (non-compile-time solutions) are just performance hindering.
-2493329 0Regression Testing. Partly automated, partly manual, depending on the tools, time and money.
Normally you should different levels of testing, and even though as software developers we would like to automate everything, some things have to be verified by hand, by having a collection of test cases executed by testers.
The Wikipedia article on regression testing is a good read.
From the whole collection of tests that most be checked by hand, it is normally worthwhile to select the minimum set that guarantee the functionality of the system to reduce costs. The balance, of course, is a fine one and depends a lot on how much the code was actually changed. Good modularization of the software product helps a lot on having good regression testing.
-11809636 0You have an empty string for an href on the overview link. So, it's attempting to "follow" to that href, which obviously doesn't exist.
Hi i'm currently implement MVVM in a WPF app i'm developing. I implemented the ViewModel and the Views by using 2 separate projects. Only the View is referencing from the ViewModel. However, i've come to a point where i need the information in the Settings class(auto generated by Visual Studio using the Settings dialogue in the Project's Properties) to the ViewModel. How do i do that since ViewModel shouldn't reference the View's classes and also Settings class has a internal modifier.
need your suggestions on this one...i'm using mvvm-light which has the Locator pattern..
thanks
-15437939 0Your string has backslashes which are read in Python as escape codes. These are when a character preceded by a backslash is changed into a special character. For example, \n is a newline. You will need to either escape them (with another backslash) or just use a raw string.
r'C:\Software\api\render\3bit\sim>'
-4882084 0 Answer.update_all(["user_id = ?", @user.id], ["answered_by = ? and user_id == ?", @user.email, 0])
-30383240 0 How to rename list of Excel sheets with a list of names I need to create profiles for a large list of clients. Each client has an ID number and I need to create a sheet in a workbook for each client, with the ID number for each client as the name for their respective sheets. I also have a sheet template that I would rather use to help create profiles in a uniform and professional manner. My question is: is there a way I can create a copy of the template for each of my clients and rename them with each of the ID's on my list, all at once?
-29501967 0You forgot to put the END delimiter
DELIMITER @ CREATE EVENT update_stats ON SCHEDULE EVERY 15 MINUTE ON COMPLETION PRESERVE ENABLE DO BEGIN UPDATE stats JOIN temp_stats ON stats.unique_key = temp_stats.unique_key SET stats.clicks = stats.clicks + temp_stats.clicks; TRUNCATE temp_stats; END@ DELIMITER ;
-394146 0 Displaying polymorphic classes I have an existing app with a command-line interface that I'm adding a GUI to. One situation that often comes up is that I have a list of objects that inherit from one class, and need to be displayed in a list, but each subclass has a slightly different way of being displayed.
Not wanting to have giant switch statements everywhere using reflection/RTTI to do the displaying, each class knows how to return its own summary string which then gets displayed in the list:
int position = 0; for (vector<DisplayableObject>::const_iterator iDisp = listToDisplay.begin(); iDisp != listToDisplay.end(); ++iDisp) cout << ++position << ". " << iDisp->GetSummary(); Similar functions are there to display different information in different contexts. This was all fine and good until we needed to add a GUI. A string is no longer sufficient - I need to create graphical controls.
I don't want to have to modify every single class to be able to display it in a GUI - especially since there is at least one more GUI platform we will want to move this to.
Is there some kind of technique I can use to separate this GUI code out of the data objects without resorting to RTTI and switch statements? It would be nice to be able to take out the GetSummary functions as well.
Ideally I'd be able to have a heierarchy of display classes that could take a data class and display it based on the runtime type instead of the compile time type:
shared_ptr<Displayer> displayer = new ConsoleDisplayer(); // or new GUIDisplayer() for (vector<DisplayableObject>::const_iterator iDisp = listToDisplay.begin(); iDisp != listToDisplay.end(); ++iDisp) displayer->Display(*iDisp);
-39959947 0 Count truthy objects in an array I'd like to count truthy objects in an array. Since I can pass a block to count, the most idiomatic way I found was this:
[1, nil, 'foo', false, true].count{ |i| i } => 3 But I was wondering if there was a better way, especially using the syntax count(&:something), because passing a full block here looks like overkill to me.
AFAIK, there is no truthy? method in Ruby, so I couldn't find how to achieve this.
I have 4 different types of widgets in my app. For each of the widget type, I have a Class derived from AppWidgetProvider and a service which handles the periodic update to the widget.
Now I have to create different sizes widget for each type. If I keep 3 sizes for each widget, do I have to create 12 classes / services ? Is there a better way ?
Any help / link to sample is welcome thanks in advance
-8132413 0 C# incrementing static variables upon instantiationI have a bankAccount object I'd like to increment using the constructor. The objective is to have it increment with every new object the class instantiates.
Note: I've overriden the ToString() to display the accountType and accountNumber;
Here is my code:
public class SavingsAccount { private static int accountNumber = 1000; private bool active; private decimal balance; public SavingsAccount(bool active, decimal balance, string accountType) { accountNumber++; this.active = active; this.balance = balance; this.accountType = accountType; } } Why is it that when I plug this in main like so:
class Program { static void Main(string[] args) { SavingsAccount potato = new SavingsAccount(true, 100.0m, "Savings"); SavingsAccount magician = new SavingsAccount(true, 200.0m, "Savings"); Console.WriteLine(potato.ToString()); Console.WriteLine(magician.ToString()); } } The output I get does not increment it individually i.e.
savings 1001 savings 1002 but instead I get:
savings 1002 savings 1002 How do I make it to be the former and not the latter?
-39732169 0Does the compiler really let you assign object to Customer without a cast?
Anyway, DataContext won't be initialized yet in the constructor.
You could handle the DataContextChanged event, which will be raised whenever DataContext changes -- in this case, that'll probably just be when it's assigned in the course of instantiating the DataTemplate that creates MyUserControl. And that's just what you want.
XAML
<UserControl ... DataContextChanged="MyUserControl_DataContextChanged" ... C#
private Customer _customer; void MyUserControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { _customer = (Customer)DataContext; } Or you could just cast DataContext to Customer whenever you need to use it. Check for null, of course. You didn't say what you're doing with Customer so it's hard to be sure when you would need to do something with it.
Try the appropriately named array_reverse function!
<?php if(function_exists('fetch_feed')) { include_once(ABSPATH . WPINC . '/feed.php'); // include the required file $feed = fetch_feed('http://sample.com.au/events/feed/'); // specify the source feed $limit = $feed->get_item_quantity(25); // specify number of items $items = $feed->get_items(0, $limit); // create an array of items $semti = array_reverse($items); // & flip it } if ($limit == 0) echo '<div>The feed is unavailable.</div>'; else foreach ($semti as $item) : ?> <p><b><a href="<?php echo esc_url( $item->get_permalink() ); ?>" target="_blank"> <?php echo esc_html( $item->get_title() ); ?></a></b> <?php echo esc_html( $item->get_date('| j F | g:i a') ); ?><br> <?php echo sanitize_text_field( $item->get_content() ); ?> </p> <?php endforeach; ?> -18307197 0array_reverse
Return an array with elements in reverse order
array array_reverse ( array $array [, bool $preserve_keys = false ] )Takes an input array and returns a new array with the order of the elements reversed.
Actually, I made it to solve the problem. Whoever uses backbone, node.js, and require.js, remember to include jquery and jquery UI as libraries with require, and when creating dynamic elements with backbone such as:
$('#content').append(html); inside backbone call jquery UI $('.drag').draggable();
-30947492 0 I totally agree with @Holden on that!
Mocking RDDS is difficult; executing your unit tests in a local Spark context is preferred, as recommended in the programming guide.
I know this may not technically be a unit test, but it is hopefully close enough.
Unit Testing
Spark is friendly to unit testing with any popular unit test framework. Simply create a SparkContext in your test with the master URL set to local, run your operations, and then call SparkContext.stop() to tear it down. Make sure you stop the context within a finally block or the test framework’s tearDown method, as Spark does not support two contexts running concurrently in the same program.
But if you are really interested and you still want to try mocking RDDs, I'll suggest that you read the ImplicitSuite test code.
The only reason they are pseudo-mocking the RDD is to test if implict works well with the compiler, but they don't actually need a real RDD.
def mockRDD[T]: org.apache.spark.rdd.RDD[T] = null And it's not even a real mock. It just creates a null object of type RDD[T]
-35149839 0 fe_sendauth: no password supplied on pgadmin IIII am getting the above error when I am creating a DB using pgadminIII.
As per the answers related to the previous answers, what I should do is in my pg_hba.conf, update the peer section to trust for user postgres, but in my pg_hba.conf there are 3 users with name postgres.
# Allow replication connections from localhost, by a user with the # replication privilege. #local replication postgres peer #host replication postgres 127.0.0.1/32 md5 #host replication postgres ::1/128 md5 Which one I should update?
-5335850 0When user launch the application you could show a splash screen for 1 or 2 second after that you could show the progress (status) of your application using text msg.
for example "Initialization of Synchronization Service" ,"Storing to data base", "Loading map" .
The above text msg. is just a reference,you could have more descriptive text to show on screen along with progress bar.
-13957112 0 Use Two Different columns to compare to another worksheetI have two columns that are different from each other. One containing numbers and the other containing text. Trying to compare (match) both to another separate worksheet.
Of course, I can VLookup each one separatedly but that doesn't give me the answer I'm looking for. I want to know if the first two columns correlate with the other worksheet.
I also tried an IF(VLookup but probably did it wrong.
To sum it up. If Column A and Column B are both on the other worksheet, then True or False.
-10146804 0 How to close a jframe without closing the main program?i designed java desktop application in that application when i press a button another Jframe is shown that draws a tree but when i close the Jframe whole operation is close but i only want to close that Jfarme what should i do? here is the jframe codes:
public class DrawTree extends JFrame{ public int XDIM, YDIM; public Graphics display; @Override public void paint(Graphics g) {} // override method // constructor sets window dimensions public DrawTree(int x, int y) { XDIM = x; YDIM = y; this.setBounds(0,0,XDIM,YDIM); this.setVisible(false); this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); display = this.getGraphics(); // draw static background as a black rectangle display.setColor(Color.black); display.fillRect(0,0,x,y); display.setColor(Color.red); try{Thread.sleep(500);} catch(Exception e) {} // Synch with system } // drawingwindow public static int depth(BinaryNode N) // find max depth of tree { if (N==null) return 0; int l = depth(N.left); int r = depth(N.right); if (l>r) return l+1; else return r+1; } // internal vars used by drawtree routines: private int bheight = 50; // branch height private int yoff = 30; // static y-offset // l is level, lb,rb are the bounds (position of left and right child) private void drawnode(BinaryNode N,int l, int lb, int rb) { if (N==null) return; try{Thread.sleep(100);} catch(Exception e) {} // slow down display.setColor(Color.green); display.fillOval(((lb+rb)/2)-10,yoff+(l*bheight),20,20); display.setColor(Color.red); display.drawString(N.element+"",((lb+rb)/2)-5,yoff+15+(l*bheight)); display.setColor(Color.blue); // draw branches if (N.left!=null) { display.drawLine((lb+rb)/2,yoff+10+(l*bheight),((3*lb+rb)/4),yoff+(l*bheight+bheight)); drawnode(N.left,l+1,lb,(lb+rb)/2); } if (N.right!=null) { display.drawLine((lb+rb)/2,yoff+10+(l*bheight),((3*rb+lb)/4),yoff+(l*bheight+bheight)); drawnode(N.right,l+1,(lb+rb)/2,rb); } } // drawnode public void drawtree(BinaryNode T) { if (T==null) return; int d = depth(T); bheight = (YDIM/d); display.setColor(Color.white); display.fillRect(0,0,XDIM,YDIM); // clear background drawnode(T,0,0,XDIM); }} and another question
when i new a object from my tree class,i want to access that object in all my button codes so where i should define that or better to say , how i should define that object that can access in all my codes??
-13144933 0 Form Authentication / Profiles slow on Azure Cloud, fine locallyI'm using MVC 4 on Azure, and it loads very slowly (over a minute). Here are the load times of a few pages:
(the 6.9 minutes was when I tried loading 7 tabs with different pages)
This problem does not occur when I'm using the Azure emulator, locally.
I've tried using an extra large instance, and using remote desktop to run the site locally, and it was just as slow. Also I have tried using IIS Express and normal IIS, and nothing there either.
I created a completely fresh MVC project using the "Internet application" template, which includes security, and it is very slow as well, so I'm pretty sure the other things I'm using in my project are not causing the problem. Here are the load times with just the default MVC project: 
I was originally using separate affinity regions for my membership DB and my website, but I've tried using matching affinity groups on both the blank MVC template with forms authentication and my project.
Revisiting pages doesn't improve their speed significantly.
I also tried creating just a MVC site without authentication, with a 10x5000 table generated:
<html> <body> <table> <thead> <tr> @for (int i = 0; i < 10; i++) { <th>@i </th> } </tr> </thead> <tbody> @for(int i = 0; i < 5000; i++) { <tr> @for(int j = 0; j < 10; j++) { <td>Row @i , column @j</td> } </tr> } </tbody> </table> </body> </html> This loads fine, both locally and on the cloud. Even from a cold start it is only ~10-15 seconds.
So I'm fairly certain that the issue lies in the Profile/Membership/Authentication of ASP.NET, but only while it is deployed to Azure (since I'm using the same SQL Azure database with Universal Providers when running locally, and there aren't these slowdowns).
I expected this problem to be more common, but the only thing that really seemed relevant was this: social.msdn.microsoft.com/Forums/en-US/windowsazuremanagement/thread/7d3323d8-571b-4b8f-9fdb-bd5ccc6c39b7 (possibly this: stackoverflow.com/questions/10791433/saving-changes-very-slow-via-datacontext)
I'm working through the things to try, as suggested in that thread, at: windowsazure.com/en-us/manage/windows/best-practices/
-25586073 0 Bcrypt, what is meant salt and cost?I was always using MD5 for encrypting passwords, but I read that it's should no more be used, and instead use bcrypt..
I'm using zendframework 2 , where I found it describing bcrypt configurations as follows:
$bcrypt = new Bcrypt(array( 'salt' => 'random value', 'cost' => 11 )); what is the salt and what is the cost ? and how could them be used?
-22340661 0You forgot to mention the "columns" attribute in the Class Meta. Please follow the mechanism currently used by Horizon to render the "Instances" data table. You can find the detailed step by step tutorial to create and render a data table here: http://docs.openstack.org/developer/horizon/topics/tutorial.html
Hope it helps
-34418139 0Here's a similar approach, using regular expressions instead:
import re def convert_string(s): return map(int, re.findall(r'[0-9]+', s)) Or using a list comprehension:
import re def convert_string(s): return [int(num) for num in re.findall(r'[0-9]+', s)] This is a more general approach and will work for any character (in this case '|') that separates the numbers in the input string.
-39184263 0 Catch image data via WI-FII have a device that takes pictures and send to an iPhone app via WI-FI. The iPhone has to connect to the device's WIFI, and when the device takes a picture it saves to camera roll of the iPhone if the app is in the foreground. However if the app is in the background, nothing happens.
My question is, can I catch this image data with another app that I create? I assume the data arrives to the iPhone via WI-FI when the app is in the background also.
Thank you for your help.
-20189448 0You share methods in a module, and you place such a module inside the lib folder.
Something like lib/fake_data.rb containing
module FakeData def random_address [Faker::Address.street_address, Faker::Address.city].join("\n") end module_function end and inside your rake task just require the module, and call FakeData.random_address.
But, if it is like a seed you need to do every time you run your tests, you should consider adding this to your general before all.
E.g. my spec_helper looks like this:
# Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f } RSpec.configure do |config| config.use_transactional_fixtures = true config.infer_base_class_for_anonymous_controllers = false config.order = "random" include SetupSupport config.before(:all) do load_db_seed end end and the module SetupSupport is defined in spec/support/setup_support.rb and looks as follows:
module SetupSupport def load_db_seed load(File.join(Rails.root, 'db', 'seeds.rb')) end end Not sure if you need to load the seeds, or are already doing this, but this is the ideal spot to also generate needed fake data.
Note that my setup support class is defined in spec/support because the code is only relevant to my specs, I have no rake task also needing the same code.
.aspx doesn't fulfill the MVC pattern because the aspx page (the 'view') is called before the code behind (the 'controller').
This means that the controller has a 'hard dependency' on the view, which is very much against MVC principles.
One of the core benefits of MVC is that it allows you to test your controller (which contains a lot of logic) without instantiating a real view. You simply can't do this in the .aspx world.
Testing the controller all by itself is much faster than having to instantiate an entire asp.net pipeline (application, request, response, view state, session state etc).
-17947245 0It's all explained in the documentation of JsonDataAccess. You'll have to do something like this:
// Create a data model with sorting keys for title GroupDataModel *model = new GroupDataModel(QStringList() << "title"); // Load the JSON data JsonDataAccess jda; QVariant list = jda.load("yourfile.json")["result"].toVariantList(); // Add the data to the model model->insertList(list.value<QVariantList>()); // Add your model to a ListView listView->setDataModel(model);
-28848097 0 Yes, x is not initialized.
int x=0; // just initialize it
-18930830 0 load() function loads only the html part of the file. So if you want datas from database just echo it
-16157624 0Does this solve your task?
@echo off for /f "delims=" %%a in (file_list.txt) do ( >>run.txt echo open %%a and save as pdf )
-26425531 0 Okay so, I had a similar problem where I needed two buttons centered at the top of the page. Due to the problem I just dropped it to one button (it was easier that way). Since I'm having the same problem now with three buttons, I can't drop them to one, so I reverted back to the two original buttons that caused me a problem and came up with this...
<div class="row start-btns"> <div class="col-lg-6 col-lg-offset-3 test"> <div class="row"> <div class="col-lg-5 pull-left start-btn">Get Started</div> <div class="col-lg-5 pull-right tour-btn">Tour The Site</div> </div> </div> </div> <!-- End .row .start-btns --> @mixin btns { background: $yellow; color: $cream; font-weight: 700; font-size: 1.3em; text-transform: uppercase; text-align: center; padding: 12px 0px; } .call-btn, .start-btn, .tour-btn { @include btns; } .start-btn { margin-right: 1em; } Having the parent ".test" span 6 cols and centered allowed me to nest another row with two buttons spanning 5 cols (actually 3 due to nesting) and pull one left and other right. This gives the effect that both buttons are spanning 3 columns and centered perfectly with a 10px spacing.
-32592653 0Nesting listviews is not support in Xamarin.Forms. You can try, but the inner one will not be scrollable and therefor useless.
If ListA has a list of ListB's, would it suite your needs to do grouping? 
Essentially, you are grouping your lists of B within items of A (where in that image I showed your list A is a list of mobile devices and your lists of B are specific types within the generic OS).
To do this, when you create your listview and set your data template/source, you must now also set IsGroupingEnabled to true and GroupHeaderTemplate to the datatemplate created to show how it will be displayed visually (exactly the same as you normally would make a datatemplate with custom viewcells).
The only difference now is instead of your source being a list of A or a list of B, it is an list A (which extends ObservableCollection) which contains a list B.
You basically need to make your A viewmodel extend ObserableCollection so A is A but A is also a list/can be used as a list.
Now you just feed your list A (where each A has a list B) as the source of your ListView.
-3881137 0 Class instance variables inside of class cause compiler errorsThe compiler is giving me the following complaints about the following class:
class AguiWidgetBase { //variables AguiColor tintColor; AguiColor fontColor; //private methods void zeroMemory(); virtual void onPaint(); virtual void onTintColorChanged(AguiColor color); void (*onPaintCallback)(AguiRectangle clientRect); void (*onTintColorChangedCallback)(); public: AguiWidgetBase(void); ~AguiWidgetBase(void); void paint(); void setTintColor(AguiColor color); AguiColor getBackColor(); }; Warning 13 warning C4183: 'getBackColor': missing return type; assumed to be a member function returning 'int' c:\users\josh\documents\visual studio 2008\projects\agui\alleg_5\agui\AguiWidgetBase.h 26 Error 2 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\users\josh\documents\visual studio 2008\projects\agui\alleg_5\agui\AguiWidgetBase.h 11 Error 3 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\users\josh\documents\visual studio 2008\projects\agui\alleg_5\agui\AguiWidgetBase.h 11 Error 5 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\users\josh\documents\visual studio 2008\projects\agui\alleg_5\agui\AguiWidgetBase.h 12 Error 6 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\users\josh\documents\visual studio 2008\projects\agui\alleg_5\agui\AguiWidgetBase.h 12 Error 11 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\users\josh\documents\visual studio 2008\projects\agui\alleg_5\agui\AguiWidgetBase.h 26 Error 12 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\users\josh\documents\visual studio 2008\projects\agui\alleg_5\agui\AguiWidgetBase.h 26 Error 1 error C2146: syntax error : missing ';' before identifier 'tintColor' c:\users\josh\documents\visual studio 2008\projects\agui\alleg_5\agui\AguiWidgetBase.h 11 Error 10 error C2146: syntax error : missing ';' before identifier 'getBackColor' c:\users\josh\documents\visual studio 2008\projects\agui\alleg_5\agui\AguiWidgetBase.h 26 Error 4 error C2146: syntax error : missing ';' before identifier 'fontColor' c:\users\josh\documents\visual studio 2008\projects\agui\alleg_5\agui\AguiWidgetBase.h 12 Error 8 error C2061: syntax error : identifier 'AguiRectangle' c:\users\josh\documents\visual studio 2008\projects\agui\alleg_5\agui\AguiWidgetBase.h 17 Error 7 error C2061: syntax error : identifier 'AguiColor' c:\users\josh\documents\visual studio 2008\projects\agui\alleg_5\agui\AguiWidgetBase.h 16 Error 9 error C2061: syntax error : identifier 'AguiColor' c:\users\josh\documents\visual studio 2008\projects\agui\alleg_5\agui\AguiWidgetBase.h 25 This should be working, I'm including the headers for those classes.
This is the h file:
//integer Point class class AguiPoint { int x; int y; public: int getX(); int getY(); void setX(int x); void setY(int y); void set(int x, int y); AguiPoint(int x, int y); AguiPoint(); std::string toString(); std::string xToString(); std::string yToString(); }; //floating version of Agui Point class AguiPointf { float x; float y; public: float getX(); float getY(); void setX(float x); void setY(float y); void set(float x, float y); AguiPointf(float x, float y); AguiPointf(AguiPoint p); AguiPointf(); std::string toString(); std::string xToString(); std::string yToString(); }; //Integer rectangle class class AguiRectangle { int x; int y; int width; int height; public: bool isEmpty(); int getTop(); int getLeft(); int getBottom(); int getRight(); AguiPoint getTopLeft(); AguiPoint getBottomRight(); }; class AguiColor { unsigned char r; unsigned char g; unsigned char b; unsigned char a; void verifyColorBounds(); public: AguiColor(int r, int g, int b, int a); AguiColor(float r, float g, float b, float a); AguiColor(); int getR(); int getG(); int getB(); int getA(); }; Thanks
I include the main header in the WidgetBase and the main header includes the base types before it includes the widgetbase
-17181978 0Without using a local variable, in most invocations we have effectively
if(field!=null) // true return field; so there are two volatile reads, which is slower than one volatile read.
Actually JVM can merge the two volatile reads into one volatile read and still conform to JMM. But we expect JVM to perform a good faith volatile read every time it's told to, not to be a smartass and try to optimize away any volatile read. Consider this code
volatile boolean ready; do{}while(!ready); // busy wait we expect JVM to really load the variable repeatedly.
-28418617 0 copydb - How to create index in background?I'm doing a lot of stuff with big databases in MongoDB and sometimes there's a need in making a copy of database where copydb command fits perfectly, however it does add global lock for whole mongod instance at the end of process for creating index.
I know that there's an argument to create index in background "background:true", but I didn't find such argument for copydb command (or copydatabase).
Is there way to avoid global lock and force background index creation for Copy Database?
-22603170 0 How to add an event handler for dynamically created QML elements?I dynamically added some qml components to my gui according to this blog post. How can I add event handlers for those newly created components?
-163599 0 How to sell the benefits of "good code" to management?I work for a very small company (~70 total w/ 10 actual programmers) with a relatively large (1M LOC in C++) application that is in need of some serious TLC. Because of the size of the company we are driven primarily by what we can sell to customers with literally no time given for maintenance of the code other than fixing the bugs that cause things to fail, and not always fixing them well. Apparently this is how the company has worked for the past 10 years!
How do I convince management that what they are doing is actually costing them money/time/productivity? What kinds of active maintenance strategies exist? Which are good for small companies with scarce resources?
-16730331 0There is no issue with the first approach. I presume you are trying to iterate over few DataTimerPicker controls. If so, can you check the Name property of each DataTimerPicker control instances. I suppose it should be, datetimeBi1,datetimeBi2,datetimeBi3 ( just guessing after seeing your code).
Meantime, you can also check the immediate parent of your child controls ( DateTimePicker).
-29159976 0I would recommend posting to the Register method and based on the value of the selected option, redirect to the relevant view to complete the details. The users table could have a (say) IsRegistrationComplete field which is marked as true only when the 2nd form has been saved.
To do this in one view, you will need a view model with properties for the Register model, Owner model, ServiceCompany model and selected option.
View model
public class RegistrationVM { public RegisterVM Register { get; set; } public OwnerVM Owner { get; set; } public ServiceCompanyVM ServiceCompany { get; set; } [Required] public string CompanyType { get; set; } } Controller
public ActionResult Register() { RegistrationVM model = new RegistrationVM(); model.Register = new RegisterVM(); return View(model); } public ActionResult Register(RegistrationVM model) { // Either Owner or ServiceCompany properties will be populated } public PartialViewResult CreateOwner() { var model = new RegistrationVM(); model.Owner = new OwnerVM(); return PartialView(model); } public PartialViewResult CreateServiceCompany() { var model = new RegistrationVM(); model.ServiceCompany = new ServiceCompany(); return PartialView(model); } Notes: The partial views should not contain a <form> element (it will be inserted inside the <form> tag of the main view). The model in the partial views needs to be RegistrationVM so the controls are correctly prefixed and can be bound on post back (e.g. <input name="Owner.SomeProperty" ../> etc)
View
@model RegistrationVM @using(Html.BeginForm()) { <section> // render controls for the register model <section> <section> @Html.RadioButtonFor(m => m.CompanyType, "owner",new { id = "owner" }) <label for="owner">Owner</label> @Html.RadioButtonFor(m => m.CompanyType, "service",new { id = "service" }) <label for="service">Service Company</label> @Html.ValidationMessageFor(m => m.CompanyType) <button id="next" type="button">Next</button> <section> <section id="step2"></section> <input id="submit" type="submit" /> // style this as hidden } Then add a script to handle the Next button which validates the existing controls, gets the value of the selected service, uses ajax to load the relevant form, re-parses the validator and displays the submit button
var form = $('form'); $('#next').click(function() { // Validate what been entered so far form.validate(); if (!form.valid()) { return; // correct errors before proceeding } // Get selected type and update DOM var type = $('input[name="CompanyType"]:checked').val(); if (type == "owner") { $('#step2').load('@Url.Action("CreateOwner")'); } else { $('#step2').load('@Url.Action("CreateServiceCompany")'); } // Re-parse validator so client side validation can be applied to the new controls form.data('validator', null); $.validator.unobtrusive.parse(form); // Show submit button $('#submit').show(); });
-2917207 0 In your view code for the 'new' action use FormHelper tags that reference the same model as your create action eg.
<%= text_field :user, :login %> Then in your create action, use a model instance with the same name:
@user = User.new # detect error, redirect to 'new' The FormHelper will use the value of this instance if it is available.
-33858634 0The enctype should be on the <form> element
<form method="POST" enctype="multipart/form-data"> <input type="file" name="uploaded" style="margin-bottom: 10px"> </form> PHP:
<?php echo $_FILES['uploaded']['type'] ?>
-4326159 0 in your solution consider changing
<Trigger Property="MenuItem.Header" Value="enums:AnEnum.ItemA" > to
<Trigger Property="MenuItem.Header" Value="{x:Static enums:AnEnum.ItemA}" > in your example you check that header is equal to sting "enums:AnEnum.ItemA" not to enum AnEnum member ItemA.
-21438253 0VT-x inside VT-x cannot be done in VirtualBox.
A (quite old) feature request about this functionality is here:
https://www.virtualbox.org/ticket/4032
-11280343 0 How to plot family tree in RI've been searching around how to plot a family tree but couldn't find something i could reproduce. I've been looking in Hadley's book about ggplot but the same thing.
I want to plot a family tree having as a source a dataframe similar to this:
dput(head(familyTree)) structure( list( id = 1:6, cnp = c("11", NA, "22", NA, NA, "33"), last_name = c("B", "B", "B", NA, NA, "M"), last_name_alyas = c(NA, NA, NA, NA, NA, "M"), middle_name = c("C", NA, NA, NA, NA, NA), first_name = c("Me", "P", "A", NA, NA, "S"), first_name_alyas = c(NA, NA, NA, NA, NA, "F"), maiden_name = c(NA, NA, "M", NA, NA, NA), id_father = c(2L, 4L, 6L, NA, NA, 8L), id_mother = c(3L, 5L, 7L, NA, NA, 9L), birth_date = c("1986-01-01", "1963-01-01", "1964-01-01", NA, NA, "1936-01-01"), birth_place = c("City", "Village", "Village", NA, NA, "Village"), death_date = c("0000-00-00", NA, NA, NA, NA, "2007-12-23"), death_reason = c(NA, NA, NA, NA, NA, "stroke"), nr_brothers = c(NA, 1L, NA, NA, NA, NA), brothers_names = c(NA, "M", NA, NA, NA, NA), nr_sisters = c(1L, NA, 1L, NA, NA, 2L), sisters_names = c("A", NA, "E", NA, NA, NA), school = c(NA, "", "", NA, NA, ""), occupation = c(NA, "", "", NA, NA, ""), diseases = c(NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_), comments = c(NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_) ), .Names = c("id", "cnp", "last_name", "last_name_alyas", "middle_name", "first_name", "first_name_alyas", "maiden_name", "id_father", "id_mother", "birth_date", "birth_place", "death_date", "death_reason", "nr_brothers", "brothers_names", "nr_sisters", "sisters_names", "school", "occupation", "diseases", "comments"), row.names = c(NA, 6L), class = "data.frame" ) Is there any way I can plot a family tree with ggplot? If not, how can i plot it using another package.
The primary key is 'id' and you connect to other members of the family using "id_father" and "id_mother".
-32105327 0Right answer would be declaring a common base class or interface but you said "I tried polymorphism, but". I do not know what (or how) did you try but assuming,
ToModel() methodYou can do
var type = _projectService.GetTaskTypeById(id); dynamic task; switch (type) { case "MS": task = _projectService.GetMSTaskById(id); break; case "TL": task = _projectService.GetTLTaskById(id); break; case "ET": task = _projectService.GetETTaskById(id); break; default: throw new NotSupportedException("Unsupported Task Type: " + type); } task.ToModel();
-40873634 0 Your code creates the Breakout object and sets its visibility:
Breakout bo = new Breakout(); bo.setVisible(true); However, you never invoke any other methods. For example you may want to invoke a run method or a main method. You have to call those methods somehow in order to execute the code.
Another option would be to add a listener to the Breakout class so that it executes your code when the window opens, something like this:
addWindowListener(new java.awt.event.WindowAdapter() { public void windowOpened(java.awt.event.WindowEvent evt) { //call a method that runs the program here! } });
-22859808 0 Cross and sub domain tracking with Google Analytics Universal Tag This is my first question on Stackoverflow. So apologies if I make a mistake...
The challenge: I have a website (main.com), a sub-domain (sub.main.com) and 10 websites that send traffic, back and forth, to the main site and the sub domain. Let's call these sites site01.com, site02.com, site03.com,...,site10.com.
My question: How do I implement Universal Tag so I can do cross-domain tracking between main.com, sub.main.com and site01.com, site02.com, site03.com,...,site10.com.
I found instructions on how to do cross domain tracking for two sites. For example, on the main domain I will add the following code:
**<!-- Universal Analytics --> <script type="text/javascript"> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-XXXXXXXXX-X', 'main.com', {'allowLinker': true}); ga('require', 'linker'); ga('linker:autoLink', ['site01.com']); ga('send', 'pageview'); </script>** And on site01.com, I will add the code below:
**<!-- Universal Analytics --> <script type="text/javascript"> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-XXXXXXXX-X', 'site01.com',{'allowLinker': true}); ga('send', 'pageview'); </script>** I don't know how to modify the code to include all 10 sites (site01.com, site02.com, site03.com,...,site10.com as part of the cross domain tracking.
Also, in relation to sub-domain tracking, I am guessing that the above code will also capture data from the sub-domain site (sub.main.com) with no issues.
Any help will be greatly appreciated.
Stratos.
-32733242 0 iOS 8/9 CalendarEvent predicateForEventsWithStartDate EndDate not working correctly?Is it possible that the function: predicateForEventsWithStartDate(startDate: NSDate, endDate: NSDate, calendars:[EKCalendar]) is not working as described in the documentation!? The enddate seems to work as expected, taking into account the day and the time of the date. But when retrieving the events for the predicate, events being on the startdate X (and later than the time of the start date) are never fetched. As soon as I set the startdate to 23:59 the previous day of X, all events of day X are fetched as expected.
Has anybody experienced this behaviour? Or is the documentation not correct and this is the expected behavoir?
Note: Tried on Iphone 6(iOS8) / Ipad mini 3(iOS8) / iPhone 5 (iOS 9)
EDIT: here is the documentiation of the method:
func predicateForEventsWithStartDate(_ startDate: NSDate, endDate endDate: NSDate, calendars calendars: [EKCalendar]?) -> NSPredicate Creates and returns a predicate for finding events in the event store that fall within a given date range.
startDate
The start date of the range of events fetched.
endDate The end date of the range of events fetched.
calendars
The calendars to search, as an array of EKCalendar objects. Passing nil indicates to search all calendars.
var happyMood = document.getElementById("happy"); var sadMood = document.getElementById("sad"); happyMood.onclick = function () { var mainHeading = document.getElementById("heading"); mainHeading.innerHTML = "You have selected "; }; sadMood.onclick = function () { var mainHeading = document.getElementById("heading"); mainHeading.innerHTML = "You have selected " + sadMood; };
-11498591 0 Dis-allow installation on specific API Level How to dis-allow my app to run on a specific API level? i know about the 3 specifiers in uses-sdk tag in the manifest. But that can't produce a logic i want to implement.
For eg: i want to allow my application to be installed on Level 4 to Level 10, dis-allow for Level 11 to Level 13 and again allow for Level 14 and Level 15.
Is that possible?
-10684079 0 Outputting relevant input/output to a GUI, having received input in the consoleI need to display some relevant information (like an introduction, yes/no questions and other questions) to a user via a gui, who then enters their response into the console. However, I cannot for the life of me think of or find a way to do this. How can I run the GUI but still allow input into the console? Here is some cut down code I have that shows what I'm trying to do. I'm doing this from a pps frame class that handles the container stuff. I just need to add buttons, text fields and later on action events.
public class gui extends XFrame { private JTextField[] textFieldsUneditable; public gui() { super(); textFieldsUneditable = new JTextField[10]; for(int i=0; i<textFieldsUneditable.length; i++) { textFieldsUneditable[i] = new JTextField(42); textFieldsUneditable[i].setEditable(false); add(textFieldsUneditable[i]); } revalidate(); repaint(); } public void paintComponent(Graphics g) { super.paintComponent(g); // code code code } But what I have is other methods, of which I want to run and then output into these uneditable JTextFields using setText in the GUI after the user has responded in the console. I hope that makes sense!
-11884355 0 Processor serial numberI need PSN of CPU. I write code like
int info[4] = { -1 }; __cpuid(info, 1); int family = info[0] & 0xf00; int features = info[3] & 0xf000; std::stringstream psn_id; How i get Processor serial number? Can anyone please help me. Thank you.
-923865 0It's definitely not the idea of MVC (or whatever you're doing) to render HTML in the Controller. HTML has to be handled in the view. What if you want to provide an alternative UI (e.g. Windows Application)? HTML does not really fit into an WinApp.
-21388154 0Merge plays and pauses as a property and filter the interval stream with it.
var pauses = $('.pause').asEventStream('click').map(false); var plays = $('.plays').asEventStream('click').map(true); var isTicking = pauses.merge(plays).toProperty(true); var ticks = Bacon.interval(500).filter(isTicking);
-23039487 0 You can't do that unless the subroutine is a built-in Perl operator, like sqrt for instance, when you could write
perl -e "print sqrt(2)" or if it is provided by an installed module, say List::Util, like this
perl -MList::Util=shuffle -e "print shuffle 'A' .. 'Z'"
-10749299 0 this is that iPhone camera rotates the image comparing with home button. it uses EXIF that is meta data of image. see this thread.
-14997937 0Include and require are identical, except upon failure: require will produce a fatal error (E_COMPILE_ERROR) and stop the script include will only produce a warning (E_WARNING) and the script will continue You can understand with examle include("test.php"); echo "\nThis line will be print";
Output :Warning: include(test.php): failed to open stream: No such file or directory in /var/www/........ This line will be print
require("test.php"); echo "\nThis line will be print"; Warning: require(test.php): failed to open stream: No such file or directory in /var/www/....
-28318371 0#pragma pack for correctnessProperties-> C/C+1-> Code Generation -> Struct Member Alignment. If you use another tool find how options are provided to the compiler and pass /Zp1(or -Zp1).There will be multiple functions used by boost which would require a specific byte alignment. These function may be from the boost framework itself or from microsoft libraries. The classic case will be atomic operations (ie like InterlockedIncrement ) which requires a minimum byte alignment.
If there is a structure
struct { char c; int a; volatile int b; } and b is used as atomic operand, The structure members alignment have to be guaranteed using #pragma pack. So boost use explicit #pragma pack for correctness.
I am following the ruby.railstutorial. I run the command "git push heroku master" and it spits out this error.
Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. I am inside my rails app "/Users/lexi87/rails_projects/first_app". Any solutions?
-32927225 0 Auth does not work on app engineI'm trying to use the given authentication methods for app engine:
handlers: - url: /static static_dir: src/static - url: /admin/.* script: src.app login: admin - url: /client/.* script: src.app login: required - url: /.* script: src.app login: optional But the authentication does not work when I navigate to /client or /admin
Your class variable cannot be private if you would like your child class to access it. Try protected instead and it should work!
-2563348 0Pretty much you want two different images of a star. One image is the plain white star and the other is the yellow (or whatever color) star that indicates it has been favorited. On the click event of the image, you just check which image is the src and then change it accordingly to match the necessary status of favorited or not. Then you run an ajax call to actually save the status to the database.
Changing your code to this:
$(document).ready(function(){ var rightHeight = $('.rightcolumn').height(); var leftHeight = $('.leftcolumn').height(); if(leftHeight < rightHeight) { $('.leftcolumn').height(rightHeight); } }); Seems to do the trick for safari. See this fiddle
-14710042 0 IE img load returns errorI am trying to insert an image from an ajax repsonse. Everything work, but not in IE.
I have tried: Image load not working with IE 8 or lower, but get "broken image".
Tried to solve it described here: http://www.paulund.co.uk/handle-image-loading-errors-with-jquery, but it does not solve anything. I did not attach it to the document.ready function though, since this is ajax, the IE < 9 hack will never be triggered by the ajax call. the Ajax call is triggered by a mouse click which repsonds with an image link. When using JQuery's dialog function, IE does not show the image. Forcing it by right-clicking and 'Show image' shows the image.
Anybody know how to solve this problem?
function search(url){ $.ajax({ type: "GET", url: url, dataType: "html", success: function(data, status, XMLHttpResponse){ clickListenerEvent(); }, error: function(data, textStatus, XMLHttpResponse){ alert("AJAX error"); } }); } function clickListenerEvent(){ $('a.show-image').click(function (e) { var element = $(this); var href = element.attr('href'); var title = element.attr('title'); var thisId = 'dialogbox_'; var exisitingDialog = $('.dialogbox[id='+thisId+']'); if(!exisitingDialog.length){ element.parent().append("<div id='"+thisId+"'></div>"); } var thisDialog = $('.dialogbox[id='+thisId+']'); var img = new Image(); $(img).load(function() { alert('successfully loaded'); }).error(function() { alert('broken image!'); //$(this).attr('src', href); }).attr('src', href); $(thisDialog).append(img); //create the dialog $('.dialogboks[id='+thisId+']').dialog({ closeText: 'Close', title: title }); if ( $.browser.msie && $.browser.version < 9 ) { $('img').each(function(){ $(this).attr('src', $(this).attr('src')); }); } e.preventDefault(); }); }
-32398155 0 PHP Sessions and Cookies set up I want to learn something, that I couldn't find on the internet. I create a simple website, more like a simple web app, we the following structure.
index.php --> handles log In or Register home.php --> main state of website. So basically I want when a user log in, the website will direct him to home.php. I did it already. But I get a really annoying bug. If I redirect bruteforce in www.someexample.com/home.php, the user can bypass the main log in screen. O.o
So I thought that if I can use a session checker to see if the user is log in or just a brute forcer -sorry about the bad term- the website will redirect him to log in screen. And if the user don't want every time to log in he can check a Remember me button to remember the session. So in the end I want to have two methods. one to check if a user is log in or not and the other to save his session even after if he close the computer until he poush the log out button.
I have checked many articles on the web but I couldn't find how to start in my own project. Can you guys help me start of with a basic structure. i use MySql.
-26214919 0Design a UI and ask the user to supply the "email incoming/outgoing server settings", which you then store in a file, database, or SharedPreferences as appropriate.
I'm using the SearchView widget in ActionbarSherlock as a follows:
File.java
public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getSupportMenuInflater(); inflater.inflate(R.menu.main, menu); SearchManager searchManager = (SearchManager)getSystemService(Context.SEARCH_SERVICE); SearchView searchView = (SearchView) menu.findItem(R.id.MenuSearch).getActionView(); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setIconifiedByDefault(true); searchView.setSubmitButtonEnabled(true); return true; } File.xml
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/MenuSearch" android:title="@string/Bs" android:icon="@drawable/ic_action_search" android:showAsAction="always|withText" android:actionViewClass="com.actionbarsherlock.widget.SearchView" > </item> </menu> In my application I get to show the search icon and select it unfolds the search box for the widget, but when I write any search I do not know how to interact with the widget SearchView to launch a new activity and show a series of results.
With the command searchView.setSubmitButtonEnabled(true); appears a icon similar to 'play' and I suppose it is for just that, but I do not know how to interact with it.
Can anyone help?
-12808179 0 Geocode results based on current locationIn one of my activities i need to be able to do a geocoding (find a location by address String search). The problem is that my results are much too broad. When i search for "mcdonalds" i get results that are in different parts of the USA. How can i make it so a user can search for nearby restaurants (or any location) and the results will be within a certain distance? I basically need more precise results for my application. Here is a screenshot of whats happening: 
public class MainActivity extends MapActivity { HelloItemizedOverlay itemizedOverlay; List<Overlay> mapOverlays; Drawable drawable; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MapView myMap = (MapView) findViewById(R.id.mapview); myMap.setBuiltInZoomControls(true); MapController mc = myMap.getController(); mapOverlays = myMap.getOverlays(); drawable = this.getResources().getDrawable(R.drawable.androidmarker); itemizedOverlay = new HelloItemizedOverlay(drawable, this); //geopoints are cordinates in microdegrees or degrees * E6 GeoPoint point = new GeoPoint(34730300, -86586100); //GeoPoint point2 = locatePlace("texas", mc); //HelloItemizedOverlay.locatePlace("Texas", mc, myMap); //overlayitems are items that show the point of location to the user OverlayItem overlayitem = new OverlayItem(point, "Hola, Mundo!", "im in huntsville"); //OverlayItem overlayitem2 = new OverlayItem(point2, "Texas", "hi"); //itemizedoverlay is used here to add a drawable to each of the points itemizedOverlay.addOverlay(overlayitem); //itemizedOverlay.addOverlay(overlayitem2); //this adds the drawable to the map //this method converts the search address to locations on the map and then finds however many you wish to see. locatePlace("mcdonalds", mc, 5); mapOverlays.add(itemizedOverlay); //this animates to the point desired (i plan on having "point" = current location of the user) mc.animateTo(point); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } @Override protected boolean isRouteDisplayed(){ return false; } public void locatePlace(String locName, MapController mc, int numberToDisplay) { // code to make the google search via string work // i use the Geocoder class is used to handle geocoding and reverse-geocoding. So make an instance of this class to work with the methods included Geocoder geoCoder1 = new Geocoder(this, Locale.getDefault()); try { List<Address> searchAddresses = geoCoder1.getFromLocationName(locName, numberToDisplay); // gets a max of 5 locations if (searchAddresses.size() > 0) { //iterate through using an iterator loop (for loop would have been fine too) //Iterator<Address> iterator1 = searchAddresses.iterator(); for (int i=0; i < searchAddresses.size(); i++){ //while (iterator1.hasNext()){ //step1 get a geopoint GeoPoint tempGeoP = new GeoPoint( (int) (searchAddresses.get(i).getLatitude()*1E6), (int) (searchAddresses.get(i).getLongitude()*1E6) ); //step2 add the geopoint to the Overlay item OverlayItem tempOverlayItm = new OverlayItem(tempGeoP, locName, "this is " + locName); //step3 add the overlay item to the itemized overlay HelloItemizedOverlay tempItemizedOverlay = new HelloItemizedOverlay(drawable, this); // its breakking here......... tempItemizedOverlay.addOverlay(tempOverlayItm); //the itemized overlay is added to the map Overlay mapOverlays.add(tempItemizedOverlay); } } } catch (IOException e) { e.printStackTrace(); // Log.e("the error", "something went wrong: "+ e); }//finally {} } } // here is the important code from the Itemized overlay class
public HelloItemizedOverlay(Drawable defaultMarker, Context context) { super(boundCenter(defaultMarker)); myContext = context; } public void addOverlay(OverlayItem overlay){ mOverlays.add(overlay); populate(); } Thanks, Adam
Here is some code after adjusting to Vishwa's comments:
// these 2 variables are my current location latitudeCurrent = 34730300; // make this dynamic later longitudeCurrent = -86586100; // make this dynamic later LLlatitude = (latitudeCurrent - 100000)/(1E6); //lowerleft latitude = original lat - (1)*degree/10 LLlongitude = (longitudeCurrent+ 100000)/(1E6);//lowerleft longitude = original longitude - (1)*degree/10 URlatitude = (latitudeCurrent + 100000)/(1E6); //upperright latitude = original + (1)*degree/10 URlongitude = (longitudeCurrent+ 100000)/(1E6); //upperright longitude = original longitude + (1)*degree/10 try { List<Address> searchAddresses = geoCoder1.getFromLocationName(locName, numberToDisplay, LLlatitude, LLlongitude, URlatitude, URlongitude); 
Probably a very poorly named title, but anyway...
I am using the command pattern on a hierarchical data set. So basically I need a method that returns an object that describes the changes that will be made without actually changing the data. So for example:
Object 1 -> Object 2 -> Object 3
If I move object 1, it will cause a change in Object 2, which will cause a change in Object 3 because they depend on each other. So...I need a method to recursively go through the hierarchical collection and gather up the changes that are required to move Object 1 without actually modifying the collection. Halfway through the recursion it would be nice to be able to use something like Object1.Location, but it may already slated for change so I can't reliably use it.
I feel like there are plenty of algorithms and such that need to do this type of "in place" modification. As a non-CS major I didn't learn much of this type of thing, so I don't really even know what search terms to look for to find a "solution". I put solution in quotes because I realize there probably isn't a direct solution for my problem, but I am merely looking for some good guidelines/examples of this being done to get my brain cranking.
Can anyone provide some real-world examples of this type of thing being done? Thanks in advance.
-16286775 0 A simple subtraction practiceI want to make a little game for my son to practice subtraction ( since he won't get off the computer !! ) . i have tried this code but my problem is that i want the first number to be always higher than the second number (cause that's wht they know so far ) ..this is my code :
<?PHP $string = "1234567890"; $shuffled = str_shuffle($string); $shuffled2 = str_shuffle($string); $num1 = substr($shuffled, 0, 3); $num2=substr($shuffled2, 0, 3); if ($num2 > $num1) { some code here .. } else { echo "$num1<BR>"; echo "$num2<BR>"; $res= $num1-$num2; echo "$res<BR>"; } ?> so what is the missing code here ..i was thinking (goto) back from my days of basic to run code from the beginning until condition if satisfied ..but i don't know if that works in PHP .. Or ...is there a way to put a condition on shuffle in the first place so it can always return the first number higher than the second number?
-34760649 1 How to use whoosh for searching keywordsArticle Schema:
Below is the article schema what I have created.
class ArticleSchema(SchemaClass): title = TEXT( phrase=True, sortable=True, stored=True, field_boost=2.0, spelling=True, analyzer=StemmingAnalyzer()) keywords = KEYWORD( commas=True, field_boost=1.5, lowercase=True) authors = KEYWORD(stored=True, commas=True, lowercase=True) content = TEXT(spelling=True, analyzer=StemmingAnalyzer()) summary = TEXT(spelling=True, analyzer=StemmingAnalyzer()) published_time = DATETIME(stored=True, sortable=True) permalink = STORED thumbnail = STORED article_id = ID(unique=True, stored=True) topic = TEXT(spelling=True, stored=True) series_id = STORED tags = KEYWORD(commas=True, lowercase=True) Search Query
FIELD_TIME = 'published_time' FIELD_TITLE = 'title' FIELD_PUBLISHER = 'authors' FIELD_KEYWORDS = 'keywords' FIELD_CONTENT = 'content' FIELD_TOPIC = 'topic' def search_query(search_term=None, page=1, result_len=10): '''Search the provided query.''' if not search_term or search_term == '': return None, 0 if not index.exists_in(INDEX_DIR, indexname=INDEX_NAME): return None, 0 ix = get_index() parser = qparser.MultifieldParser( [FIELD_TITLE, FIELD_PUBLISHER, FIELD_KEYWORDS, FIELD_TOPIC], ix.schema) query = parser.parse(search_term) query.normalize() search_results = [] with ix.searcher() as searcher: results = searcher.search_page( query, pagenum=page, pagelen=result_len, sortedby=[sorting_timestamp, scores], reverse=True, terms=True ) if results.scored_length() > 0: for hit in results: search_results.append(append_to(hit)) return (search_results, results.pagecount) parser = qparser.MultifieldParser( [FIELD_TITLE, FIELD_PUBLISHER, FIELD_TOPIC], ix.schema, termclass=FuzzyTerm) parser.add_plugin(qparser.FuzzyTermPlugin()) query = parser.parse(search_term) query.normalize() search_results = [] with ix.searcher() as searcher: results = searcher.search_page( query, pagenum=page, pagelen=result_len, sortedby=[sorting_timestamp, scores], reverse=True, terms=True ) if results.scored_length() > 0: for hit in results: search_results.append(append_to(hit)) return (search_results, results.pagecount) return None, 0 When I am trying the title search is working, but for author and keyword the search is not working. I am not able to understand what wrong I am doing here. I am getting data from api and then running the index. It's all working fine. But when I am searching through keywords like authors and keywords it's not working.
A workaround is to add the attribute statically in addition to the binding
<use xlink:href="" xlink:href$="[[replaceSVGPath(item)]]"></use> Polymer has issues creating the attribute, if it already exists it can update it just fine.
-5833218 1 CoreDumpDirectory isn't working on ubuntu; getting segmentation fault in apache2 error logI am not able to log the apache2 crashes in CoreDumpDirectory on ubuntu 10.10. I am using Django 1.2.3 and apache2 with mod_wsgi. I followed the steps listed in response to this question but to no avail. I added - CoreDumpDirectory /var/cache/apache2/
at the end of apache2.conf file and then after executing 'ulimit -c unlimited', restarted the apache server. Then I replicated the condition that causes apache error log to show- "child pid 27288 exit signal Segmentation fault (11)" but there is no mention of apache2 logging that crash in CoreDumpDirectory and also there is nothing in /var/cache/apache2.
EDIT:
I was able to solve this problem. The issue was with PyLucene environment being initialized on the run time. I was executing initvm() call everytime a request comes and it was causing segmentation fault. This link directed that I should do it in .wsgi file and after I did that there were no segmentation faults.
-15453912 0 Return car make by providing car model from XML file using .asmx web serviceI am writing an .asmx web service to return all car makes matching a requested model from within an XML file.
Using VB in ASP.net, can you suggest how I could:
1) first find a match to the requested make, then 2) return all models?
Below is a sample of the XML. Thanks!
<cars> <car> <carmake>Acura</carmake> <carmodels> <carmodel>ILX</carmodel> <carmodel>MDX</carmodel> <carmodel>RDX</carmodel> </carmodels> </car> <car> <carmake>Aston Martin</carmake> <carmodels> <carmodel>DB9</carmodel> <carmodel>DBS</carmodel> <carmodel>Rapide</carmodel> </carmodels> </car> </cars>
-40892415 0 Blank MySQL error on shared hosting I am doing a little bit of learning on mysql, php and the like. I'm using a shared hosting plan so am quite limited from a settings changes point of view.
I am attempting to run a simple mysql select command through PHP, but all i get back is a blank error
<?php $typeID = $_GET['tid']; //variables for the database server $server = "localhost"; $user = "codingma_rbstock"; $pwd = "M@nL%V{%RI+h"; $db = "codingma_rbstock"; //variables for the database fields $itemNo; $itemNm; $itemDesc; $buyPr; $sellPr; $quan; $dept; //database connection //create connection $conn = new mysqli($server, $user, $pwd, $db); //if the connection fails throw an error. if ($conn->connect_error){ die("Connection Failed: " . $conn->connect_error); } echo "Welcome to " . $typeID . "<br>"; $sql = "select ITEM_NAME from stock where ITEM_NO='00001'"; if ($conn->query($sql) === TRUE){ $res = $conn->query($sql); if ($res->num_rows > 0){ echo "success"; } }else{ echo "Error: " .$sql . "<br>" . $conn->error; } echo $res; ?> I have checked and it seems to be connecting to the database fine (I changed a few account details to see if that threw a different error and it did).
I am sure I am missing something completely obvious here! The below is the text output from the error;
Error: select ITEM_NAME from stock where ITEM_NO='00001'
Thanks for any help.
-28900440 0 CustomComparator sort objects errorI keep getting the error
The method sort(List<T>, Comparator<? super T>) in the type Collections is not applicable for the arguments (List<InterfaceMessage>, Folder.CustomComparator) on the code...
@Override public void sortByDate(boolean ascending) { Collections.sort(messageList, new CustomComparator()); } class CustomComparator implements Comparator<Message> { public int compare(Message message1, Message message2) { return message1.getDate().compareTo(message2.getDate()); } } I'm trying to compare the dates within each object in a list to order them by their dates. I'm new to making a comparator but I have seen many examples which I've followed but mine doesn't seem to work? I know I haven't done anything with "ascending" yet, I just want to get the basic comparator working.
Any help is appreciated, thank you :)
-10644981 0I don't think this will do you any good. AFAIK, there's no relationship between android.hardware.SensorEvent and com.sun.j3d.utils.behaviors.sensor.SensorEvent.
From a brief look at the Android source code, it looks like there's simply no way to create your own SensorEvent object. This is a serious oversight on Google's part, if you ask me.
Edit: Here's what I do. I write a method named sensorChanged(Sensor sensor, float[] values) to do all the work, and just call it from the regular onSensorChanged() method. Then, when I want to test sensor handling from within my app, I call sensorChanged() with whatever values I want. I might not be able to create a SensorEvent object, but this way I can still test my code.
-4046546 0Be careful with the ":method" argument. It specifies an HTTP method, not the action.
-29607437 0I am assuming you have a length measure. If so, the below should work.
WITH MEMBER Measures.SumOfLengths AS SUM ( [DimDate].[Alldate].[Day].members, [Measures].[Length] ) SELECT Measures.SumOfLengths ON 0, [DimDate].[Alldate].[Day].members ON 1 FROM [YourCube]
-21656732 0 I think it's supposed to be:
Document doc = Jsoup.connect("http://en.wikipedia.org/wiki/Main_Page").get(); Elements el = doc.select("div#mp-tfa"); System.out.println(el);
-39589061 0 Many to many relationship hibernate with join on non-primary column hibernate I have 4 tables -
How can i create the pojo for last table (which is the join table) in Hibernate for this.
-308245 0First of all, inheritance in interfaces is OK, it applies in the same way as it does for class inheritance and is a very powerful tool.
Interfaces describe behavior, let's say an interface defines what a class "can do" so if you implement an interface you are declaring you can do what that interface specifies. For example:
interface ISubmergible { void Submerge(); } So is obvious, if the class implements the interface then it can submerge. Some interfaces nonetheless imply other interfaces, for example, imagine this interface
interface IRunner { void Run(); } That defines an interface that indicates that the class implementing it can run... nonetheless, in the context of our program is understood that, if something can run it can obviously walk, so you want to make sure that is fulfill:
interface IWalker { void Walk(); } interface IRunner : IWalker { void Run(); } Finally, about the whole NotImplementedException thing... I'm amazed with some of the suggestions. A NotImplementedException should never, ever, be raised by an interface method of a class. If you implement an interface your are explicitly accepting the contract that interface establishes, if you raise a NotImplementedException you are basically saying "ok, I lied, I told you I supported the interface but I really don't".
Interfaces are meant to avoid having to worry about what the class implements and what doesn't. If you take that away they are useless. Much more important, your fellows will expect such behavior, even if you understand what you're doing the rest of your team won't and even you, 6 months from now won't understand the logic beneath it. So class2 violates common sense and interface purpose. Class2 does not implement the IBase so don't claim it does.
-7938348 0 Is there a get_method() function in PHP?In one class I call $this->view() which will be handled by its extended class. But how can I get the name of the method in the parent view();
To make it somewhat clearer:
<?php class UsersController extends Controller public function signup() { $this->view(); } } class Controller { public function view() { // How can I get 'signup' so that I can include 'views/Users/signup.php' } } ?>
-9688121 0 what are Static Nested Classes in Java? I am new to java and have been scratching my head understanding some its concepts. I am following the tutorial Java tutorial. However, I cannot find the usefulness of using Static Nested Classes. I mean I think I need some good examples as to why I should want to use it. Can someone provided me some codes as examples so I can understand it better? thax
-11380835 0private ByteArrayInputStream getPhoto() { Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, id); Uri photoUri = Uri.withAppendedPath(contactUri, Contacts.Photo.CONTENT_DIRECTORY); Cursor cursor = getContentResolver().query(photoUri, new String[] {ContactsContract.CommonDataKinds.Photo.PHOTO}, null, null, null); if (cursor == null) { return null; } try { if (cursor.moveToFirst()) { byte[] data = cursor.getBlob(0); if (data != null) { return new ByteArrayInputStream(data); } } } finally { cursor.close(); } return null; } This is my code. It is working.
-26682699 0 Use case for not declaring a function as a prototype of another custom function?I'm trying to get my head around the proper way of declaring js functions within my existing custom objects.
E.g. Usually I've done it this way to add functions to my existing object(s):
function whateverController() { this.doSomething = function() { } } What is the advantage of doing it the following way?
function whateverController() { ...some random code } whateverController.prototype.doSomething = function() { } From what I've been reading the latter example is the optimum way of declaring these functions to avoid having to recreate these functions every single a time I create a new whateverController object.
Could someone please provide a good use case though where my former example would be better suited? If at all? Any good reading links would be helpful too!
Is the latter method considered standard?
-36655963 0 Recursive functions and removeEventListenerI want to write a dynamic button creator. So I have the html file
<body> <button id="0" type="button" onclick="create_button(0)">Create button 1</button> </body> and js file which "simulates" proper action
var counter = 0; function create_button(n) { /*Shift up*/ for (i=counter; i>n; i--) { document.getElementById(i).id = i+1; document.getElementById(i+1).innerHTML = i+1; }; /*Create new button*/ var new_button = document.createElement("Button"); new_button.innerHTML = n+1; new_button.type = "button"; new_button.id = n+1; function helper() { create_button(n+1); }; new_button.addEventListener('click', helper ); document.body.insertBefore(new_button,document.getElementById(n).nextSibling); counter++; }; However /*Shift up*/ part only changes id and innerHTML of buttons not the action of click. So in order to fix that I need to add in /*Shift up*/ two lines which should work as
document.getElementById(i+1).addEventListener('click', helper(i+1) ); document.getElementById(i+1).removeEventListener('click', helper(i) ); Clearly It will not work. Due to recursive nature of create_button function, I imagine that helper should be moved outside of create_button. But I have no idea how to do it.
Some additional info I simplified the code, but in practice buttons have some addition functions which depend on n. Let say that we also want to alert the position of the button. So we change helper to
function helper() { create_button(n+1); alert(n+1); }; See in https://jsfiddle.net/o3Lsttyq/3/ what alerts say. Click for example 1,1,3.
-11025128 0 pl/sql Compare with previous rowThe goal is to combine Time_a within 10 min interval that has same ID. And group the ID.
ID Time_a -> ID ------------ ---------- 1 12:10:00 1 1 12:15:00 2 1 12:20:00 2 2 12:25:00 2 12:35:00 2 02:00:00 It became two '2' because time interval between row5 and row6 is more than 10 min. I was able to combine within 10-min difference, but it doesn't distinguish ID.
select ID from( select id, Time_a, min(time) OVER (order by id, time rows between 1 preceding and 1 preceding) prev_t_stamp from dual ) where abs(Time_a-prev_t_stamp)>10/1440
-16710054 0 I faced this issue couple of days before.
Right click your project, Go to properties->Java Build path->Order and Export
Check Android Private Library->Click Ok
Clean the project and run it.it will work.
-20855339 0For the benefit of those of you who land up here in search of a working implementation. The following code works for every search criteria no matter how complex. I am using Codeigniter, just for the record.
if($this->input->get('_search')=="true"){ $where = ""; $ops = array( 'eq'=>'=', 'ne'=>'<>', 'lt'=>'<', 'le'=>'<=', 'gt'=>'>', 'ge'=>'>=', 'bw'=>'LIKE', 'bn'=>'NOT LIKE', 'in'=>'LIKE', 'ni'=>'NOT LIKE', 'ew'=>'LIKE', 'en'=>'NOT LIKE', 'cn'=>'LIKE', 'nc'=>'NOT LIKE' ); $filters = json_decode($this->input->get('filters'), true); $first = true; foreach ( $filters['rules'] as $item){ $where .= $first ? " WHERE" : " AND "; $searchString = $item['data']; if($item['op'] == 'eq' ) $searchString = "'".$searchString."'"; if($item['op'] == 'bw' || $item['op'] == 'bn') $searchString = "'".$searchString."%'"; if($item['op'] == 'ew' || $item['op'] == 'en' ) $searchString = "'%".$searchString."'"; if($item['op'] == 'cn' || $item['op'] == 'nc' || $item['op'] == 'in' || $item['op'] == 'ni') $searchString = "'%".$searchString."%'"; $where .= " ".$item['field']." ".$ops[$item['op']]." ".$searchString; if ($first) { $first = false; } } $sql = "SELECT * FROM applicant".$where; $query = $this->db->query($sql); $result = $query->result_array(); $i=0; foreach ($result as $myrow){ $responce->rows[$i]['id']=$myrow['id']; $responce->rows[$i]['cell']=array($myrow['id'],$myrow['contingent_id'],$myrow['firstname'],$myrow['lastname'],$myrow['age'],$myrow['grouptype_id'],$myrow['registrationtype_id']); $i++; } }
-8760264 0 You can use .one() for that.
$("a").one("click", function() { // do your stuff } Or you could store the fact that the link has already been clicked by adding a .data() attribute.
$('a').click(function() { var a = $(this); if (a.data('clicked') == 'clicked') return false; // do your stuff a.data('clicked', 'clicked'); }); Whatever you do you should really drop that inline js (for maintainability and clean code).
-5869224 0 Serialize large files - store in memory or on disk?I do a networking app using iPhones and their limited memory is something I must consider. My Message class holds both a image and a video. Now I am about to implement the video file transfer (image already implemented, and is working). I guess the image can be loaded to memory because of their relatively small size (1+ MB), but large video files must reside on disk to avoid filling the memory.
To be able to encode the Message instance for sending it over the network (using NSCoding protocol), I convert the UIImage instance to NSData that resides in memory:
NSData *imageData = UIImagePNGRepresentation(self.image); The video is stored on disk and is accessed by using an NSURL videoURL. The content of this url (the video file itself) should also be encoded, and it have to be converted to NSData as well. If I init an NSData instance with this url, the videoData will be loaded into and occupying all available space in memory...
NSData *videoData = [[NSData alloc] initWithContentsOfURL:videoURL]; ...(am I wrong?) so this must be accomplished using another technique.
Should I send the Message instance (without the video) first, and then send the video separately using some unknown technique? Or maybe I did miss some conceptual steps here?
To change date-time format take a look at this http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/263d73b2-8611-4398-9f09-9aa76bbf325e/
You basically need to use native Win API method SetLocaleInfo.
I cant really be specific about your template structure (template-part content-title??) but using a generic example the following will display the featured image where available;
functions.php
if ( ! function_exists( 'mytheme_setup' ) ) : function mytheme_setup() { /* * Enable support for Post Thumbnails on posts and pages. * * See: https://codex.wordpress.org/Function_Reference/add_theme_support#Post_Thumbnails */ add_theme_support( 'post-thumbnails' ); set_post_thumbnail_size( 825, 510, true ); } endif; add_action( 'after_setup_theme', 'mytheme_setup' ); your content template page (content.php, template-page, etc..)
// WP_Query arguments $args = array ( 'nopaging' => false, 'posts_per_page' => '2', 'offset' => '1', ); // The Query $the_query = new WP_Query( $args ); // The Loop if ( $the_query->have_posts() ) { while ( $the_query->have_posts() ) { $the_query->the_post(); ?> <article> <?php if ( has_post_thumbnail() ) : ?> <div class="post-thumbnail"> <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"> <?php the_post_thumbnail(); ?> </a> </div> <?php endif; ?> <div class="post-title"> <?php echo '<h2>' . get_the_title() . '</h2>'; ?> </div> </article> <?php } /* Restore original Post Data */ wp_reset_postdata(); } else { // no posts found echo "NADA"; }
-7686072 0 NSMutableDictionary *variables = [NSMutableDictionary dictionaryWithCapacity:4]; [variables setObject:[NSString stringWithFormat:@"Hi."] forKey:@"message"]; [variables setObject:@"http://icon.png" forKey:@"picture"]; //http://tinyurl.com/45xy4kw [variables setObject:@"Create post" forKey:@"name"]; [variables setObject:@"Write description." forKey:@"description"]; [_facebook requestWithGraphPath:[NSString stringWithFormat:@"/%@/feed",facebook_user_id] andParams:variables andHttpMethod:@"POST" andDelegate:self];
-37094776 0 There is a major flaw in your design. The error is obvious. In this line
final helpers helpers = new helpers(); you are trying to create an object of an activity which is a very very bad practice. You cannot simply create an object of an activity like this. All Activities in Android must go through the Activity lifecycle so that they have a valid context attached to them. In this case a valid context is not attached to the helper instance. So as a result the line
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE); causes a null pointer as 'this' is null. (Why? Because this refers to the context which has not yet been created as the activity is not started using startActivity(intent))
Another thing though this is not an error, you must use activity names starting with an upper case letter. It is the convention followed and will make your code more readable. Your code is pretty confusing due to the weird use of upper and lower case names. You declare your class with a lower case letter while at some places the variables are upper case. which causes confusion. The rule is that classes, interfaces, etc should start with upper case letters and variables as lower case.
So in this case what do you do?
You never start your Helper activity and I think you do not need to show it to the user. That is it needs to do some work without user interaction. You should make it a service. And then start it using startService(intent).Or you may also create it as a Java class, depends on your use case.
Edit: By the way I answered another similar question having the same problem but involving services later today.
-34891278 0A simple approach to error-checking user input is with a while loop. For example:
def make_score(): while True: score = raw_input('Air, Water, or Grass? ') if score in Attack: break else: print 'Invalid selection.' return score This will loop to input until the user enters a string that matches one of your list items (in the Attack list).
-20617177 0As I was writing the question, I figured out the answer, so I decided to post it right here. But if someone has a different solution, that is more stable or clean, I'm still interested.
The dictionary to be passed to .format should be:
vars(sys.modules[func.__module__])
There's one more issue you might need to address if you are using the Windows 2008 Server with IIS7. The server might report the following error:
Microsoft Office Excel cannot access the file 'c:\temp\test.xls'. There are several possible reasons:
The solution is posted here (look for the text posted by user Ogawa): http://social.msdn.microsoft.com/Forums/en-US/innovateonoffice/thread/b81a3c4e-62db-488b-af06-44421818ef91?prof=required
-10736964 0 gitolite-admin clone issueI am going nuts with a problem cloning the gitolite-admin repository. I have followed this http://sitaramc.github.com/gitolite/install.html#migr and it went perfectly.
I ran ssh-keygen -t rsa and scp ~/.ssh/id_rsa.pub morten@ubuntu-server:/tmp/morten.pub
authorized_keys on the server looks like this:
# gitolite start command="/home/morten/gitolite/src/gitolite-shell morten",no-port-forwarding,no-X11-forwarding,no-agent-forward$ # gitolite end Which AFAIK is okay.
When I run git clone morten@ubuntu-server:gitolite-admin on my client, I get
fatal: 'gitolite-admin' does not appear to be a git repository fatal: The remote end hung up unexpectedly I have no idea what I missed!
-37726516 0When you invoke the printloop function with 5 the for loop essentially becomes
for (x = 5; x < 5; x++) { //... } And x < 5 will never be true.
I guess what you meant was something like
for (x = 0; x < valx; x++) { //... }
-6674893 0 Alt+Key is one way, like AresAvatar posted above.
if you want some more possibilities you can use the KeyBinding class
-37718576 0 How to change the ViewControllers frame position inside the PageViewController?The Code I Have written for loading view controllers in Page View Controllers. Programatically creating four view controllers and adding them to Page View Controller. I have changed the view controllers frame position but still not changing in the app
let controller: UIViewController = UIViewController() print(controller.view.frame) controller.view.frame = CGRectMake(10, 20, self.view.frame.width/2, self.view.frame.height - 20) print(controller.view.frame) controller.view.backgroundColor = UIColor.blackColor() let controller2: UIViewController = UIViewController() controller2.view.backgroundColor = UIColor.redColor() let controller3: UIViewController = UIViewController() controller3.view.backgroundColor = UIColor.blackColor() let controller4: UIViewController = UIViewController() controller4.view.backgroundColor = UIColor.greenColor() let p1 = controller let p2 = controller2 let p3 = controller3 let p4 = controller4 myViewControllers = [p1,p2,p3,p4] for index in 0 ..< myViewControllers.count { NSLog("\(myViewControllers[index])") } let startingViewController = self.viewControllerAtIndex(0) let viewControllers: NSArray = [startingViewController] self.setViewControllers(viewControllers as? [UIViewController], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: {(done: Bool) in })
-5430987 0 You don't need EXECUTE IMMEDIATE in this context.
DECLARE long_var long:=0; BEGIN DBMS_OUTPUT.PUT_LINE(LENGTH(long_var)); SELECT filesize INTO long_var FROM files; DBMS_OUTPUT.PUT_LINE(LENGTH(long_var)); END; / EXECUTE IMMEDIATE runs a stand alone statement of SQL from your PL/SQL code. It can't return anything to your code. The statement you're using isn't valid SQL so you get the ORA-00905. It is valid PL/SQL code and so works as you'd expect once EXECUTE IMMEDIATE is removed.
Edit
Code for your follow on question: To do this with more than one row you can use this
DECLARE CURSOR C1 IS SELECT filesize FROM files; BEGIN FOR files IN c1 LOOP DBMS_OUTPUT.PUT_LINE(LENGTH(files.filesize)); END LOOP; END; /
-40606285 0 C# FtpWebRequest creates corrupted files I'm using .NET 3.5 and I need to transfer by FTP some files. I don't want to use files because I manage all by using MemoryStream and bytes arrays.
Reading these articles (article and article), I made my client.
public void Upload(byte[] fileBytes, string remoteFile) { try { string uri = string.Format("{0}:{1}/{2}", Hostname, Port, remoteFile); FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(uri); ftp.Credentials = new NetworkCredential(Username.Normalize(), Password.Normalize()); ftp.UseBinary = true; ftp.UsePassive = true; ftp.Method = WebRequestMethods.Ftp.UploadFile; using (Stream localFileStream = new MemoryStream(fileBytes)) { using (Stream ftpStream = ftp.GetRequestStream()) { int bufferSize = (int)Math.Min(localFileStream.Length, 2048); byte[] buffer = new byte[bufferSize]; int bytesSent = -1; while (bytesSent != 0) { bytesSent = localFileStream.Read(buffer, 0, bufferSize); ftpStream.Write(buffer, 0, bufferSize); } } } } catch (Exception ex) { LogHelper.WriteLog(logs, "Errore Upload", ex); throw; } } The FTP client connects, writes and close correctly without any error. But the written files are corrupted, such as PDF cannot be opened and for DOC/DOCX Word shows a message about file corruption and tries to restore them.
If I write to a file the same bytes passed to the Upload method, I get a correct file. So the problem must be with FTP transfer.
byte[] fileBytes = memoryStream.ToArray(); File.WriteAllBytes(@"C:\test.pdf", fileBytes); // --> File OK! ftpClient.Upload(fileBytes, remoteFile); // --> File CORRUPTED on FTP folder!
-20113789 0 creating quiz jquery, function load options store quiz code: http://jsfiddle.net/HB8h9/7/
<div id="tab-2" class="tab-content"> <label for="tfq" title="Enter a true or false question"> Enter a Multiple Choice Question </label> <br /> <textarea name="tfq" rows="3" cols="50"></textarea> <p>Mark the correct answer</p> <input type="radio" name="multians" value="A">A)</input> <input name="Avalue" type="text"> <br> <input type="radio" name="multians" value="B">B)</input> <input name="Bvalue" type="text"> <br> <input type="radio" name="multians" value="C">C)</input> <input name="Cvalue" type="text"> <br> <input type="radio" name="multians" value="D">D)</input> <input name="Dvalue" type="text"> <br> //different file below used as main page
$(document).ready(function() { $("#second li ").click(function() { $("#content").load("file_above.html .tabs"); }); }); trying to create a quiz using div elements from different file containing select option tags. Need to create a function which will load all the "appropriate div tags" according to the selected option and display the dropdown options again after each option has been selected. I'm not sure when to implement submit button either after each question type is loaded or somewhere between 5 - 10 questions. the submit button will "store" the questions selected into a quiz which will later be used for another user to answer.
I hope this makes sense, I'm not too familiar with jquery and any help would be highly appreciated.
Any other techniques which would be better suited are also welcomed. thanks.
-14680916 0 On listview only want to click one item at a timeI have a listview with item. Click on an item it goes to another activity. My problem is on clicking on multiple items (say 3 0r4 ) all clicked are loaded. But i dont need it. Only want to load 1 item at a time. Tested on HTC one,samsung galaxy s plus. Please help.
-18407201 0 Html file works locally on IE, but not on server. Works fine for Opera, Chrome, Safari and FirefoxBasically, as the title states, the file works locally, but not when uploaded to a server.
Here's a live working version: jsfiddle
Code extracted from http://www.onextrapixel.com/2013/07/31/creating-content-tabs-with-pure-css/
*The divs are displaying right below their parent tab. That's ok, I just striped down the code to post the question.
This is all in one file, there's no reference to any external files, so path problems should be ruled out.
Thanks.
Google Chrome 
IE Local 
IE when uploaded to webserver 
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Pure CSS Tabs with Fade Animation Demo 1</title> <style type="text/css"> body, html { height: 100%; margin: 0; -webkit-font-smoothing: antialiased; font-weight: 100; background: #aadfeb; text-align: center; font-family: helvetica; } .tabs input[type=radio] { position: absolute; top: -9999px; left: -9999px; } .tabs { width: 650px; float: none; list-style: none; position: relative; padding: 0; margin: 75px auto; } .tabs li{ float: left; } .tabs label { display: block; padding: 10px 20px; border-radius: 2px 2px 0 0; color: #08C; font-size: 24px; font-weight: normal; font-family: 'Roboto', helveti; background: rgba(255,255,255,0.2); cursor: pointer; position: relative; top: 3px; -webkit-transition: all 0.2s ease-in-out; -moz-transition: all 0.2s ease-in-out; -o-transition: all 0.2s ease-in-out; transition: all 0.2s ease-in-out; } .tabs label:hover { background: rgba(255,255,255,0.5); top: 0; } [id^=tab]:checked + label { background: #ececec; border-bottom: 3px orange solid; color: black; top: 0; } [id^=tab]:checked ~ [id^=tab-content] { display: block; } .tab-content{ z-index: 2; display: none; text-align: left; width: 100%; font-size: 20px; line-height: 140%; padding-top: 10px; margin-top:10px; background: #ffffff; padding: 15px; color: black; position: absolute; box-sizing: border-box; -webkit-animation-duration: 0.5s; -o-animation-duration: 0.5s; -moz-animation-duration: 0.5s; animation-duration: 0.5s; } </style> </head> <body> <div class="container"> <div class="main"> <ul class="tabs"> <li> <input type="radio" checked name="tabs" id="tab1"> <label for="tab1">test 1</label> <div id="tab-content1" class="tab-content animated fadeIn"> "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. 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> </li> <li> <input type="radio" name="tabs" id="tab2"> <label for="tab2">test 2</label> <div id="tab-content2" class="tab-content animated fadeIn"> "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? </div> </li> <li> <input type="radio" name="tabs" id="tab3"> <label for="tab3">test 3</label> <div id="tab-content3" class="tab-content animated fadeIn"> "But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?" </div> </li> </ul> </div> </div> </body>
-4625577 0 Trouble including httparty in ruby on rails I've been trying to use HTTParty in my rails code
sudo gem install httparty From the command line I can now successfully do
httparty "http://twitter.com/statuses/public_timeline.json" When I try this in my rails app
require 'rubygems' require 'httparty' class FooController < ApplicationController include HTTParty def bar blah = HTTParty.get("http://twitter.com/statuses/public_timeline.json") end end I get the error message "no such file to load -- httparty"
I suspect there is something wrong with my environment?
-8740252 0 Why are these two queries different?Display the details of the employees who have subscribed for Football and Chess but not for Tennis.
SELECT * FROM employee WHERE empid IN (SELECT empid FROM subscription WHERE facid IN (SELECT facid FROM facility WHERE facility = 'Chess' OR facility = 'Football')) AND empid NOT IN (SELECT empid FROM subscription WHERE facid = (SELECT facid FROM facility WHERE facility = 'Tennis')); SELECT DISTINCT empid FROM subscription WHERE facid IN (SELECT facid FROM facility WHERE facility = 'Chess' OR facility = 'Football') AND facid != (SELECT facid FROM facility WHERE facility = 'Tennis'); The first one gives correct result.
-5453517 0Do you want to keep the session variable? If not you can just use the header function:
header('http://domain.com/category/health-beauty/');
-23132498 0 WP 8.1 - Debug Universal App in device not working with VS 2013 im trying to ebug my universal app from VS 2013 update 2 in my WP8.1 device but i have this error:
Failed to deploy. Make sure another deployment or debugging session is not in progress for the same emulator or device from a different instance of Visual Studio: Error writing file '%FOLDERID_SharedData%\PhoneTools\11.0\Debugger\bin\RemoteDebugger\msvsmon.exe'. Error 0x80070005: Access Denied.
I tried run as administrator and got the same error. Im using VS 2013 Update 1+2, Windows Phone 8.1 on my device (unlocked with WP8.1 developer tool).
Thanks in advance!
-11440989 0 How do I winsorize data in SPSS?Does anyone know how to winsorize data in SPSS? I have outliers for some of my variables and want to winsorize them. Someone taught me how to do use the Transform -> compute variable command, but I forgot what to do. I believe they told me to just compute the square root of the subjects measurement that I want to winsorize. Could someone please elucidate this process for me?
Try a simple trick. Apple has got samples on its site to show how to zoom into a photo using code. Once done zooming, using graphic context take the frame size of the bounding view, and take the image with that. Eg Uiview contains scroll view which has the zoomed image. So the scrollview zooms and so does your image, now take the frame size of your bounding UIview, and create an image context out of it and then save that as a new image. Tell me if that makes sense.
Cheers :)
-15265844 0Might be a typo but Accounts.OnCreateUser(fn); should be Accounts.onCreateUser(fn); Meteor docs: http://docs.meteor.com/#accounts_oncreateuser
And then another post on the same subject: Meteor login with external service : how to get profile information?
EDIT: Posting as edit due the formatting of the below piece of code. In the meantime I have got it running on my own project with this piece of code:
Accounts.onCreateUser(function(options, user) { if(!options || !user) { console.log('error creating user'); return; } else { if(options.profile) { user.profile = options.profile; } } return user; }); Which is working just fine. Have you placed the Accounts.onCreateUser(); on the server?
We have a problem in our project using the node ws websockets library. When the client looses network connection the only way to know that the client is disconnected is by sending a ws.ping() from the server. This is too resource consuming for us.
Does anybody know if there is a default way to get the ws server to use TCP level keepalives instead of using the ping/pong functionality?
-5644871 0 What's wrong with this PHP/JavaScript form validation?I’m not sure whether the problem I’m having is with JavaScript or with PHP.
My objective: To validate a simple yes no form using JavaScript then process it via PHP and have a message displayed.
My problem: When JavaScript is enabled and I click the radio button and submit it the PHP doesn’t output “YES status checked”. Instead it refreshes the page (ie. I think it simply posts the form to user_agreement4.php and does nothing else) When JavaScript is disabled and I click on the YES radio button and submit it, the message “YES status checked” displays correctly. Please note that the code below is for user_agreement4.php. The form will be submitted to itself.
What am I doing wrong?
Please note that this is unfinished code-I haven't added things like cookies, redirection etc. yet.
Also I have a question about choosing answers. May I choose more than one reply as an answer?
<?php // Set variables $selected_radio = 'test'; session_start(); // start up your PHP session! // The below code ensures that $dest should always have a value. if(isset($_SESSION['dest'])){ $dest = $_SESSION['dest']; } // Get the user's ultimate destination if(isset($_GET['dest'])){ $_SESSION['dest'] = $_GET['dest']; // original code was $dest = $_GET['dest']; $dest = $_SESSION['dest']; // new code } else { echo "Nothing to see here Gringo."; //Notification that $dest was not set at this time (although it may retain it's previous set value) } // Show the terms and conditions page //check for cookie if(isset($_COOKIE['lastVisit'])){ /* Add redirect >>>> header("Location: http://www.mywebsite.com/".$dest); <<This comment code will redirect page */ echo "aloha amigo the cookie is seto!"; } else { echo "No cookies for you"; } //Checks to see if the form was sent if (isset($_POST['submitit'])) { //Checks that a radio button has been selected if (isset($_POST['myradiobutton'])) { $selected_radio = $_POST['myradiobutton']; //If No has been selected the user is redirected to the front page. Add code later if ($selected_radio == 'NO') { echo "NO status checked"; } //If Yes has been selected a cookie is set and then the user is redirected to the downloads page. Add cookie code later else if ($selected_radio == 'YES') { echo "YES status checked"; // header("Location: http://www.mywebsite.com/".$dest); } } } ?> <HTML> <HEAD> <TITLE>User Agreement</TITLE> <script language="javascript"> function valbutton(thisform) { // validate myradiobuttons myOption = -1; for (i=thisform.myradiobutton.length-1; i > -1; i--) { if (thisform.myradiobutton[i].checked) { myOption = i; } } if (myOption == -1) { alert("You must choose either YES or NO"); return false; } if (myOption == 0) { alert("You must agree to the agreement to download"); return false; } thisform.submit(); // this line submits the form after validation } </script> </HEAD> <BODY> <H1> User Agreement </H1> <P>Before downloading you must agree to be bound by the following terms and conditions;</P> <form name="myform" METHOD ="POST" ACTION ="user_agreement4.php"> <input type="radio" value="NO" name="myradiobutton" />NO<br /> <input type="radio" value="YES" name="myradiobutton" />YES<br /> <input type="submit" name="submitit" onclick="valbutton(myform);return false;" value="ANSWER" /> </form> </BODY> </HTML>
-20307980 0 PHP if/else not working as intended Below is some code I am using to check if a field says "CIT" to display that as the selected item in the html select box. Elseif the field says "CSE", display "CSE" as selected and CIT/CSE in the drop downs respectively if one or the other is selected in the database. No matter what is in the database field the code always seems to use the first if statement. So courses with "CSE" as course_major are showing "CIT" as the first option in the drop down, however it shouldn't be this way.
while ($row = mysqli_fetch_array ($r, MYSQLI_ASSOC)) { $bg = ($bg=='#B39C56' ? '#000000' : '#0A0A0A'); echo '<tr> <form action="edit_course.php" method="post"> <!--Next Course First Line of Table --><td>Major:</td> <td style="text-align:left">'; if ($row['course_major'] = "CIT") { echo' <select name="course_major" class="rounded"> <option value="'.$row['course_major'].'">'.$row['course_major'].'</option> <option value="CSE">CSE</option> </select>'; } elseif ($row['course_major'] = "CSE") { echo' <select name="course_major" class="rounded"> <option value="'.$row['course_major'].'">'.$row['course_major'].'</option> <option value="CIT">CIT</option> </select>'; }; echo'</td> ........................
-7915444 0 How to play a few video in youtube player on Java, Android? I have a few videos for Android. My app plays it by code:
Intent youtube=new Intent(Intent.ACTION_VIEW, Uri.parse(link)); startActivityForResult(youtube, 100); But it code play 1 video from list. How can I put a few video for Intent in order to standart player play it in series?
-13815278 0 System.InvalidOperationException: Cannot use a DependencyObject that belongs to a different thread than its parent FreezableI have this problem... but can't figure out where is coming from. Do you know of a way to debug this? This happens in a WPF application that has several windows each running in different dispatchers.
System.InvalidOperationException: Cannot use a DependencyObject that belongs to a different thread than its parent Freezable. at System.Windows.Freezable.EnsureConsistentDispatchers(DependencyObject owner, DependencyObject child) at System.Windows.Freezable.OnFreezablePropertyChanged(DependencyObject oldValue, DependencyObject newValue, DependencyProperty property) at System.Windows.Media.RenderData.PropagateChangedHandler(EventHandler handler, Boolean adding) at System.Windows.UIElement.RenderClose(IDrawingContent newContent) at System.Windows.Media.RenderDataDrawingContext.DisposeCore() at System.Windows.Media.DrawingContext.System.IDisposable.Dispose() at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.StackPanel.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Grid.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.DockPanel.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Control.ArrangeOverride(Size arrangeBounds) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Grid.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Grid.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Control.ArrangeOverride(Size arrangeBounds) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Control.ArrangeOverride(Size arrangeBounds) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Grid.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Border.ArrangeOverride(Size finalSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Grid.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Control.ArrangeOverride(Size arrangeBounds) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Grid.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Grid.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Grid.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at MS.Internal.Helper.ArrangeElementWithSingleChild(UIElement element, Size arrangeSize) at System.Windows.Controls.ContentPresenter.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Grid.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Control.ArrangeOverride(Size arrangeBounds) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.DockPanel.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Border.ArrangeOverride(Size finalSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at MS.Internal.Helper.ArrangeElementWithSingleChild(UIElement element, Size arrangeSize) at System.Windows.Controls.ContentPresenter.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Grid.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Border.ArrangeOverride(Size finalSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Grid.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Border.ArrangeOverride(Size finalSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Border.ArrangeOverride(Size finalSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Documents.AdornerDecorator.ArrangeOverride(Size finalSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Window.ArrangeOverride(Size arrangeBounds) at Syncfusion.Windows.Shared.ChromelessWindow.ArrangeOverride(Size arrangeBounds) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Interop.HwndSource.SetLayoutSize() at System.Windows.Interop.HwndSource.set_RootVisualInternal(Visual value) at System.Windows.Window.SetRootVisualAndUpdateSTC() at System.Windows.Window.SetupInitialState(Double requestedTop, Double requestedLeft, Double requestedWidth, Double requestedHeight) at System.Windows.Window.CreateSourceWindow(Boolean duringShow) at System.Windows.Window.ShowHelper(Object booleanBox) at Djali.Services.WindowInfo.PreloadWindow() in c:\src-tfs\Development\Djali\Djali\Services\GuiThreadsService.cs:line 612 at Djali.Services.GuiThreadsService.<>c__DisplayClass20.<InitializeRuntime>b__11() in c:\src-tfs\Development\Djali\Djali\Services\GuiThreadsService.cs:line 293 at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
-8645865 0 3D World with GPS data in Javascript and html5 I would like to create a 3D rotating world in javascript, dynamically positioning points from a json to display data such as text or pictures, and randomly rotating from a point to another.
I would like to receive examples and suggestions before beginning to develop. Which libraries would you use? Which algorythm would you use to rotate the world accordingly to the gps data?
Edit: Reading again my question I think I should make it more clear. I want to make something like Google Earth, without the zoom. There will be points on a 3d model of the earth, and a rotation from a point to another.
-31790460 0 Haproxy - How to parse and store parts of an incoming URLIf I have an incoming url like so:
foo.com/FooID/1234/FooLocation/NYC
How do I go about extracting these values from the incoming request so I can use them for a lookup in a map file. I know this must be doable with regex, but I was hoping for a more elegant solution similar to extracting url parameters:
Example:
http-request set-header X-FooId %[url_param(FooID)].
If not, which regex function would be best used in this instance so I could either store this value or access it directly via a header?
-4341105 0I don't know a very short way, but I would use something like this (as qick hack to get an impression):
try { // this is a new frame, where the picture should be shown final JFrame showPictureFrame = new JFrame("Title"); // we will put the picture into this label JLabel pictureLabel = new JLabel(); /* The following will read the image */ // you should get your picture-path in another way. e.g. with a JFileChooser String path = "C:\\Users\\Public\\Pictures\\Sample Pictures\\Koala.jpg"; URL url = new File(path).toURI().toURL(); BufferedImage img = ImageIO.read(url); /* until here */ // add the image as ImageIcon to the label pictureLabel.setIcon(new ImageIcon(img)); // add the label to the frame showPictureFrame.add(pictureLabel); // pack everything (does many stuff. e.g. resizes the frame to fit the image) showPictureFrame.pack(); //this is how you should open a new Frame or Dialog, but only using showPictureFrame.setVisible(true); would also work. java.awt.EventQueue.invokeLater(new Runnable() { public void run() { showPictureFrame.setVisible(true); } }); } catch (IOException ex) { System.err.println("Some IOException accured (did you set the right path?): "); System.err.println(ex.getMessage()); }
-17701718 0 Combining solve and dsolve to solve equation systems with differential and algebraic equations I am trying to solve equation systems, which contain algebraic as well as differential equations. To do this symbolically I need to combine dsolve and solve (do I?).
Consider the following example: We have three base equations
a == b + c; % algebraic equation diff(b,1) == 1/C1*y(t); % differential equation 1 diff(c,1) == 1/C2*y(t); % differential equation 2 Solving both differential equations, eliminating int(y,0..t) and then solving for c=f(C1,C2,a) yields
C1*b == C2*c or C1*(a-c) == C2*c c = C1/(C1+C2) * a How can I convince Matlab to give me that result? Here is what I tried:
syms a b c y C1 C2; Eq1 = a == b + c; % algebraic equation dEq1 = 'Db == 1/C1*y(t)'; % differential equation 1 dEq2 = 'Dc == 1/C2*y(t)'; % differential equation 2 [sol_dEq1, sol_dEq2]=dsolve(dEq1,dEq2,'b(0)==0','c(0)==0'); % this works, but no inclusion of algebraic equation %[sol_dEq1, sol_dEq2]=dsolve(dEq1,dEq2,Eq1,'c'); % does not work %solve(Eq1,dEq1,dEq2,'c') % does not work %solve(Eq1,sol_dEq_C1,sol_dEq_C2,'c') % does not work No combination of solve and/or dsolve with the equations or their solutions I tried gives me a useful result. Any ideas?
-6279882 0 Tutorials for Writing Common Code for use on Windows, OS X, iOS, and potentially AndroidI'm looking at writing an application that I would like to use on Windows, OSX, and iOS (maybe pushing into Android if other people want to use it). I want to duplicate as little work as possible and I'm having a hard time finding information on the best way to do this.
From what I've found so far I can't use a framework like QT because iOS doesn't support QT so it looks like I'm stuck recreating the interface for each target. I'm looking at writing the business logic in C++ because it seems to be supported by the native tools (Visual Studio and xCode).
Has anyone had experience with a setup like this and if so can you point me towards a good reference for this kind of development?
-34101309 0The second parameter of SetFileAttributesW should be a code to set the value
Try this
HIDE_ATTRIBUTE = 0x02 filepath='file path' ctypes.windll.kernel32.SetFileAttributesW(unicode(file2path), HIDE_ATTRIBUTE)
-7381478 0 Here's a diagram I put together to illustrate the ideas in the other posts:

Test-Path can be used with a special syntax:
Test-Path variable:global:foo
-2950178 0 What you're describing sounds like the proper behavior for a "p" tag. See here. If you don't want the link below it why don't you use a "div" instead of a "p" tag? You should be able to transfer all styles over to the new div.
Update: I think the HTML below would do what you are saying. I did the styles inline for simplicity, you'll want to move those to your css file.
<div class="footer"> <div style="float:left">bla bla bla bla</div> <a href="url_here" style="float:right" class="next" title="Next">Next</a> </div>
-23432284 0 Well, you can check if a variable is an array or string using instanceOf or typeOf or .constuctor: See here http://tobyho.com/2011/01/28/checking-types-in-javascript/
if(myVariable instanceOf Array){ //multi select } else if(myVariable.constructor === String){ //single select } or you can simply convert your string to an array and check the length of the array.
$scope.myVariable = $scope.myPreviousVar.split(','); // or however you want to delimit this if($scope.myVariable.length === 1){ //single select } else if($scope.myVariable.length > 1){ //multi select }
-21748197 0 Here is sample code for you, please note how there are domain classes like Range and Attribute are used for string parsing convenience. All the grouping is done via regular java map.
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class PetalGrouping { private static final String input = "Petal_Length\t0\t1.3 - 2.42\n" + "Petal_Length\t1\t2.42 - 3.54\n" + "Petal_Length\t2\t3.54 - 4.66\n" + "Petal_Length\t3\t4.66 - 5.78\n" + "Petal_Length\t4\t5.78 - 6.9\n" + "Petal_Width\t 5\t0.3 - 0.76\n" + "Petal_Width\t 6\t0.76 - 1.2200000000000002\n" + "Petal_Width\t 7\t1.2200000000000002 - 1.6800000000000002\n" + "Petal_Width\t 8\t1.6800000000000002 - 2.14\n" + "Petal_Width\t 9\t2.14 - 2.6\n" + "Sepal_Length\t10\t4.3 - 5.02\n" + "Sepal_Length\t11\t5.02 - 5.739999999999999\n" + "Sepal_Length\t12\t5.739999999999999 - 6.459999999999999\n" + "Sepal_Length\t13\t6.459999999999999 - 7.179999999999999\n" + "Sepal_Length\t14\t7.179999999999999 - 7.899999999999999\n" + "Sepal_Width\t 15\t2.3 - 2.76\n" + "Sepal_Width\t 16\t2.76 - 3.2199999999999998\n" + "Sepal_Width\t 17\t3.2199999999999998 - 3.6799999999999997\n" + "Sepal_Width\t 18\t3.6799999999999997 - 4.14\n" + "Sepal_Width\t 19\t4.14 - 4.6"; public static void main(String... args) { Map<String, List<Attribute>> map = new HashMap<String, List<Attribute>>(); String[] lines = input.split("\n"); for (String line : lines) { Attribute attribute = Attribute.parse(line); List<Attribute> attributeList = map.get(attribute.getName()); if (attributeList == null) { attributeList = new ArrayList<Attribute>(); map.put(attribute.getName(), attributeList); } attributeList.add(attribute); } System.out.println(map); } } class Range { private double from; private double to; private Range(double from, double to) { this.from = from; this.to = to; } public static Range parse(String string) { String[] parts = string.split(" "); if (parts.length != 3) { throw new RuntimeException("Parsing failed for line: " + string); } return new Range(Double.parseDouble(parts[0].trim()), Double.parseDouble(parts[2].trim())); } @Override public String toString() { return "{from=" + from + ", to=" + to + '}'; } } class Attribute { private String name; private int index; private Range range; protected Attribute(String name, int index, Range range) { this.name = name; this.index = index; this.range = range; } public static Attribute parse(String line) { String[] lineParts = line.split("\t"); if (lineParts.length != 3) { throw new RuntimeException("Parsing failed for line: " + line); } String name = lineParts[0].trim(); int index = Integer.parseInt(lineParts[1].trim()); Range range = Range.parse(lineParts[2].trim()); return new Attribute(name, index, range); } @Override public String toString() { return "index=" + index + " " + range + '}'; } public String getName() { return name; } }
-26143255 0 Nginx rewrite POST as GET, and redirect Is it possible for a POST request to http://me.com
to be converted to a GET request such as http://me.com/api.php?some_static_param=yippee;<rest of post data as get request> using Nginx?
Yes, you will need a 64 bit JVM to utilize all your memory. I am not up to date with what you can get for Windows so I will let someone else answer that.
However, I think the main reason why you can't find a 64 bit netbeans is that it is 100% pure java and architecture independent. Eclipse provides an alternative GUI framework with a more native look and feel (SWT) and uses it for the development environment itself. Once you link to your java app to native libraries you need to distribute the libraries for the correct architecture, hence the architecture dependence of the eclipse distribution (your second item).
-27217219 0You have this problem because you're not correctly using pointers. Look, you create two TreeNode's on a stack, then you take their addresses, and make them children of new node. But, because they are on stack, they have the same address. So all the left and right children will point to the same location.
You probably wanted to allocate them on heap using new or shared_ptr.
I was wondering whether its possible to add new text next to or append text to existing text already on tooltip.
For example, I have a div tag containing tooltip text like so;
<div id="myDiv1" class="myDiv" title="This is Tooltip">body text </div> As shown above, the current tooltip text is: This is Tooltip
What I want to do is using jquery, appned / add more text to this. For example,
This is toopltip for myDiv1 I have tried, but these don't seem to work and most don't return anything some return undefined, please help;
$('#myDiv1').attr("title", $('#myDiv1').tooltip + "" + "\nSome new text to append"); $('#myDiv1').prop("tooltipText", $('#myDiv1').tooltipText + "" + "\nSome new text to append"); $('#myDiv1').attr("data-original-title", $('#myDiv1').tooltipText + "" + "\nSome new text to append"); Any help is welcomed :)
-16536715 0 PHP generated XML parsing failedIn my CodeIgniter 2.x project with PHP 5.3.x I use following function to render Dom Document as XML response. Every things are goes fine. But generated XML parsing failed due to some malformed unexpected text (non-whitespace text outside root element).
function renderDOMAsXML(DOMDocument &$dom, $format = true, $status = 200){ $dom->formatOutput = $format; $controller = &get_instance(); $controller->output->set_status_header($status); $controller->output->set_header('Content-type: application/xml; charset=utf-8'); $controller->output->set_output($dom->saveXML()); } for my curiosity I decoded the malformed unexpected text (non-whitespace text outside root element) as hexadecimal format as following.
\x00ef\x00bb\x00bf\x00ef\x00bb\x00bf\x00ef\x00bb\x00bf\x00ef\x00bb\x00bf\x00ef\x00bb\x00bf or
\x{00ef}\x{00bb}\x{00bf}\x{00ef}\x{00bb}\x{00bf}\x{00ef}\x{00bb}\x{00bf}\x{00ef}\x{00bb}\x{00bf}\x{00ef}\x{00bb}\x{00bf} or like this
 I could not realize what's the wrong. What are the malformed unexpected text (non-whitespace text outside root element)? are they any header information? How do I could skip them as I want to render it as XML response for browser.
-13046003 0yes. Don't see any point not to support it, documentation here provides no restrictions on it (I myself at least have used -land qualifier)
-11118569 0 How do I keep a frame always on top within the application but put it to background when using other applications in Java?My Java application has multiple frames. Some of them are set to be always on top. However, when the user opens another program (let's say a web browser), I want the always-on-top frames to move to the background, making way for the other application to fully show on screen.
-10992697 0Change this
onclick= "SaveData();" to
onclick= "SaveData(this);" Then change the saveData function to
function SaveData(elem) { localStorage["LessonID"] = $(elem).attr('LessonID'); localStorage["SubjectName"] = $(elem).find('.lesson_subject').text(); } Or even better, you can use $.on like @James Allardice showed in his answer.
You could just simplify your query to:
WITH MyQueryAlias1 AS (30 minutes sql query here) SELECT q1.field1 FROM MyQueryAlias1 q1 JOIN MyQueryAlias1 q2 ON q1.field2 = q2.field3 Which will get rid of the second sub-query factoring clause.
This might also work:
WITH MyQueryAlias1 AS (30 minutes sql query here) SELECT field1 FROM MyQueryAlias1 WHERE LEVEL = 1 AND ( field2 = field3 OR CONNECT_BY_ISLEAF = 0 ) CONNECT BY NOCYCLE PRIOR field2 = field3 AND LEVEL = 2;
-40148793 0 Can I use the child selector for the media query? I have some media queries in a class and they're working absolutely fine, but the Chrome browser displays it wrongly as the only browser. So I used a browser hack for the other classes but I don't know how to target the media query. I tried this inside the browser hack:
.firstclass > h1 > @media(min-width: 1620px) { font-size: 3.7vw; } But my code editor says that "media definitions require block statements after any features", so it seems that it takes it as a new media query...
How can I target it correctly? Isn't the media query a child of the class?
-37440671 0I think your problem is with the declaration of overFeature and outFeature.
Actually, while onSelect and onUnselect are template methods, designed to be overriden, overFeature and outFeature are not. Overriding those methods cause the override of the default behaviour ( layer.drawFeature(feature, style); ).
Anyway, I'd suggest you to use events instead. Try with
selectControlHover.events.register('featurehighlighted', null, function(e) { console.log('feature selected ', e.feature); }); Also, I'm quite sure that you can use one single control instead of two, but not knowing what you're trying to do, I can't suggest you another approach.
-23638224 0 how to apply accordion effect manuallyI've made some boxes which will be be expanded and hidden by clicking on the titles of the boxes. I've just used slideToggle() for making it. I need another effect. Here is my fiddle: http://jsfiddle.net/qheJQ/
On that, I have three boxes: Slow Task, Different type of Task and Quick Tasks When anyone click on the Slow Task, the box will be expanded. If user click on Slow Task again, that box will be hidden. if user don't click again for hiding the Slow Task box and click Different type of Task, both the box will remain expanded. So, I want, when user click on Different type of Task, this box will be expanded and other boxes will be hidden if they are extended just like this accordion.
How can I get this without using any plugin for accordion?
My Script:
$('.title').click(function() { $(this).children('.arrow').toggleClass('arrow_up'); $(this).next('.box_expand').slideToggle(); });
-7871219 0 there are three ways to do it
You can read more from PHP Manual
Restler 1.0 had a Digest Authentication example. I've modified to make it work with Restler 2.0
class DigestAuthentication implements iAuthenticate { public $realm = 'Restricted API'; public static $user; public $restler; public function __isAuthenticated() { //user => password hardcoded for convenience $users = array('admin' => 'mypass', 'guest' => 'guest'); if (empty($_SERVER['PHP_AUTH_DIGEST'])) { header('HTTP/1.1 401 Unauthorized'); header('WWW-Authenticate: Digest realm="'.$this->realm.'",qop="auth",nonce="'. uniqid().'",opaque="'.md5($this->realm).'"'); throw new RestException(401, 'Digest Authentication Required'); } // analyze the PHP_AUTH_DIGEST variable if (!($data = DigestAuthentication::http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) || !isset($users[$data['username']])) { throw new RestException(401, 'Wrong Credentials!'); } // generate the valid response $A1 = md5($data['username'] . ':' . $this->realm . ':' . $users[$data['username']]); $A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']); $valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2); if ($data['response'] != $valid_response) { throw new RestException(401, 'Wrong Credentials!'); } // ok, valid username & password DigestAuthentication::$user=$data['username']; return true; } /** * Logs user out of the digest authentication by bringing the login dialog again * ignore the dialog to logout * * @url GET /user/login * @url GET /user/logout */ public function logout() { header('HTTP/1.1 401 Unauthorized'); header('WWW-Authenticate: Digest realm="'.$this->realm.'",qop="auth",nonce="'. uniqid().'",opaque="'.md5($this->realm).'"'); die('Digest Authorisation Required'); } // function to parse the http auth header private function http_digest_parse($txt) { // protect against missing data $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1); $data = array(); $keys = implode('|', array_keys($needed_parts)); preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER); foreach ($matches as $m) { $data[$m[1]] = $m[3] ? $m[3] : $m[4]; unset($needed_parts[$m[1]]); } return $needed_parts ? false : $data; } }
-3864427 0 Variables scope I have two javascript files included at the header of my website. Both files contains almost same variables.
If I have header like this
<head> <script src="http://127.0.0.1/js/file1.js" type="text/javascript"></script> <script src="http://127.0.0.1/js/file2.js" type="text/javascript"></script> </head> Is it possible to access vars defined in file1.js from file2.js ?
This is what i`m trying
file1 $(function() { var x = 1; }); file2 $(function() { console.log(x); //This dosen`t work. Can`t access var });
-30753782 0 This is due to the border having to fit in with whatever the triangles height is. Just change with the width in .triangle-left and you will see the responsiveness.
It will only resize up to 500px high though but this should be more than adequate.
.contain { width: 100%; } /*Left pointing*/ .triangle-left { width: 5%; height: 0; padding-top: 5%; padding-bottom: 5%; overflow: hidden; } .triangle-left:after { content: ""; display: block; width: 0; height: 0; margin-top:-500px; border-top: 500px solid transparent; border-bottom: 500px solid transparent; border-right: 500px solid #4679BD; } <div class="contain"> <div class="triangle-left"></div> </div> The SVG version just requires positioning.
.contain { height: 30px; } <div class="contain"> <svg width="100%" height="100%" viewBox="0 0 500 500"> <polygon points="0,250 500,0 500,500" style="fill:red;stroke:black;stroke-width:2" /> </svg> </div> In SwipListView.java change
case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: log("============ACTION_UP"); clearPressedState(); if (mIsShown) { hiddenRight(mPreItemView); } to
case MotionEvent.ACTION_UP: showRight(mCurrentItemView); case MotionEvent.ACTION_CANCEL: log("============ACTION_UP"); clearPressedState(); if (mIsShown) { if ( mPreItemView != null) hiddenRight(mPreItemView); }
-20116912 0 A very simple GUI application is possible sticking with C and Windows API only.
In short, you have to register your own Window class (RegisterClassEx), then create the window (CreateWindowEx). Note that your window class main element is its (WindowProc) that receive the messages and that you have to implement to act as you want. After that, your C program should run the message pump (PeekMessage and DispatchMessage) for Windows to do its stuff and allow interacting with your window.
See the MSDN documentation for these functions to get help and examples.
-34961752 0 How do i programmatically click a button with C# in IE by classname?So i'm trying to create a code which will automatically click buttons for me in my webBroswer1 object in my visual studio C# Windows form application.
However, the buttons in the website i would want to click do not have IDs, therefore it'd need to be my href/classname
The tag of the buttons is <a>and the href is javascript:void(0), could someone assist me please?
You call a class method by appending the class name likewise:
class.method In your code something like this should suffice:
Test.static_init() You could also do this:
static_init(Test) To call it inside your class, have your code do this:
Test.static_init() My working code:
class Test(object): @classmethod def static_method(cls): print("Hello") def another_method(self): Test.static_method() and Test().another_method() returns Hello
Is it possible to upload files to Rackspace Files Cloud from browser like in Amazon S3?
-13282015 0The right way to do it might be:
(defun my-grep-select(&optional beg end) (interactive (if (use-region-p) (list (region-beginning) (region-end)) (list <wordbegin> <wordend>))) ...)
-6574123 0 If you use jquery datatables you can do something like this in your click event:
var columnIndexToSort = 0, sortAcending = true; $("#table").fnSort([[columnIndexToSort, sortAcending ? 'asc' : 'desc']]); This will cause jquery datatables to sort and redraw the table for you. The jquery datatables plugin is very powerful and I find it harder to find something it can't do rather than something it can.
-1847105 0 How to determine which assembly a specific class belongs to?Often i have a problem that I need to determine which assebmly to include into my project in order to use specific class. For instance I want to you TypeInfo class. MSDN does not say it belongs to. Actually I am not even been able to find TypeInfo class using MSDN document explorer search. All the results relate to some other stuff. For instance first result is about System.Runtime.Remoting.
Also MSDN says - assembly mscorlib. In the components page of Add Reference dialog box i can see mscorlib but also fully qualified names like System.RunTime.Serialization
What is the difference?
-19115264 0WordPress doesn't have wp_dropdown_posts just like it has wp_dropdown_categories and wp_dropdown_users.
It has to be made by hand with get_posts or WP_Query, loop the results and make the <select><option>. For your use case, I think you'll need to use the Custom Fields parameters.
You can find a sample code at WPSE: Dropdown list of a custom post type.
-19228211 0Take a look on that script: https://github.com/CardinalPath/gas/blob/master/src/plugins/max_scroll.js Regards
-26956926 0 matplotlib not share axis x with many sub plotsI want to draw a chart with several sub-charts. The axes X have different lengths. The shape will be like:
subchart 1: ---------
subchart 2: --------------
subchart 3: ------------------
But i don't know how.
-18304309 0The problem is that the InPageAppender relies on log4javascript's own page load handling code to know whether it can start drawing itself. When loaded via RequireJS, the page is already loaded and log4javascript's page load handling code never runs.
You can get around this by calling log4javascript.setDocumentReady(). The most sensible place to do this would seem to be in the shim init() function, but I'm no expert in RequireJS so there may be a better way:
requirejs.config({ shim: { 'log4javascript': { exports: 'log4javascript', init: function() { log4javascript.setDocumentReady(); } } } });
-30979260 0 In ANSI standard SQL, you can do:
select (extract(year from col)*100000 + extract(month from col)*100 + extract(day from col)*1 + (extract(hour from col)*3600 + extract(minute from col)*60 + extract(second from col)) / (24.0*60*60) )
-7271552 0 How to store the cookie info when android killed my app I have an app need login, I use a singleton http client to do everything, so it can track the cookies for me.
But when I launch a browser intent in my app to view some html pages, the app sometimes be killed by low memory, when user come back from the browser, my app activity would be recreated, but the new http client would not contains that login session id.
So I think what I need is to cache the cookies when my app get killed, and then restore it back when the app got recreated. I know there is a CookieSyncManager, but I do not have a full picture of how to use that.
(1) So How can I do that? is Cookie seralizable, I just thought to cache it in the sdcard, maybe a bad idea.
Another more general question maybe:
(2) How to share httpclient with webview/system browser? Not just pass cookies from httpclient to webiew/browser, but also get the cookies when initialize the cookies, How to make the http client and webview/browser share just ONE copy of cookie store in any time?
-24283752 0I believe I've seen this issue upon trying to playback via the simulator vs. on an actual device. Similar to the following post
-15884068 0It looks like you can remove the transform on the second image and it will go back behind the first one. So in other words, on image click I would probably first remove all occurrences of the transform property before applying to the clicked image.
Or you could also set both images to position:relative and then on click set the z-index to something like 5 and set all other images to something below it such as 3. But again, you'll need to clear these inline styles so that when another image is clicked there are remnants from before that give you un-clear results.
-19632055 0TextViews can only contain a small subset of HTML tags not CSS. These tags include <strong>, <underline>, <emphasis>, <p>, <small>, <medium> etc. There are a few others as well.
You can change the font and font colour by doing something like
<p font-color="blue">This is my blue text</p> but you can't add CSS. If you need to do formatting in this way that would require CSS then a webview would be better.
-38804848 1 Select texts between tags in Xpath in Python<td width="250"> 10.03.1984 16:30 <br/> Lütfi Kırdar, İstanbul <br/> <br/> 47-38, 49-58, 8-10 </td> I want to get all text between "td" tags. My code is mactarih=tree.xpath("//tr//td[@width='250']//text()") . But it is wrong.
The expected result is: text=['10.03.1984 16:30','Lütfi Kırdar, İstanbul','47-38, 49-58, 8-10']
-14469684 0This just happened to me... exactly. I needed to change it to \\n instead of \n.
alert("Hello again! This is how we"+"\\n"+"add line breaks to an alert box!");
-27345615 0 In your code se1 still has its base type SalaryEmployee where setSalesAmount method does not exist.
I would say your program is badly designed.
-22387098 0As follow up from comments, next formulas works in F2 and copied down:
=IF(D2="YES",B2*E2,0) or
=B2*E2*(D2="YES")
-20395607 0 How to split a comma separated string into groups of 2 each and then convert all these groups to an array I have a string which is like 1,2,2,3,3,4 etc. First of all, I want to make them into groups of strings like (1,2),(2,3),(3,4). Then how I can make this string to array like{(1,2) (2,3) (3,4)}. Why I want this is because I have a array full of these 1,2 etc values and I've put those values in a $_SERVER['query_string']="&exp=".$exp. So Please give me any idea to overcome this issue or solve.Currently this is to create a group of strings but again how to make this array.
function x($value) { $buffer = explode(',', $value); $result = array(); while(count($buffer)) { $result[] = sprintf('%d,%d', array_shift($buffer), array_shift($buffer)); } return implode(',', $result); } $result = x($expr); but its not working towards my expectations
-10821233 0Adding to Ansari's answer, the diagDominantFlag can be calculated by:
diagDominantFlag = all(diag(A) >= (sum(A, 2) - diag(A))); Thus replacing your double for loop with a one-liner.
I have a CGSize objects that I need to send to my server. The maximum size I can send to the server is 900*900 (900 width/900 height).
There are some objects that are larger the 900*900 and I want to write a function that resizes them to the maximum (as I already say, the maximum is 900*900) but to keep the aspect ratio.
For example: if I have an object that is 1,000px width and 1,000px height I want the function to return a 900*900 object. If I have an object that is 1920px width and 1080px height I want it to return the maximum size possible with keeping the ratio.
Anyone have any idea how can I do that?
Thank you!
OriginalUser2 answer:
I've tried this code:
let aspect = CGSizeMake(900, 900) let rect = CGRectMake(0, 0, 1920, 1080) let final = AVMakeRectWithAspectRatioInsideRect(aspect, rect) final is {x 420 y 0 w 1,080 h 1,080}, I can't understand why the x = 420, but anyway 1080*1080 is not in the same aspect ratio as 1920*1080 and it's bigger than 900*900.
Can you explain a bit more?
-6779371 0HTTP is a pretty simple protocol, the following should get the status code out pretty reliably (updated to be a tad more robust):
int statusCodeStart = httpString.IndexOf(' ') + 1; int statusCodeEnd = httpString.IndexOf(' ', statusCodeStart); return httpString.Substring(statusCodeStart, statusCodeEnd - statusCodeStart); If you really wanted to you could add a sanity check to make sure that the string starts with "HTTP", but then if you wanted robustness you could also just implement a HTTP parser.
To be honest this would probably do! :-)
httpString.Substring(9, 3);
-12686778 0 I think for posting comment main problem you will be having is with the login, before that you need to authorize user, for authorizing user you can use django-social-auth.
As you told that after save you want to do something, you can do it by overriding save function in model. For eg
class Updates(models.Model) ........... ........... def save(): super(save()) .................... # Do your job here .................... Thanks
-29321395 0 How method preference work in java?I just want to understand how below code snippet work ?
class AnnaThread extends Thread { public static void main(String args[]){ Thread t = new AnnaThread(); t.start(); } public void run(){ System.out.println("Anna is here"); } public void start(){ System.out.println("Rocky is here"); } } Output - Rocky is here
-25111308 0You forgot to include the schema in your sql query. Write your query like this:
SELECT * FROM Tester.User Try also to look at your server log in Netbeans, in the output window. Usually you can find their if you're doing wrong something else.
-8500923 0you may need to implement a switch using the value of ...
require('os').type() and the use spawn("open") or spawn("xdg-open") depending on the platform?
-24375276 0You are probably getting this error because Access' Tabledefs list does not always immediately reflect changes you make, i.e. a delete. You can refresh it with CurrentDB.TableDefs.Refresh after any .Appends and/or .Deletes, but this takes time, and considering that refreshing linked tables takes a significant amount of time each, time is something you may not be able to afford.
It is better practice to check your TableDefs for pre-existing links and refresh them, not delete and recreate them, as deleting them also deletes any formatting, such as column widths and field formats that a refresh would leave unchanged.
If you have tables that need their links refreshed, change the .Connect property, then use CurrentDB.TableDefs(TableName).RefreshLink
You should only be using CurrentDb.TableDefs.Delete tdf.Name when the source table no longer exists.
I use a method similar to this myself, however I also store the date and time of the last linked table refresh, and only refresh those tables that had their schema modified after that time. With a hundred or more table links and 2+ seconds per table to refresh the links, I need to save all the time I can.
EDIT:
The following code is the code I use to perform a similar task linking MS Access to SQL Server.
Disclaimer: The following code is provided as-is, and will not work for a pure Access front-end/back-end situation. It will be necessary to modify it to suit your needs.
Public Sub RefreshLinkedTables() Dim adoConn As ADODB.Connection Dim arSQLObjects As ADODB.Recordset Dim CreateLink As Boolean, UpdateLink As Boolean, Found As Boolean Dim dWS As DAO.Workspace Dim dDB As DAO.Database Dim drSQLSchemas As DAO.Recordset, drSysVars As DAO.Recordset, drMSO As DAO.Recordset Dim dTDef As DAO.TableDef Dim ObjectTime As Date Dim sTStart As Double, sTEnd As Double, TStart As Double, TEnd As Double Dim CtrA As Long, ErrNo As Long Dim DescStr As String, SQLStr As String, ConnStr As String Dim SQLObjects() As String sTStart = PerfTimer() Set dWS = DBEngine.Workspaces(0) Set dDB = dWS.Databases(0) Set drSysVars = dDB.OpenRecordset("tbl_SysVars", dbOpenDynaset) If drSysVars.RecordCount = 0 Then Exit Sub AppendTxtMain "Refreshing Links to """ & drSysVars![ServerName] & """: """ & drSysVars![Database] & """ at " & Format(Now, "hh:mm:ss AMPM"), True Set adoConn = SQLConnection() Set arSQLObjects = New ADODB.Recordset SQLStr = "SELECT sys.schemas.name AS [Schema], sys.objects.*, sys.schemas.name + '.' + sys.objects.name AS SOName " & _ "FROM sys.objects INNER JOIN sys.schemas ON sys.objects.schema_id = sys.schemas.schema_id " & _ "WHERE (sys.objects.type IN ('U', 'V')) AND (sys.objects.is_ms_shipped = 0) " & _ "ORDER BY SOName" ObjectTime = Now() arSQLObjects.Open SQLStr, adoConn, adOpenStatic, adLockReadOnly, adCmdText Set drSQLSchemas = dWS.Databases(0).OpenRecordset("SELECT * FROM USys_tbl_SQLSchemas WHERE LinkObjects = True", dbOpenDynaset) Set drMSO = dWS.Databases(0).OpenRecordset("SELECT Name FROM MSysObjects WHERE Type In(1,4,6) ORDER BY Name", dbOpenSnapshot) ReDim SQLObjects(0 To arSQLObjects.RecordCount - 1) With arSQLObjects drMSO.MoveFirst If Not .EOF Then .MoveLast .MoveFirst End If prgProgress.Max = .RecordCount prgProgress = 0 CtrA = 0 ConnStr = "DRIVER={SQL Server Native Client 10.0};SERVER=" & drSysVars![ServerName] & ";DATABASE=" & drSysVars![Database] If Nz(drSysVars![UserName]) = "" Then ConnStr = ConnStr & ";Trusted_Connection=YES" Else ConnStr = ConnStr & ";Uid=" & drSysVars![UserName] & ";Pwd=" & drSysVars![Password] & ";" End If Do Until .EOF TStart = PerfTimer SQLObjects(CtrA) = arSQLObjects![Schema] & "_" & arSQLObjects![Name] AppendTxtMain ![SOName] & " (" & ![modify_date] & "): ", True drSQLSchemas.FindFirst "[SchemaID] = " & ![schema_id] If Not drSQLSchemas.NoMatch Then UpdateLink = False CreateLink = False drMSO.FindFirst "Name=""" & drSQLSchemas![SchemaName] & "_" & arSQLObjects![Name] & """" If drMSO.NoMatch Then CreateLink = True AppendTxtMain "Adding Link... " Set dTDef = dDB.CreateTableDef(arSQLObjects![Schema] & "_" & arSQLObjects![Name], dbAttachSavePWD, ![SOName], "ODBC;" & ConnStr) dDB.TableDefs.Append dTDef dDB.TableDefs(dTDef.Name).Properties.Append dTDef.CreateProperty("Description", dbText, "«Autolink»") ElseIf ![modify_date] >= Nz(drSysVars![SchemaUpdated], #1/1/1900#) Or RegexMatches(dDB.TableDefs(arSQLObjects![Schema] & "_" & arSQLObjects![Name]).Connect, "SERVER=(.+?);")(0).SubMatches(0) <> drSysVars![ServerName] _ Or (dDB.TableDefs(arSQLObjects![Schema] & "_" & arSQLObjects![Name]).Attributes And dbAttachSavePWD) <> dbAttachSavePWD Then UpdateLink = True AppendTxtMain "Refreshing Link... " With dDB.TableDefs(arSQLObjects![Schema] & "_" & arSQLObjects![Name]) .Attributes = dbAttachSavePWD .Connect = "ODBC;" & ConnStr .RefreshLink End With End If End If TEnd = PerfTimer() AppendTxtMain SplitTime(TEnd - TStart, 7, "s") .MoveNext prgProgress = prgProgress + 1 CtrA = CtrA + 1 Loop End With prgProgress = 0 prgProgress.Max = dDB.TableDefs.Count DoEvents dDB.TableDefs.Refresh TStart = PerfTimer() AppendTxtMain "Deleting obsolete linked tables, started " & Now() & "...", True For Each dTDef In dDB.TableDefs If dTDef.Connect <> "" Then ' Is a linked table... On Error Resume Next DescStr = dTDef.Properties("Description") ErrNo = Err.Number On Error GoTo 0 Select Case ErrNo Case 3270 ' Property does not exist ' Do nothing. Case 0 ' Has a Description. If RegEx(DescStr, "«Autolink»") Then ' Description includes "«Autolink»" Found = False For CtrA = 0 To UBound(SQLObjects) If SQLObjects(CtrA) = dTDef.Name Then Found = True Exit For End If Next If Not Found Then ' Delete if not in arSQLObjects AppendTxtMain "Deleting """ & dTDef.Name & """", True dDB.TableDefs.Delete dTDef.Name End If End If End Select End If prgProgress = prgProgress + 1 Next TEnd = PerfTimer() AppendTxtMain "Completed at " & Now() & " in " & SplitTime(TEnd - TStart, 7, "s"), True drSysVars.Edit drSysVars![SchemaUpdated] = ObjectTime drSysVars.Update drSQLSchemas.Close dDB.TableDefs.Refresh Application.RefreshDatabaseWindow Set drSQLSchemas = Nothing arSQLObjects.Close Set arSQLObjects = Nothing adoConn.Close Set adoConn = Nothing drSysVars.Close Set drSysVars = Nothing drMSO.Close Set drMSO = Nothing dDB.Close Set dDB = Nothing dWS.Close Set dWS = Nothing prgProgress = 0 End Sub
-10496754 0 Opentaps ERP- ClassNotFoundException error during running Hi I am new to openTaps ERP development just a day before I started it.I have install a previously done project in my eclips.When I run it it gives me following error.I dont understand that error.
what should be done?
(I am using Postgresql database in it)
Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory at org.hibernate.cfg.Configuration.<clinit>(Configuration.java:152) at org.opentaps.foundation.infrastructure.Infrastructure.getSessionFactory(Infrastructure.java:120) at org.opentaps.common.container.HibernateContainer.start(HibernateContainer.java:109) at org.ofbiz.base.container.ContainerLoader.start(ContainerLoader.java:102) at org.ofbiz.base.start.Start.startStartLoaders(Start.java:264) at org.ofbiz.base.start.Start.startServer(Start.java:313) at org.ofbiz.base.start.Start.start(Start.java:317) at org.ofbiz.base.start.Start.main(Start.java:400) Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) ... 8 more Anyone knows how to resolve it??
-1959965 0We know what is a "site" and "application", so all we got left is The Web
Now, a web application may be a part of a whole website. A website is comprehended of web applications. Though usually you'll see that a website has only one web application.
For instance, you have an iPhone device (compared to a website) which may include different applications: playing music, videos, web browser etc.
-10388700 0Do not pretend the Isolated Storage as a SQL Server. There will be great performance difference. If you want to process too much data, send them to server.
However, there is a method for getting a thumbnail. You can use it:
http://msdn.microsoft.com/en-us/library/system.drawing.image.getthumbnailimage.aspx
Also, please check this answer:
-7394560 0 Why don't inflated views respond to click listeners?I'm trying to set a click listener for a button in my layout. The click listener is only triggered when I call findViewById() directly, and not when I take the view from the inflated layout:
public class MyActivity extends Activity implements View.OnClickListener { private static final String TAG = "MyActivity"; @Override public void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); setContentView( R.layout.test ); Button button = (Button)findViewById( R.id.mybutton ); button.setOnClickListener( this ); LayoutInflater inflater = (LayoutInflater)getSystemService( Context.LAYOUT_INFLATER_SERVICE ); ViewGroup rootLayout = (ViewGroup)inflater.inflate( R.layout.test, (ViewGroup)findViewById( R.id.myroot ), false ); rootLayout.getChildAt( 0 ).setOnClickListener( new View.OnClickListener() { @Override public void onClick( View v ) { Log.d( TAG, "Click from inflated view" ); } } ); } @Override public void onClick( View v ) { Log.d( TAG, "Click" ); } } Here is my layout:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/myroot" android:orientation="vertical" android:layout_width="fill_parent" android:background="#ffffff" android:layout_height="fill_parent"> <Button android:text="Button" android:id="@+id/mybutton" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> </LinearLayout> Why is this? I only get the click event from the first method and not from the inflated view.
-25130700 0Add <base href="/demo/"> to your head or /demo/ to your links. The problem is, that you haven't told the browser to look in your subfolder.
You can easily validate your links: just click on them, analyse the browser's addressbar and correct what's missing or extra in the address shown there.
-11495856 0 Actionscript 3: Healthbar and ButtonSo basically I am making a game in which a button is clicked to decrease the amount of health in a healthbar. I have a button on the stage named fortyfivedown_btn, and a healthbar, which is a 101 frame (includes zero) movieclip. The health bar has an instance name of lifebar. On the stage, the button coding is:
fortyfivedown_btn.addEventListener(MouseEvent.CLICK, fortyfivedownClick); function fortyfivedownClick(event:MouseEvent):void{ lifebar.health = lifebar.health-45; } Inside the healthbar movieclip, I have a layer of coding that is:
var health:int = 100; gotoAndStop(health + 1); if(health < 0) health = 0; else if(health > 100) health = 100; gotoAndStop(health + 1); So, there is my coding. The thing is, when the button is clicked, the healthbar does not go down. I traced the health variable in the button:
fortyfivedown_btn.addEventListener(MouseEvent.CLICK, fortyfivedownClick); function fortyfivedownClick(event:MouseEvent):void{ lifebar.health = lifebar.health-45; } { trace(lifebar.health); } I saw that the output is 0. For some reason the button believes the health is 0, when I declared it was 100 inside the healthbar movieclip? Any help is appreciated.
(Edit)
Alright, in answer to the trace question, if I don't do it like that, there is no output. I should say I'm a beginner at this all, and am learning as I go, so please bear with me. Here is my fla file:
-35239284 0 using compass mixins in scss files compiled by gulp in Laravel ElixirI want to use Compass mixins and Capabilities in scss files that should compiled with Gulp tasks in laravel Elixir.
For example , I have two scss files named my-styles.css and app.scss in resource/assets/sass directory :
This is my-styles.scss file :
@import "compass/css3"; body{ opacity: 1.0; animation: test; color: red; text-align: center; a:link{ background-color: red; text-decoration: none ; &.span{ color: red; @include border-radius(5px); } } } And this is app.scss file Content :
a{ transform: scale(1.1); transform: rotate(30deg) scale(10); } And to compile this scss files and combine them to a file name all.css in public/css directory , I write this :
var elixir = require('laravel-elixir'); var gulp = require('gulp'); var compass = require('gulp-compass'); var sass = require('gulp-sass'); gulp.task('compile', function () { return gulp .src(['my-styles.scss', 'app.scss']) .pipe(sass({compass: true, sourcemap: true, style: 'compressed'})) .pipe(gulp.dest('public/css/all.css')); }); elixir.config.sourcemaps = false; elixir(function (mix) { mix.task('compile'); }); after running gulp command in console this messages are shown:
D:\wamp\www\newProject>gulp [12:36:48] Using gulpfile D:\wamp\www\newProject\gulpfile.js [12:36:48] Starting 'default'... [12:36:48] Starting 'task'... [12:36:48] Starting 'compile'... [12:36:48] Finished 'task' after 17 ms [12:36:48] Finished 'default' after 21 ms [12:36:48] Finished 'compile' after 26 ms But No file is created in public directory.
what is Problem ?
-35194137 0Refer to this SO Discussion which details the reasons for a problem similar to yours.
BETWEEN 'a' and 'b' actually matches to columnValue >='a' and columnValue <= 'b'
In your case w52 is greater than w5 due to lexicographic ordering of Strings - this means that the BETWEEN clause will never return a true (think about it as equivalent to saying BETWEEN 10 and 1 instead of BETWEEN 1 and 10.
Edit to my response:
Refrain from storing the week value as a string. Instead here are a couple of approaches in order of their preference:
YEAR, WEEKNO where YEAR will store values like 2015, 2016 etc and WEEKNO will store the week number. This way you can query data for any week in any year.Since the statements are in a try block there's a chance that they will fail, and your program has a chance of trying to use a non-initialized variable. The solution is to initialize the variables to a default value that makes sense, i.e.,
int guess = -1; // some default value You should also wrap the while loop around the try/catch block. Don't let the program progress until inputted data is valid.
boolean validGuess = false; while (!validGuess) { // prompt user for input here try { guess = Integer.parseInt(iConsole.nextLine()); if (/* .... test if guess is valid int */ ) { validGuess = true; } } catch (NumberFormatException e) { // notify user of bad input, that he should try again } } You could even encapsulate all of this into its own method if you need to do similar things throughout the program.
-28499620 0$("#TextContent").wysihtml5({useLineBreaks: true, ...}) var myCustomTemplates = { custom1: function (context) { var s = "" s += '<li class="dropdown">'; s += '<a class="btn btn-default dropdown-toggle" data-toggle="dropdown" tabindex="-1" aria-expanded="false">'; s += '<span class="current-color">Size</span>'; s += '<b class="caret"></b>'; s += '</a>'; s += '<ul class="dropdown-menu" style="margin-top: 0px;">'; s += '<li><a class="fontSize" data-wysihtml5-command="fontSize" data-wysihtml5-command-value="fs5">5px</a></li>'; s += '</ul>'; s += '</li>'; return s; } }; $("#TextContent").wysihtml5( { customTemplates: myCustomTemplates, "stylesheets": ["~/Content/wysiwyg/editor.css"] }); editor.css
.wysiwyg-font-size-fs5 { font-size: 5px; }
-32249059 0 Firstly, you have not measured the speed of len(), you have measured the speed of creating a list/set together with the speed of len().
Use the --setup argument of timeit:
$ python -m timeit --setup "a=[1,2,3,4,5,6,7,8,9,10]" "len(a)" 10000000 loops, best of 3: 0.0369 usec per loop $ python -m timeit --setup "a={1,2,3,4,5,6,7,8,9,10}" "len(a)" 10000000 loops, best of 3: 0.0372 usec per loop The statements you pass to --setup are run before measuring the speed of len().
Secondly, you should note that len(a) is a pretty quick statement. The process of measuring its speed may be subject to "noise". Consider that the code executed (and measured) by timeit is equivalent to the following:
for i in itertools.repeat(None, number): len(a) Because both len(a) and itertools.repeat(...).__next__() are fast operations and their speeds may be similar, the speed of itertools.repeat(...).__next__() may influence the timings.
For this reason, you'd better measure len(a); len(a); ...; len(a) (repeated 100 times or so) so that the body of the for loop takes a considerably higher amount of time than the iterator:
$ python -m timeit --setup "a=[1,2,3,4,5,6,7,8,9,10]" "$(for i in {0..1000}; do echo "len(a)"; done)" 10000 loops, best of 3: 29.2 usec per loop $ python -m timeit --setup "a={1,2,3,4,5,6,7,8,9,10}" "$(for i in {0..1000}; do echo "len(a)"; done)" 10000 loops, best of 3: 29.3 usec per loop (The results still says that len() has the same performances on lists and sets, but now you are sure that the result is correct.)
Thirdly, it's true that "complexity" and "speed" are related, but I believe you are making some confusion. The fact that len() has O(1) complexity for lists and sets does not imply that it must run with the same speed on lists and sets.
It means that, on average, no matter how long the list a is, len(a) performs the same asymptotic number of steps. And no matter how long the set b is, len(b) performs the same asymptotic number of steps. But the algorithm for computing the size of lists and sets may be different, resulting in different performances (timeit shows that this is not the case, however this may be a possibility).
Lastly,
If the creation of a set object takes more time compared to creating a list, what would be the underlying reason?
A set, as you know, does not allow repeated elements. Sets in CPython are implemented as hash tables (to ensure average O(1) insertion and lookup): constructing and maintaining a hash table is much more complex than adding elements to a list.
Specifically, when constructing a set, you have to compute hashes, build the hash table, look it up to avoid inserting duplicated events and so on. By contrast, lists in CPython are implemented as a simple array of pointers that is malloc()ed and realloc()ed as required.
Alternatively you can control can interface via netlink protocol. See http://www.pengutronix.de/software/libsocketcan/download/ or libnl (http://lists.infradead.org/pipermail/libnl/2012-November/000817.html)
-34554095 0Do not use destructor , because .net C# is managed language
GC class automatically call when then any class initialized,
use ....,
try{ Console.WriteLine("Exception Occurred!"); }catch(Execption ex){ return; } try{ Console.WriteLine("Exception Occurred!"); }catch{ } block to solve this problem. don't use destructor. I think it may help you
-13079237 0 Magento discount to multiple categories without discounting SKU?I am applying a price rule to whole categories in my Magento store but I want to leave out a few of the items within the discounted category.
How can I do this in the price rules? I have tried everything and it just discounts all the products and still discounts the products I want to leave at full normal price.
Thank you so much!
-10992871 0 CodeIgniter: Passing information from the Model to the Controller using result_array()I have the following model that print_r shows Array ( [id] => 1 [cms_name] => Content Mangement System ) Currently in my controller I have $data['contentMangement'] = $this->model->function but I am unsure how to bring my above array into this.
function systemOptions($options) { $this->db->select($options); $query = $this->db->get('options'); if($query->num_rows() > 0) { $row = $query->row_array(); $row['cms_name']; } print_r($row); return $query->result_array(); }
-2175388 0 Yes, you can do this by implementing ISerializationSurrogate and ISurrogateSelector interfaces.
Something like this:
[AttributeUsage(AttributeTargets.Class)] public class SerializeLinqEntities : Attribute { } public class LinqEntitiesSurrogate : ISerializationSurrogate { public void GetObjectData( object obj, SerializationInfo info, StreamingContext context) { EntitySerializer.Serialize(this, obj.GetType(), info, context); } public object SetObjectData( object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector) { EntitySerializer.Deerialize(obj, obj.GetType(), info, context); return obj; } } /// <summary> /// Returns LinqEntitySurrogate for all types marked SerializeLinqEntities /// </summary> public class NonSerializableSurrogateSelector : ISurrogateSelector { public void ChainSelector(ISurrogateSelector selector) { throw new NotImplementedException(); } public ISurrogateSelector GetNextSelector() { throw new NotImplementedException(); } public ISerializationSurrogate GetSurrogate( Type type, StreamingContext context, out ISurrogateSelector selector) { if (!type.IsDefined(typeof(SerializeLinqEntities), false)) { //type not marked SerializeLinqEntities selector = null; return null; } selector = this; return new LinqEntitiesSurrogate(); } } [SerializeLinqEntities] public class TestSurrogate { public int Id { get; set; } public string Name { get; set; } } class Program { static void Main(string[] str) { var ns1 = new TestSurrogate {Id = 47, Name = "TestName"}; var formatter = new BinaryFormatter(); formatter.SurrogateSelector = new NonSerializableSurrogateSelector(); using (var ms = new MemoryStream()) { formatter.Serialize(ms, ns1); ms.Position = 0; var ns2 = (TestSurrogate) formatter.Deserialize(ms); // Check serialization Debug.Assert(ns1.Id == ns2.Id); Debug.Assert(ns1.Name == ns2.Name); } } }
-26362475 0 DECLARE @FixedDate DATE = '2014-11-01'; DECLARE @NextYearFixed DATE = DATEADD(year, 1, @FixedDate) -- 2015-11-01 DECLARE @PreviousYearFixed DATE = DATEADD(year, -1, @FixedDate) -- 2013-11-01
-38650099 0 Avoid the timer altogether.
for i as integer =0 to 100 DoSomething() next i Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick DoSomething() End Sub Sub DoSomething() ' do something End Sub
-9184301 0 In standard C++ there is no such thing as a stack. The standard only differentiates between the different lifetimes of objects. In that case a variable declared as T t; is said to have automatic storage duration, which means it life-time ends with the end of it's surrounding scope. Most (all?) compilers implement this through a stack. It is a reasonable assumption that all objects created that way actually live on the stack.
Replace every occurrence of TODAY() with DATE(2011,9,1):
=YEAR(DATE(2011,9,1))-YEAR(C2)-1 + (MONTH(DATE(2011,9,1))>MONTH(C2)) + (MONTH(C2)=MONTH(DATE(2011,9,1)))*(DAY(DATE(2011,9,1))>=DAY(C2)) For a person born on the date in cell C2, this would give what their age will be on Sept 1, 2011.
Edit: Or, more simply, try this:
=2011-YEAR(C2)-1 + 9>MONTH(C2) + (MONTH(C2)=9)*(1>=DAY(C2))
-40935837 0 I wrote a little PHP wrapper for LIFX. https://github.com/ewkcoder
-22009556 0 OpenCV SURFDetector Range of minHessianI'm using the OpenCV SURFDetector to search for keypoints in an image. In my program I want to give the user the opportunity to set the value of the minHessian with a trackbar, but this means that I would have to know the range of the hessian-values.
I know that the higher I set this threshold the less keypoints I get and vice versa.
Is there a way to calculate a range of the hessian values so I can set 0 (which would be a very high minHessian threshold) on my trackbar to “no keypoints” and 100 (which is probably minHessian=1 or 0) for “all possible keypoints”?
I’ve already taken a look at this question, but this doesn’t help me out here: Whats the meaning of minHessian (Surffeaturedetector)
Edit: I've found a way for my application that works, but I'm not happy with this solution. This is what I am doing now: I constantly raise my minHessian and check if I still find keypoints, but this variant is neither fast nor really exact because I have to take bigger steps (in my case i+=100) to get results faster. I'm pretty sure there is another solution. What about binary search or something similar? Is it really not possible to calculate the maxHessian value?
Here's my code:
C#-side:
private int getMaxHessianValue() { int maxHessian = 0; for (int i = 0; i < 100000; i+=100) { int numberOfKeypoints = GetNumberOfKeypoints(pathToImage, i); if (numberOfKeypoints == 0) // no keypoints found? -> maxHessian { maxHessian = i; break; } } return maxHessian; } C++-side:
int GetNumberOfKeypoints(char* path, int minHessian) { /// Load image Mat templ; templ = imread( path, CV_LOAD_IMAGE_GRAYSCALE ); // Detect the keypoints using SURF Detector SurfFeatureDetector detector( minHessian ); std::vector<KeyPoint> keypoints; detector.detect( templ, keypoints ); // return number of keypoints return keypoints.size(); }
-22886896 0 It's using recursion (of a sort) to handle one set of replacements exposing a new set characters that subsequently need replacing in the same way.
-13770409 0 Re-load Unloaded Projects in EnvDTEI have listed all the projects in my solution, using EnvDTE, but I found a bug in my code: I can't get the projects that are Unloaded.
I found a way to skip the Unloaded projects:
if (string.Compare(EnvDTE.Constants.vsProjectKindUnmodeled, project.Kind, System.StringComparison.OrdinalIgnoreCase) == 0) continue; This way, my code doesn't crash - but I am unable to load the missing projects through code, since they exist already.
How can I Load the Unloaded projects into the solution ?
I have tried:
project.DTE.ExecuteCommand("Project.ReloadProject"); And got error:
System.Runtime.InteropServices.COMException (...): Command "Project.ReloadProject" is not available.
So I tried to somehow get
application.DTE.ExecuteCommand("Project.ReloadProject"); But before that, from every place I searched on the NET, I must pre-select the project in the solution - and for that, I need project.Name (which I have), and the path, which I don't (every example I have found assumes that the solution path is the same as the project path, which is highly unlikely in a generic situation).
you're not implementing background processes, you're trying to start a background process using the syntax of the already-implemented-shell on your computer (but honestly, it's pretty hard to tell what's going on with that indentation. That's really bad. Can you make it readable, please?). That '&' character is recognised by your shell, not by execvp. Have a look at this similar looking question which was the first hit in a google search for your problem.
-25060226 0Override iterator method in ProxyNodeManager.
You can base on how django does it.
-6149620 0Note I'm assuming you just have the data part of the string, not an entire JSON fragment - i.e.
string s = @"blah \u003c blah \u00252 blah"; If the above assumption is wrong and you have a full JSON fragment, just use JavaScriptSerializer to get an object from the data.
Annoyingly, HttpUtility has encode but not decode.
You could spoof the string into a full JSON object, though - this seems a bit overkill:
class Dummy { public string foo { get; set; } } static void Main(string[] args) { string s = @"blah \u003c blah \u00252 blah"; string json = @"{""foo"":""" + s + @"""}"; string unencoded = new JavaScriptSerializer().Deserialize<Dummy>(json).foo; }
-17954648 0 unable to correctly define edittexts in java I am trying to define 3 edittexts adjacent to each other in java.
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // LinearLayout mainLayout=(LinearLayout)findViewById(R.id.linearLayout); // LinearLayout -> RelativeLayout main=new RelativeLayout(this); mainParams=new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT ); main.setLayoutParams(mainParams); mainLayout.addView(main); // LinearLayout -> RelativeLayout -> EditText1 EditText item1=new EditText(this); item1.setHint("Enter the item"); item1.setId(5); RelativeLayout.LayoutParams etParams=new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); etParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT); item1.setLayoutParams(etParams); main.addView(item1); // LinearLayout -> RelativeLayout -> EditText2 EditText quantity1=new EditText(this); item1.setHint("Quantity"); item1.setId(6); RelativeLayout.LayoutParams qparams=new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); etParams.addRule(RelativeLayout.ALIGN_LEFT, 5); item1.setLayoutParams(qparams); main.addView(quantity1); // LinearLayout -> RelativeLayout -> EditText3 EditText rate1=new EditText(this); item1.setHint("rate"); item1.setId(7); RelativeLayout.LayoutParams rparams=new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); etParams.addRule(RelativeLayout.ALIGN_RIGHT, 6); item1.setLayoutParams(rparams); main.addView(rate1); `
I know you might be thinking that i can also do it in xml but the thing is that i have to create more edittexts at runtime.
The problem is that all the editTexts are overlapping each other. plz help
-24191454 0The issue might be that you are trying to Uri encode an already Uri encoded string.
As per the Intent class documentation for the toUri() method:
Convert this Intent into a String holding a URI representation of it. The returned URI string has been properly URI encoded, so it can be used with Uri.parse(String). The URI contains the Intent's data as the base URI, with an additional fragment describing the action, categories, type, flags, package, component, and extras.
So try:
String finaldata = Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME));
-8409762 0 2 column floating layout, does width have to be specified for left column If one uses float:left to layout two columns, does the left column have to have a width specified? Without a width assigned, when I shrink the width of the browser page, the second (main) column gets put underneath the left (navigation) column. Is there a way to avoid this, without assigning a width? If not, what is the least width spec's I need to add? I.e. can I assign a fixed pixel width to the left column, and have the right column get the rest?
Thanks
----- Addition -----
After trying various answers, noting their complexity, is there any reason not to just use a two column table?
-9402799 0The JList component is backed by a list model. So the only recommended way to remove an item from the list view is to delete it from the model (and refresh the view).
I have no idea what the question in there is, but I'll offer:
where ( param1 is not NULL or param2 is not NULL ) and ( ( ( col1 like param1 ) or param1 is NULL ) or ( ( col2 like param2 ) or param2 is NULL ) )
-11066168 0 QMAKE_CXXFLAGS += -std=c++0x Results in an error because you're not using the MinGW compiler. "D9002: Ignoring unknown option -std=c++0x" is an error from the MSVC compiler.
In QtCreator, go to the projects tab(on the left) and change the toolchain you're using. If it hasn't auto-detected MinGW, you're going to have to add it yourself by clicking on the manage button.
-30923131 0 param is missing or the value is empty: itemitems_controller.rb
class ItemsController < ApplicationController def index @items = Item.all render text: @items.map{ |i| "#{i.name}: #{i.price}" }.join('<br/>') end def create item_params = params.require(:item).permit(:name, :description, :price, :real, :weight) @item = Item.create(item_params) render text: "#{@item.id}: #{@item.name}(#{!@item.new_record?})" end end error : param is missing or the value is empty: item
Rails.root: E:/work/my_store_2
Application Trace | Framework Trace | Full Trace app/controllers/items_controller.rb:9:in `create' Request
Parameters:
{"name"=>"car1", "description"=>"good car", "price"=>"500000", "weight"=>"0", "real"=>"1"}
console
Started GET "/items/create?name=car1&description=good+car&price=500000&weight=0&real=1" for 127.0.0.1 at 2015-06-18 21:25:39 +0300 Processing by ItemsController#create as HTML Parameters: {"name"=>"car1", "description"=>"good car", "price"=>"500000", "weight"=>"0", "real"=>"1"} Completed 400 Bad Request in 2ms ActionController::ParameterMissing (param is missing or the value is empty: item): app/controllers/items_controller.rb:9:in `create' where is my mistake?
-5480650 0Try this:
imageView.opaque = NO; imageView.backgroundColor = [UIColor clearColor]; Also, the image used to mask should be black and white (not transparent).
-12665688 0You are checking for Submit in $_POST, but the method specified in the form is GET.
To have it work, change the PHP code to look for $_GET['Submit'].
(But I'd move instead everything, form method included, to POST).
That said, your script seems to have been pasted twice, the second version using $q instead of $trimmed (is $q defined?), and a SQL table called 'table' instead of 'questions':
// get results $query = "SELECT * FROM table WHERE question LIKE '%$q%' OR name LIKE '%$q%' or detail like '%$q%'"; $result = mysql_query($query) or die("Couldn't execute query");
-30327271 0 Another possible workaround is instead of Visibility property use Opacity. In this case calling Focus() actually sets focus.
I have some code in assembly which behaves a little bit strange. I have a C extern function that calls with asm another function from an .asm file. This C function puts on the stack three addresses used by my function from .asm file. All went well untill this appeared:
; Let's say we take from the stack first parameter from my C function. ; This parameter is a string of bytes that respect this format: ; - first 4 bytes are the sign representation of a big number ; - second 4 bytes are the length representation of a big number ; - following bytes are the actual big number section .data operand1 dd 0 section .text global main main: push ebp mov ebp, esp mov eax, [ebp + 8] ; Here eax will contain the address where my big number begins. lea eax, [eax + 8] ; Here eax will contain the address where ; my actual big number begins. mov [operand1], eax PRINT_STRING "[eax] is: " PRINT_HEX 1, [eax] ; a SASM macro which prints a byte as HEX NEWLINE PRINT_STRING "[operand1] is: " PRINT_HEX 1, [operand1] NEWLINE leave ret When running this code, I get at the terminal the correct output for [eax], and for [operand1] it keeps printing a number which will not change if I modify that first parameter of my C function. What am I doing wrong here?
-5323995 0 how to get the url/xmlhttprequest that loads to get the data from a server?i have this problem that i can't solve for days now...here is my code. i want to get the xmlhttprequest or the url that loads everytime i clicked the $("#btnQuery"). what happened here is when i clicked the button, it will display the data in jqgrid from the server.
$("#btnQuery").click( function() { var params = { "ID": $("#eID3").val(), "dataType": "data" } var url = 'process.php?path=' + encodeURI('project/view') + '&json=' + encodeURI(JSON.stringify(params)); $('#tblD').setGridParam({ url:url, datatype: ajaxDataType, }); $('#tblD').trigger('reloadGrid'); $('#firstur').append('the url: ' + url+'<br>');//the xmlhttpRequest should disply here in my html $('#secur').append('response: ' + url+'<br>'); //the response of xmlhttpRequest should display here in my html }); here's the code of my process.php. this is where i'm going to get the data for my jqgrid.
<?php print(file_get_contents("http://localhost/" . $_GET["path"] . "?json=" . ($_GET["json"]))); ?> in firebug console, the xmlhttprequest/location that displays is: http://localhost/process.php?....%22:%22%22,%22Password%22:%22%22%7D
and it's response body is simething like:
{"result":{"ID":"1C1OMk123tJqzbd"}, "time_elapsed":0} does anybody here knows how to get the url/xmlhttprequest that loads to get the data? and its response body? i wan to display it in my html body aside from my jqgrid...is there anyone who can help me?..please... thank you so much
-4867515 0This is strange, if I'm reading your code correctly. Is there a reason that you can't maintain the collection and modify it (as opposed to re-creating it) so that you don't need to RaisePropertyChanged at all? That's what ObservableCollection(of T) does, after all.
As I'm reading it, it might as well be an IEnumerable(of T).
(Creating a new ObservableCollection(of T) in a property getter is almost always a mistake. A ReadOnlyObservableCollection(of T) makes a lot more sense in that context.)
The connections strings that I use look like
<add name="myOracleConnection" connectionString="Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=MyServer)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=XE))); User Id=MyUser; Password=MyPassword;" providerName="system.data.oracleclient"/> I.e. I do not rely on these external configuration files (were they named .ora? I forgot it).
Maybe you can lower dependencies and side-effects if you also try to make your connection string self-containing with everything included?
-36737513 0As you said in the answers above, the field got manually removed from the database, so the migration tries to delete a field that is no longer existing in the database.
Normally you should never delete fields directly in the db but use the migrations instead. As the field is already gone you can now only fake the migration to tell django that the changes were already made:
manage.py migrate rentals 0002 --fake Make sure though that you are at migration 0001, otherwise that would be faked aswell.
just to be sure, you could run the following command first:
manage.py migrate rentals 0001
-13792488 0 CC=gcc CPPFLAGS=-I include VPATH=src include main: main.o method1.o method2.o method3.o method4.o -lm $(CC) $^ -o $@ main.o: main.c main.h $(CC) $(CPPFLAGS) -c $< method1.o: method1.c $(CC) $(CPPFLAGS) -c $< method2.o: method2.c $(CC) $(CPPFLAGS) -c $< method3.o: method3.c $(CC) $(CPPFLAGS) -c $< method4.o: method4.c $(CC) $(CPPFLAGS) -c $< it worked like this
-26136894 1 Why does tuple(set([1,"a","b","c","z","f"])) == tuple(set(["a","b","c","z","f",1])) 85% of the time with hash randomization enabled?Given Zero Piraeus' answer to another question, we have that
x = tuple(set([1, "a", "b", "c", "z", "f"])) y = tuple(set(["a", "b", "c", "z", "f", 1])) print(x == y) Prints True about 85% of the time with hash randomization enabled. Why 85%?
hobby is a String and Strings don't have a method called add in Java.
You should change hobby's type from String to String[] because there is a hobby[rando] in the code that indicates hobby's type must be String[]
Why not just use the array you've created?
For(int i = 0; i< sL.length; i++){ String wavFileName = sl[i] + ".wav"; // do whatever you need to do here } For on demand (press a button get a specific sound) then Jeroen's idea of using a map will work.
-15320259 0Ok i think i understand your problem :
The after_destroy method in PictureFileCallbacks will be auto-magically called by rails :
When rails destroys your PictureFile object, it will instantiate a PictureFileCallbacks object and try to run an after_destroy method in it.
Everything works by convention, if you follow the naming properly everything will work out of the box.
Try it on a dummy project, and if you have some trouble making this work come back with some code to show.
-20960384 0A stop-gap measure would be to insert one (or several) line(s) of
DoEvents
after the change and before ActiveWindow....NextHeaderFooter. That command yields execution to the OS. That may give Word the time it needs to catch up.
Of course, you would do better to avoid using ActiveWindow... altogether and iterate through the sections with a For loop.
-27480594 0I think all you need to have is a so called application defined in your Wowza Streaming Servier, which I guess you already have. This application, let's suppose it's called live can receive multiple live streams from different sources, e.g. GoCoders. Each source can publish a stream with custom name into your application, and then you can choose which one to play in your JW Player's setup, by specifying the stream name in the URL.
(It's not clear to me if you wanted to play multiple videos simultaneously in the same JW Player instance, in a picture-in-picture style.)
-20306465 0 iterating through PictureBoxes in visual c++I'm programming in visual c++, and i have about 60 pictures (indexed p0...p63), and i want to make a loop that goes through all the pictures and change their ImageLocation under some conditions.
I figured the Tag property and one of my attempts was like this: i tagged my pictures from 0 to 63 and then tried the following:
for(int i=0; i<64; i++) { PictureBox->Tag[i]->ImageLocation="possible-.gif"; } It's not working... I get this error:
syntax error : missing ';' before '->' line: 1514 syntax error : missing ';' before '->' line: 1514 (twice, same line)
What's the right way of doing it?
Thank you!
edit:
OK now i have the pictures in an array. Is there a way to have a common rule for all of them? I want to make a click event for each and every one of the pictures. Is the only way setting a rule for each independently? Or can i set a rule for the array itself by saying something like:
if(Pictureboxes[i]_Clicked) { Pictureboxes[i].something = "something else"; }
-26658216 0 Excel Macro - Windows().Activate not taking value The code that works is the following:
Windows("Contract Drilldown (3).xls").Activate When I use :
Windows(Chr(34) & ddlOpenWorkbooks.Value & Chr(34)).Activate I get:
Runtime Error '424': Object Required
If I use a String Variable to pass in the values i.e.:
Dim wbn As String wbn = "Contract Drilldown (3).xls" Windows(Chr(34) & wbn & Chr(34)).Activate I get:
Run-time error '9': Subscript out of range
And if I use
wbn = ddlOpenWorkbooks.Value Windows(Chr(34) & wbn & Chr(34)).Activate I also get
Runtime Error '424': Object Required
Anyone have any idea how I can pass in the ddlOpenWorkbooks.Value in without getting an error?
Ok so the application looks like this: 
the full code block for the Import Data Button is:
Public Sub Data_Import() Windows(ddlOpenWorkBooks.Value).Activate Columns("A:V").Select Selection.Copy Omni_Data.Activate Range("A1").Select ActiveSheet.Paste Omni_Data.Range("A:Z").Interior.ColorIndex = 0 Omni_Data.Range("A:Z").Font.Name = "Segoe UI" Omni_Data.Range("A:Z").Font.Name = "Segoe UI" 'Setting Background Colour to white and changing font End Sub The above Sub is called on Click Event for the button.
As a test the close button has the following code:
Private Sub cmdCancel_Click() MsgBox (ddlOpenWorkbooks.Value) End End Sub Which works fine:

So we have found the problem.
As this is being called from a module it didn't know where ddlOpenWorkbooks was and where to pull that data from.
The corrected code in the Sub is:
Public Sub Data_Import() Windows(frmOmniDataManipulation.ddlOpenWorkbooks.Value).Activate Columns("A:V").Select Selection.Copy Omni_Data.Activate Range("A1").Select ActiveSheet.Paste Omni_Data.Range("A:Z").Interior.ColorIndex = 0 Omni_Data.Range("A:Z").Font.Name = "Segoe UI" Omni_Data.Range("A:Z").Font.Name = "Segoe UI" 'Setting Background Colour to white and changing font End Sub This will allow me to call the sub.
Thanks All!
-11193167 0 intercept data changes and alter/validate from a serverI'm working on a solution to intercept changes to the data from our node.js server and validate/alter them before they are stored/synced to other clients.
Any strategies or suggestions on how to solve this with the current code base?
Currently, it seems like the only option is to rewrite it post-sync operation. That would mean each client would probably receive the sync (including the server), then the server would rewrite the data and trigger a second sync.
To help understand the context of the question, here's what seems like an ideal strategy for my needs:
firebase.child('widgets').beforeSync(myCallback)I am trying to obtain a handle on one of the views in the Action Bar
I will assume that you mean something established via android:actionLayout in your <item> element of your <menu> resource.
I have tried calling findViewById(R.id.menu_item)
To retrieve the View associated with your android:actionLayout, call findItem() on the Menu to retrieve the MenuItem, then call getActionView() on the MenuItem. This can be done any time after you have inflated the menu resource.
Why, you use
var dropdownlist = $(container.find("#ddlActionType")).data("kendoDropDownList"); instead.
You're welcome!
-25304005 0The highest available version of GCC in the 12.04 repositories is 4.6. You can use the package manager to install a newer version, but you will have to add a PPA. This link should help, although it is for a slightly older version of GCC (but can be used for the newest version).
As a commenter pointed out, if your own built version of GCC was compiled with the --prefix parameter, the entire installation should be in that directory under /usr/local or wherever you installed it, and can be removed.
var select = document.getElementById('myselect'); var newoption = document.createElement('option'); newoption.value = 0; // or whatever newoption.innerHTML = '0'; // or whatever select.insertBefore(newoption, select.options[0]);
-11195232 0 My facebook app renders blank for some users I have built facebook app. It's hosted on: http://resihop.herokuapp.com/.
The app is suppose to be visible here: https://apps.facebook.com/393963983989013/
On facebook it's embedded in an iframe. The weird part is that for some users the content of the iframe is empty, just: and for some users it displays the page. Here is the html: that I got from inspect element:
Working:
<div> <noscript><div class="mas"><div class="pam uiBoxRed">Du måste ha javascript aktiverat i din webbläsare för att använda Facebook-applikationer.</div></div></noscript> <form action="https://resihop.herokuapp.com/?fb_source=search&ref=ts" method="post" target="iframe_canvas_fb_https" id="canvas_iframe_post_4fe8ad942b9be6531902412" onsubmit="return Event.__inlineSubmit(this,event)"> <input type="hidden" autocomplete="off" name="signed_request" value="x4b_ddxAkL71eQEdopzIZJpWZCmTPFqOMmmMvx_TCC8.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImV4cGlyZXMiOjEzNDA2NTQ0MDAsImlzc3VlZF9hdCI6MTM0MDY0ODg1Miwib2F1dGhfdG9rZW4iOiJBQUFGbVR1TlI2UlVCQU9zQkRkc2hwbkpNN0pKR0ZaQTNsaGhtMlViNWFlWkFpeFpDNnNYcWVEbXpaQjVqb1dtVUwzVTg1WW5wUWg2WkJVdUxQV3o2M1lIQk5aQVQ4a3dNNGNtWkExZU00MXZ5SU5KeVpDeWFpbDhWIiwidXNlciI6eyJjb3VudHJ5Ijoic2UiLCJsb2NhbGUiOiJzdl9TRSIsImFnZSI6eyJtaW4iOjIxfX0sInVzZXJfaWQiOiIxMDAwMDA2MjcwMTQzODQifQ"> </form> <iframe class="smart_sizing_iframe" frameborder="0" scrolling="yes" id="iframe_canvas" name="iframe_canvas_fb_https" src='javascript:""' height="800" style="height: 574px; "></iframe> </div> Broken:
<div> <noscript><div class="mas"><div class="pam uiBoxRed">You need Javascript enabled in your browser to use Facebook Applications.</div></div></noscript> <form action="https://resihop.herokuapp.com/" method="post" target="iframe_canvas_fb_https" id="canvas_iframe_post_4fe8adec0223e0f59580030" onsubmit="return Event.__inlineSubmit(this,event)"> <input type="hidden" autocomplete="off" name="signed_request" value="yx5eMWJ-0WFSOHg5bkfxesurLc5zZcfuYdyuJqffv0M.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImV4cGlyZXMiOjEzNDA2NTQ0MDAsImlzc3VlZF9hdCI6MTM0MDY0ODk0MCwib2F1dGhfdG9rZW4iOiJBQUFGbVR1TlI2UlVCQUJ6NVRxdWRuaW1tN01ZVzRkdXhSMHczTU1zcDZvbU9ZZ3ZZVm1zZG11dVJLN1lEb1h6Mm9TYUFIeUpaQ2NsSjg5cFBFWkJaQ2haQURyMGZCWWIxOUxaQ0o0QnVaQnR3WkRaRCIsInVzZXIiOnsiY291bnRyeSI6InNlIiwibG9jYWxlIjoiZW5fVVMiLCJhZ2UiOnsibWluIjoyMX19LCJ1c2VyX2lkIjoiNjUxNjY2NDgzIn0"></form> <iframe class="smart_sizing_iframe" frameborder="0" scrolling="yes" id="iframe_canvas" name="iframe_canvas_fb_https" src='javascript:""' height="800" style="height: 294px; "></iframe> </div> One difference I have noticed is that the actions are different. I have waited for several hours now, so it might be a server-unsync-thing, but probably not.
-19100930 0The access token returned in the call to the OAuth2 endpoint identifies the caller and privileges (which api calls you can make). This is required for any of the api calls (REST) to create payments, execute, refunds etc. Some calls require more privileges than others, i.e. you need to have requested more information or provided more credentials when createing the access token.
The token returned in the URL identifies the payment, this is so that when a user is redirected back to your site, you have a way to identify which payment has been redirected back to your site and identify the proper information, i.e. execute the correct payment.
-1521859 0 "Nonrepresentable section on output" error during linking on linuxI get this error at the linker stage when compiling the webkit-1.1.5 package on my Ubuntu 9.04 box:
libtool: link: gcc -ansi -fno-strict-aliasing -O2 -Wall -W -Wcast-align -Wchar-subscripts -Wreturn-type -Wformat -Wformat-security -Wno-format-y2k -Wundef -Wmissing-format-attribute -Wpointer-arith -Wwrite-strings -Wno-unused-parameter -Wno-parentheses -fno-exceptions -fvisibility=hidden -D_REENTRANT -I/usr/include/gtk-2.0 -I/usr/lib/gtk-2.0/include -I/usr/include/atk-1.0 -I/usr/include/cairo -I/usr/include/pango-1.0 -I/usr/include/pixman-1 -I/usr/include/freetype2 -I/usr/include/directfb -I/usr/include/libpng12 -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include -I/usr/include/libsoup-2.4 -I/usr/include/libxml2 -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include -g -O2 -O2 -o Programs/.libs/GtkLauncher WebKitTools/GtkLauncher/Programs_GtkLauncher-main.o -pthread ./.libs/libwebkit-1.0.so /usr/lib/libgtk-x11-2.0.so /usr/lib/libgdk-x11-2.0.so /usr/lib/libatk-1.0.so /usr/lib/libpangoft2-1.0.so /usr/lib/libgdk_pixbuf-2.0.so -lm /usr/lib/libpangocairo-1.0.so /usr/lib/libgio-2.0.so /usr/lib/libcairo.so /usr/lib/libpango-1.0.so /usr/lib/libfreetype.so -lfontconfig /usr/lib/libgmodule-2.0.so /usr/lib/libgobject-2.0.so /usr/lib/libgthread-2.0.so -lrt /usr/lib/libglib-2.0.so -pthread make[1]: Leaving directory `/home/nagul/build_area/webkit-1.1.5' WebKitTools/DumpRenderTree/gtk/TestNetscapePlugin/TestNetscapePlugin.cpp: In function ‘NPError webkit_test_plugin_get_value(NPP_t*, NPPVariable, void*)’: WebKitTools/DumpRenderTree/gtk/TestNetscapePlugin/TestNetscapePlugin.cpp:221: warning: deprecated conversion from string constant to ‘char*’ WebKitTools/DumpRenderTree/gtk/TestNetscapePlugin/TestNetscapePlugin.cpp:224: warning: deprecated conversion from string constant to ‘char*’ WebKitTools/DumpRenderTree/gtk/TestNetscapePlugin/TestNetscapePlugin.cpp: In function ‘char* NP_GetMIMEDescription()’: WebKitTools/DumpRenderTree/gtk/TestNetscapePlugin/TestNetscapePlugin.cpp:260: warning: deprecated conversion from string constant to ‘char*’ /usr/bin/ld: Programs/.libs/GtkLauncher: hidden symbol `__stack_chk_fail_local' in /usr/lib/libc_nonshared.a(stack_chk_fail_local.oS) is referenced by DSO /usr/bin/ld: final link failed: Nonrepresentable section on output collect2: ld returned 1 exit status make[1]: *** [Programs/GtkLauncher] Error 1 make: *** [all] Error 2 I'd like some pointers on how to attack this problem, either by looking into the "hidden sybmol" error or by helping me understand what the "Nonrepresentable section on output" message from the linker actually means.
I have already checked that this is consistent behaviour that persists across a make clean;make invocation.
I have a huge text file in my application (version 1.0).
Lets assume that a new version (2.0) of this file was just released. Most of the file remained the same but the new (2.0) version has a few modifications (some lines removed, others added).
I now wish to update the file (1.0) to the new version (2.0), but do not wish to download the whole file again. I would love to just patch the file with the changes of the new file, thus saving bandwith from downloading the WHOLE new file from my server. (Similar to the way versioning systems like git or svn act)
How can I do this programmatically? Are there any iOS libraries available?
Thank you
-19710113 0 Hadoop - set reducer number to 0 but write to same file?My job is computational intensive so I am actually only using the distribution function of Hadoop, and I want all my output to be in 1 single file so I have set the number of reducer to 1. My reducer is actually doing nothing...
By explicitly setting the number of reducer to 0, may I know how can I control in the mapper to force all the outputs are written into the same 1 output file? Thanks.
-3356905 0I figured out a way somehow. Actually it is in "http://msdn.microsoft.com/en-us/library/ms752347.aspx"
ListBox ItemsSource="{**Binding**}" IsSynchronizedWithCurrentItem="true"/> Note that although we have emphasized that the Path to the value to use is one of the four necessary components of a binding, in the scenarios which you want to bind to an entire object, the value to use would be the same as the binding source object. In those cases, it is applicable to not specify a Path. Consider the following example:
XAML Copy
-20258294 0 How to create human readable time stamp?This is my current PHP program:
$dateStamp = $_SERVER['REQUEST_TIME']; which I later log.
The result is that the $dateStamp variable contains numbers like:
1385615749
This is a Unix timestamp, but I want it to contain human readable date with hour, minutes, seconds, date, months, and years.
So I need a function that will convert it into a human readable date.
How would I do that?
There are other similar questions but not quite like this. I want the simplest possible solution.
-22024213 0 Calling scanf_s() with array of charsI tried this code, but it is not working.
char word1[40]; printf("Enter text: \n"); scanf_s("%s", word1); printf("word1 = %s", word1); When I execute it, it shows:
-28406405 0word1 =
You need to add <tr> in while loop like,
<?php $result = mysql_query("SELECT * FROM A"); while($row=mysql_fetch_array($result)){ ?> <tr> <!-- add this tr --> <td><?php echo $row["source_id"]; ?></td> <td><?php echo $row["escl_status"]; ?></td> <td><?php echo $row["escl_notice"]; ?></td> </tr> <?php } ?> Also change .odd to :odd in your jquery selector,
$("#report tr:odd").click(function(){ // :odd not .odd $(this).next("tr").toggle(); $(this).find(".arrow").toggleClass("up"); });
-11365653 0 If your string can be ANY length and you want to match the cases when you have 0 to 3 charaters you should use:
\d?\d?\d?\d?$ or, if the regex engine understands it:
\d{0-4}$
-28339893 0 Why is IIS exiting with code 0 whenever I preview in Chrome from Visual Studio? I started on a new asp.net site yesterday with vb.net; I am familiar with VB.NET but not ASP.NET.
My primary browser is Google Chrome, but when I attempt to 'emulate' (debug) the site, the debugger exits the local development server spawned by Visual Studio and as a result, Chrome can never load the website (since when it tries to the webserver isn't running). This can be seen easily by viewing Chrome and Visual Studio side-by-side; Visual Studio's status bar turns orange for a second or so then goes back to blue, and IIS exits with code 0:
The program '[73048] iisexpress.exe: Program Trace' has exited with code 0 (0x0). The program '[73048] iisexpress.exe' has exited with code 0 (0x0). However this can be temporarily fixed by 'emulating' in Internet Explorer and then with Chrome again, but this fix must be applied on every reboot in order for it to work.
Why is this happening, and how can I properly debug in Chrome without the webserver exiting?
I read How can I prevent Visual Studio 2013 from closing my IIS Express app when I end debugging? but however none of the solutions helped me in this respect, and that the issue is that Visual Studio seems to be closing iisexpress.exe when the debugging has started.
Chrome runs each tab in a separate process (sandboxing), so perhaps it could be that Visual Studio is expecting Chrome's 'base' PID when Chrome actually spawns an entirely new PID for the new tab created when the 'emulator' starts?
Is there any solution to this other than use Internet Explorer (or the 'fix') for debugging the site?
I am using Visual Studio 2013 Ultimate with Windows 8.1 Pro (Media Centre Edition) and Chrome 40.0.2214.93 m.
-40797343 0 Excel Workbook - Sheet Sync / Version ControlLet's say I have a workbook with two sheets: A and B.
I'm looking for a simple version control system that would allow two users to work on one workbook and keep it in sync. So,
What's a nice & simple way to keep the workbook synced for both users? I don't know if this would require a Macro to compare sheets or if there is some kind of version control software like git to do this.
-12817268 0Start your activity B by Activity A
Intent intent = new Intent(ActivityA.this,ActivityB.Class); startActivityForResult(intent,0); finish your activity B with
Intent intent = new Intent(); setResult(RESULT_OK,intent ); finish(); now in ActivityA
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); //Do your work here in ActivityA }
-2708031 0 You can get the index like so:
$("#eq > span").each(function (index, Element) { alert(index); ... see http://api.jquery.com/each/
-10449952 0Updated after rereading the question.
You are mixing GROUP BY and DISTINCT ON. What you want (how I understand it) can be done with a window function combined with a DISTINCT ON:
SELECT DISTINCT ON (a) a, b, c , count(d) OVER (PARTITION BY a, b, c) AS d_ct , e FROM tbl ORDER BY a, d_ct DESC; Window functions require PostgreSQL 8.4 ore later.
What happens here?
d_ct how many identical sets of (a,b,c) there are in the table with non-null values for d. a. If you don't ORDER BY more than just a, a random row will be picked.ORDER BY d_ct DESC in addition, so a pseudo-random row out of the set with the highest d_ct will be picked.Another, slightly different interpretation of what you might need, with GROUP BY:
SELECT DISTINCT ON (a) a, b, c , count(d) AS d_ct , min(e) AS min_e -- aggregate e in some way FROM t GROUP BY a, b, c ORDER BY a, d_ct DESC; GROUP BY is applied before DISTINCT ON, so the result is very similar to the one above, only the value for e / min_e is different.
Based on your requirement(And as you haven't posted XML layout here that you have tried so far), i assume and can suggest the following:
android:layout_marginBottom="60dip"android:layout_above="@+id/footer"I suggest to you go with 2nd option.
Based on the XML you have posted, try this correct XML layout:
<RelativeLayout android:id="@+id/relativeLayout1" android:layout_height="wrap_content" android:layout_width="match_parent" xmlns:android="http://schemas.android.com/apk/res/android"> <ListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/companylistView" android:layout_above="@+id/textView1"> </ListView> <TextView android:text="Footer Text" android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#000000" android:layout_alignParentBottom="true"> </TextView> </RelativeLayout>
-7220921 0 Subscribing to events in VB.NET requires either the AddHandler or Handles keyword. You will also have a problem with the lambda, the Function keyword requires an expression that returns a value. In VS2010 you can write this:
AddHandler m_switchImageTimer.Tick, Sub(s, e) LoadNextImage() In earlier versions, you need to either change the LoadNextImage() method declaration or use a little private helper method with the correct signature:
AddHandler m_switchImageTimer.Tick, AddressOf SwitchImageTimer_Tick ... Private Sub SwitchImageTimer_Tick(sender As Object, e As EventArgs) LoadNextImage() End Sub
-23072844 0 You could check if the #localVideo element exists. Also, if they are the only elements in the #A element, you can remove them by calling $('#A').empty();.
$(document).ready(function() { $('#BtnOn').click(function() { if ($('#localVideo').length == 0) { $('#A').append('<video id="localVideo" style="background-color:black"></video><div id="remoteVideos"></div>'); } }); $('#BtnOff').click(function() { if ($('#localVideo').length > 0) { $("#localVideo").remove(); $("#remoteVideos").remove(); } }); }); You could also consider hiding and showing the video elements, rather than adding and removing them.
-587003 0http://www.kronenberg.org/ies4osx/
-38090493 0Try:
#+CALL: foo() Also, check the value of the variable org-babel-library-of-babel to make sure that the C-c C-v i worked properly.
(I've tried to edit @false's response, but it was rejected)
my_len_tail/2 is faster (in terms of both the number of inferences and actual time) than buldin length/2 when generating a list, but has problem with N in 1..2 constraint.
?- time(( my_len_tail(L,N),N=10000000 )). % 20,000,002 inferences, 2.839 CPU in 3.093 seconds (92% CPU, 7044193 Lips) L = [_G67, _G70, _G73, _G76, _G79, _G82, _G85, _G88, _G91|...], N = 10000000 . ?- time(( length(L,N),N=10000000 )). % 30,000,004 inferences, 3.557 CPU in 3.809 seconds (93% CPU, 8434495 Lips) L = [_G67, _G70, _G73, _G76, _G79, _G82, _G85, _G88, _G91|...], N = 10000000 .
-30765246 0 natualHeight
Look veeeeeeery closely at that word... =)
It's probably just finding that NaN is neither less than nor greater than nor equal to NaN. (You have the same typo on naturalWidth too)
I am using maven spring boot and spring security with java configuration. I have also created Security Configuration which extends WebSecurityConfigurerAdapter.
Here what i need is once my session is expired then automatically reload all the pages based on antMatchers.
Note: I am using jquery rest client with @RestController instead of jsp and servlet.
No, nested collections as properties can not be used.
The philosophy is simple: maximum decomposition of objects and relationships to effectively use graph algorithms as a tool of analysis. Using your example with food:
And as an illustration of an exemplary model:
-38854818 0 How twitter ios app is doing to push the profile page with a new UINavigationControllerI wondering how Twiter is doing, in the ios app, to push a profile viewController with a new navbar or a new navigationController above the current viewController ?
-25683894 0try with below code :-
if (Request.Cookies["AdminPrintModule"] != null) { HttpCookie cookie = Request.Cookies["AdminPrintModule"]; test = cookie["PrinterSetting2"].ToString(); } Have a look at this document http://www.c-sharpcorner.com/uploadfile/annathurai/cookies-in-Asp-Net/ :-
Below are few types to write and read cookies :-
-33274822 0Non-Persist Cookie - A cookie has expired time Which is called as Non-Persist Cookie
How to create a cookie? Its really easy to create a cookie in the Asp.Net with help of Response object or HttpCookie
Example 1:
HttpCookie userInfo = new HttpCookie("userInfo"); userInfo["UserName"] = "Annathurai"; userInfo["UserColor"] = "Black"; userInfo.Expires.Add(new TimeSpan(0, 1, 0)); Response.Cookies.Add(userInfo);Example 2:
Response.Cookies["userName"].Value = "Annathurai"; Response.Cookies["userColor"].Value = "Black";How to retrieve from cookie?
Its easy way to retrieve cookie value form cookes by help of Request object. Example 1:
string User_Name = string.Empty; string User_Color = string.Empty; User_Name = Request.Cookies["userName"].Value; User_Color = Request.Cookies["userColor"].Value;Example 2:
string User_name = string.Empty; string User_color = string.Empty; HttpCookie reqCookies = Request.Cookies["userInfo"]; if (reqCookies != null) { User_name = reqCookies["UserName"].ToString(); User_color = reqCookies["UserColor"].ToString(); }
First check the Gemfile is present in server or not.
If present, then specify the location in your configuration file by adding below code.
-12734612 0
set :bundle_gemfile, "rails_code/Gemfile"
While your particular case concerns Windows Azure specific (the 4 minute timeout of LBs), the question is pure IIS / ASP.NET workwise. Anyway, I don't think it is possible to send "ping-backs" to the client while in AsyncController/AsyncPage. This is the whole idea of the AsyncPages/Controllers. The IIS leaves the socket aside having the thread serving other requests. And gets back only when you got the OutstandingOperations to zero with AsyncManager.OutstandingOperations.Decrement(); Only then the control is given back to send final response to the client. And once you are the point of sending response, there is no turning back.
I would rather argue for the architectural approach of why you thing someone would wait 4 minutes to get a response (even with a good animated "please wait")? A lot of things may happen during this time. From browser crash, through internet disruption to total power loss/disruption at client. If you are doing real Azure, why not just send tasks for a Worker Role via a Queue (Azure Storage Queues or Service Bus Queues). The other option that stays in front of you for so long running tasks is to use SingalR and fully AJAXed solution. Where you communicate via SignalR the status of the long running operation.
UPDATE 1 due to comments
In addition to the approach suggested by @knightpfhor this can be also achieved with a Queues. Requestor creates a task with some Unique ID and sends it to "Task submission queue". Then "listens" (or polls at regular/irregular intervals) a "Task completion" queue for a message with given Task ID.
In any way I don't see a reason for keeping client connected for the whole duration of the long running task. There are number of ways to decouple such communication.
-6511542 0 Force JavaScript exception/error when reading an undefined object property?I'm an experienced C++/Java programmer working in Javascript for the first time. I'm using Chrome as the browser.
I've created several Javascript classes with fields and methods. When I read an object's field that doesn't exist (due to a typo on my part), the Javascript runtime doesn't throw an error or exception. Apparently such read fields are 'undefined'. For example:
var foo = new Foo(); foo.bar = 1; var baz = foo.Bar; // baz is now undefined I know that I can check for equality against 'undefined' as mentioned in "Detecting an undefined object property in JavaScript", but that seems tedious since I read from object fields often in my code.
Is there any way to force an error or exception to be thrown when I read an undefined property?
And why is an exception thrown when I read an undefined variable (as opposed to undefined object property)?
-14186873 0 What's the best practice to code shared enums between classesnamespace Foo { public enum MyEnum { High, Low } public class Class1 { public MyEnum MyProperty { get; set; } } } MyEnum is declared outside Class1 cause I need it here and in other classes
Seems good, but what if I decide later to delete the file containingClass1?
MyEnum declaration will be lost!!
What's the best practice to code shared enums between classes?
-17177976 0I had the same issue.
But I found another solution. I used the artisan worker as is, but I modified the 'watch' time. By default(from laravel) this time is hardcoded to zero, I've changed this value to 600 (seconds). See the file: 'vendor/laravel/framework/src/Illuminate/Queue/BeanstalkdQueue.php' and in function 'public function pop($queue = null)'
So now the work is also listening to the queue for 10 minutes. When it does not have a job, it exits, and supervisor is restarting it. When it receives a job, it executes it after that it exists, and supervisor is restarting it.
==> No polling anymore!
notes:
Why can't htmlspecialchars() continually encode characters after each form submission? Take a look at the following example:
<?php $_POST['txt'] = htmlspecialchars($_POST['txt']); ?> <form method="post"> <input name="txt" value="<?=$_POST['txt'] ?>" /> <input type="submit" name="save" value="test" /> </form> You can see it at running at http://verticalcms.com/htmlspecialchars.php.
Now do the following
1) Type & into the text field 2) Hit the test button once 3) When the page completes post back, hit the test button again 4) When the page completes post back, view the page source code In the input box, the value is & amp;
I was expecting & amp; amp;
Why is it not & amp; amp; ???
-15329227 0public class twoTimes
{
public static void main(String[] args) { for ( int i=1; i<11; i++)//; <----- Due to this it is not working { System.out.println("count is" + i); } } }
-17935283 0 How to get all the parent classes of a derived class in C# ReflectionIt is weird that I was not able to find a similar question but this is what actually I want, finding all the parent classes of a derived class.
I tested a code with a hope that it works for me :
void WriteInterfaces() { var derivedClass = new DerivedClass(); var type = derivedClass.GetType(); var interfaces = type.FindInterfaces((objectType, criteria) => objectType.Name == criteria.ToString(),"BaseClass"); foreach(var face in interfaces) { face.Name.Dump(); } } interface BaseInterface {} class BaseClass : BaseInterface {} class BaseClass2 : BaseClass {} class DerivedClass : BaseClass2{} Basically, here my main intention is to check if a derived class somehow inherits a base class somewhere in its base hierarchy.
However, this code returns null and works only with interfaces.
-2854088 0 Serialize struct with pointers to NSDataI need to add some kind of archiving functionality to a Objective-C Trie implementation (NDTrie on github), but I have very little experience with C and it's data structures.
struct trieNode { NSUInteger key; NSUInteger count, size; id object; __strong struct trieNode ** children; __strong struct trieNode * parent; }; @interface NDTrie (Private) - (struct trieNode*)root; @end What I need is to create an NSData with the tree structure from that root - or serialize/deserialize the whole tree some other way (conforming to NSCoding?), but I have no clue how to work with NSData and a C struct containing pointers.
Performance on deserializing the resulting object would be crucial, as this is an iPhone project and I will need to load it in the background every time the app starts.
What would be the best way to achieve this?
Thanks!
-20662268 0try to write Range("c" & row).FormulaR1C1=temp
I have a server that uses requests to make queries to another server that may or may not be running. If that server is not running, I do not want to block for a long time; I can just handle the error right away. However, the timeout parameter does not seem to apply to the process of making the initial connection.
From the terminal, I run:
>>> import time >>> import requests >>> t1 = time.time() ; exec("try: requests.get('http://192.168.99.100/', timeout=1.0)\nexcept: pass") ; t2 = time.time() ; t2 - t1 21.00611114501953 This takes about 21 seconds and has no dependance on the timeout I give. I also tried using eventlet's timeout, but it turned out the same:
>>> import time >>> import eventlet >>> requests = eventlet.import_patched('requests') >>> t1 = time.time() ; exec("try: \n with eventlet.Timeout(1): requests.get('http://192.168.99.100/')\nexcept: pass") ; t2 = time.time() ; t2 - t1 21.00276017189026 The error I am getting for the connection is:
ConnectionError: ('Connection aborted.', error(11, 'Resource temporarily unavailable')) Finally, I am running python under the Windows Subsystem for Linux, which might be working with sockets differently.
-36312102 0In your INSTALLED_APPS
INSTALLED_APPS = [ ..., 'HdfsstatsConfig', ] in your views.py
from .viewcreator import Builder UPDATE, DJANGO IMPORTS
There are 3 ways to imports module in django
1. Absolute import: Import a module from outside your current application Example from myapp.views import HomeView 
2. Explicit import: Import a module from inside you current application 
3. Relative import: Same as explicit import but not recommended
from models import MyModel
-27548347 0 First, remove stuff that shouldn't be there:
$str = preg_replace('/[^PDL\d-]/i', '', $str); That gives you the following normalised results:
D456789-1 D456789-1 D456789-1ldlddld Then, attempt to match the data you want:
if (preg_match('/^([PDL])(\d+-\d)/i', $str, $match)) { $code = $match[1]; $load = $match[2]; } else { // uh oh, something wrong with the format! }
-15755847 0 I presume you want the strings instead of the numerical values, correct?
s = '' for j in range(30, 0, -1): s += "{}/{} + ".format(31-j, j) print s[:-2] Read this documentation to get a grasp of it. Essentially, it's formatting the string, using the two pairs of curly braces as placeholders, and passing in the value 31-j in the first slot, and j in the second.
Surely there is a more elegant way to do it, but this is the quick and dirty method.
-15822322 0It's actually not so hard to get this to work. It's a bit hacky since you are adding code to the engine's routes.rb file that changes depending on which env it's running in. If you are using the spec/dummy site approach for testing the engine then use the following code snippet in /config/routes.rb file:
# <your_engine>/config/routes.rb if Rails.env.test? && Rails.application.class.name.to_s == 'Dummy::Application' application = Rails.application else application = YourEngine::Engine end application.routes.draw do ... end What this is basically doing is switching out your engine for the dummy app and writing the routes to it when in test mode.
-12448760 0There are better ways to solve your problem. The typical protocol I use is:
RegisterWindowMessage in both applications. The message name should contain a GUID to make it uniquePostMessage(HWND_BROADCAST, registeredMsg, idIWantToFindYou, HWNDofA)idIWantTofindYou to distinguish between different commands for your message. PostMessage(HWNDofA, registeredMessage, idHereIsMyHWnd, HWNDofB)The upside of this mechanism is not running into problems with unresponsive programs. However, the "connection" isn't immediate, so you have to change your program flow. Alternatively, you can use EnumWindows and SendMessageTimeout to probe all top-level windows.
If you need to use the window class:
The class name assigned by MFC is only so window classes with the same attributes get reused. I am not aware of any problems with using your own window classes.
So the following should work:
WNDCLASS or WNDCLASSEX with the required attributesDefWindowProc as WNDPROC (that's what MFC does, MFC's WNDPROC is set when creating the window)AfxRegisterClass or RegisterClass to register the window class. AfxRegisterClass checks if the class is already registered and if the class is registered from a DLL, it will unregister the class when the DLL is unloaded. Otherwise they are roughly equivalent. If a multithreaded program runs safe on a single-core CPU with hyperthreading, will it also run safe on a dual-core CPU with hyperthreading? Concerning thread-safety etc.
EDIT
Ok, I try to be more specific. I mean the bad source code lines, where I will have forgotten or failed to make sure, that they won't be an (concurrency) issue.
So, maybe the 1-core htt "lies" by preventing dead-locks, crashes, cpu spikes or anything that my code causes on a 2-core machine. I'm unsure, how exactly 2 (logical) processors of a htt PC are different from 2 processors of a dual-core PC, how transparent htt is. If there's any issue, I'll probably buy a second PC just for that, that's why I asked.
-7034090 0The class is being applied by the date picker plug-in, probably using the addClass function. The plug-in, when it's initialized, probably creates a DIV (id=;dp-popup') that has the necessary values for the current month. That DIV is hidden (display:none) but still has the class of dp-popup when first initialized. When you click in the textbox or click the button, there's an event handler assigned to those events (focus for the textbox, click for the button) that sets the display style of the DIV to not be hidden and it also positions it right below the text box.
I didn't dig into the code a whole lot, but looking at the markup a little, that's how I suspect it's working.
-34883336 0You can cast like this:
if(a2 instanceof B) System.out.println("in testmeth->" + ((B) a2).getVar2() ); else System.out.println("in testmeth->" + a2.getVar1() );
-25618225 0 set [Serializable] prpoerty to AuditMessage.
-39697387 1 Real-time Synchronize data between two python applicationIm going to have two python scripts. one is server and another one is client. the server is used to get information from Network Devices like Router or Switch via SNMP. The client needs to get the data from server and output to users.
My algorithm is to let server store all data from snmp into MySQL every minute. Then client reads data from Mysql and show out to user interface every minute also.
I would like to know if there is any other better way to synchronize data between server and client?
Thank in advance.
-26987268 0 NoSuchBeanDefinitionException: No unique bean of type is define. While two beans of same typeThis is first time I am using @autowiring, I have a example.
I want to use Autowiring by TYPE , SO that at Run time container injects appropriate Object and calls appropriate bean/method.
1.INTERFACE
public interface Calculator { public int add(int a,int b); } 2.First Class
public class CalculatorImpl implements Calculator { public int add(int a, int b) { // TODO Auto-generated method stub int result=a+b; return result; } }
3.Second Class
public class CalculatorImpl2 implements Calculator{ public int add(int a, int b) { // TODO Auto-generated method stub int result=a-b; return result; } }
4.REST CLASS
@Component @Path("/calc") public class CalculationService { @Autowired Calculator calculator; @GET @Path("/add/{a}/{b}/") @Qualifier("calculatorImpl") @Produces("text/plain") public Response serveAdd(@PathParam("a") int a, @PathParam("b") int b) { int result= calculator.add(a, b); return Response.status(200).entity(String.valueOf(result)).build(); } @GET @Path("/sub/{a}/{b}") @Qualifier("calculatorImpl2") public Response serveSub(@PathParam("a") int a, @PathParam("b") int b) { int result= calculator.add(a, b); return Response.status(200).entity(String.valueOf(result)).build(); } } 5.APPLICATION-CONTEXT.xml
<context:component-scan base-package="com.veke.rest" /> <bean id="calculatorImpl" class="com.veke.calcImpl.CalculatorImpl" autowire="byType"/> <bean id="calculatorImpl2" class="com.veke.calcImpl.CalculatorImpl2" autowire="byType"/> </beans> ERROR:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'calculationService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.veke.calc.Calculator com.veke.rest.CalculationService.calculator; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.veke.calc.Calculator] is defined: expected single matching bean but found 2: [calculatorImpl, calculatorImpl2]
Have I done correct things? Or I am wrong.
I have done this with my understanding of @autowiring.
Many Thanks :)
Edit: @Qualifier is solution for this problem.(As i Have two beans with same type in context). Its used to solve ambiguity problem. @Autowired is by Type.
try this
Option Explicit Sub test() Dim j As Long Dim rng As Range, cell As Range Dim i As Long j = Application.InputBox("No. of rows to be inserted?", Type:=1) With Worksheets("REFS") '<-_| change "REFS" to your actual worksheet name i = 1 With .Range("D2", .Cells(.Rows.Count, "D").End(xlUp)) Do While i <= .Rows.Count With .Cells(i).EntireRow .Copy .Offset(1).Resize(j).Insert Shift:=xlDown Application.CutCopyMode = False End With i = i + j + 1 Loop End With End With End Sub I'm using Application.InputBox() method instead of VBA InputBox() one because the former lets you force the user input data type (in the example Type:=1 forces numeric input)
-36123828 0 Double from CoreData returns very small numberI am working on a diving application, and one of the feature is to store diving's rating as double into CoreData. The interface should be able to retrieve the double value from the coredata object and then display on screen. However, the problem I got from my code is that the double returned from the object is very small (e with the power of -315). I have no idea why this is happening.
if let dives = self.diveSite?.logged_dives { for dive in dives { print("######### dive site info ########") rating = Double(dive.rating) + rating print(dive) print("raw dive site rating is \(dive.rating)") print("dive rating is \(rating)") } } else { print("no logged_dives") } Here is what's been printed out on the console...
######### dive site info ######## <ScubaDoo.DiveLog: 0x7fe9ea02cbc0> (entity: DiveLog; id: 0xd000000000180002 <x-coredata://2B6F1E6F-1EDA-4910-91FA-0593E05F9EB2/DiveLog/p6> ; data: { current = nil; depth = 0; "dive_at" = "0xd000000000140000 <x-coredata://2B6F1E6F-1EDA-4910-91FA-0593E05F9EB2/DiveSite/p5>"; id = nil; latitude = 0; longitude = 0; rating = 5; "sea_condition" = nil; temperature = 0; time = nil; weather = nil; }) raw dive site rating is 5.35679601527854e-315 dive rating is 1.06203402623994e-314 dive site rating is 1.06203402623994e-314 The DiveLog object in swift is as below. I really do not have a clue about this. It seems that something is out of bound while getting the rating properties?
import Foundation import CoreData extension DiveLog { @NSManaged var time: NSDate? @NSManaged var latitude: NSNumber? @NSManaged var id: String? @NSManaged var rating: NSNumber? @NSManaged var depth: NSNumber? @NSManaged var temperature: NSNumber? @NSManaged var weather: String? @NSManaged var current: String? @NSManaged var sea_condition: String? @NSManaged var longitude: NSNumber? @NSManaged var dive_at: DiveSite? }
-19976655 0 I am currently using C++ builder 6 XE4 for developing finance charts. Exception when moving to a location on the chart canvas While using a C++ builder 6 XE4 for creating a finance charts, i was trying to create, draw line feature. The Series that i had created was candle Stick Series. I tried to move to the XY co-ordinate as pointed out by the mouse pointer but whenever the below piece of code was hit, it threw an exception.
Chart1->Canvas->MoveTo(10,20); --> have given some valid values.
Is it possible to draw a line or any figures on the Chart (not on the form)? If yes, could you please let me know, how should it be done.
Thanks.
-4758750 0 JQuery restart setIntervalSorry to be a bore but having trouble restarting a setInterval with a toggle function. I get to stop it - when needed, but I cannot get it to restart when the toggle "closes"
Here is my code
Set the setInterval
var auto_refresh = setInterval( function() { $('.holder').load('board.php'); }, 5000 ); Stop on toggle - BUT want it to start on the "reverse toggle"
$('.readmore').live('click',function() { $(this).next().slideToggle('slow'); clearInterval(auto_refresh); }, function() { var auto_refresh = setInterval( function() { $('.holder').load('board.php'); }, 5000 ); }); Help much appreciated, as is prob. very simple just I've never beed good at putting functions "within functions"
-10794153 0The problem is not with the fileuploading part, rather looks like in the initialization part. If your file upload control is dynamically created make sure you initialize the uploader after binding that in your markup.
-3309473 0 Spring-Hibernate used in a webapp,what are strategies for Thread safe session managementI'm developing a web app with Spring and Hibernate and I was so obsessed by making he application thread safe and being able to support heavy load that based on my boss recommendation I end up writing my own session and a session container to implement a session per request pattern. Plus I have a lot of DAOs and me not willing to write the same save method for all the DAOs I copy paste this Hibernate GenericDAO (I can't tell it's the same thing because at the time hibernate wasn't owned by jboss) and do the plumbing stuff, and under pressure, all become quickly complicated and on production, the is StaleObjectException and duplicated data right, and i have the feeling that it's time to review what I've done, simplify it and make it more robust for large data handling. One thing you should know is that one request involves many DAO's.
There is quartz running for some updates in the database.
As much as I want to tune everything for the better I lack time to do the necessary research plus Hibernate is kind of huge (learning).
So this is it, I'll like to borrow your experience and ask for few question to know what direction to take.
Question 1 : is Hibernate generated uuid safe enough for threading environment and avoiding StaleObjectException?
Question 2 what are best strategy to use hibernate getCurrentSession in threadSafe scenario (I've read about threadlocal stuff but didn't get too much understanding so didn't do it)
Question 3 : will HIbernateTemplate do for the simplest solution approach?
Question 4 : what will be your choice if you were to implement a connection pool and tuning requirement for production server?
Please do no hesitate to point me to blogs or resources online , all that I need is a approach that works for my scenario. your approach if you were to do this.
Thanks for reading this, everybody's idea is welcomed...
-13330043 0 Git remote branches not listedSo I'm trying to create a remote branch so I can push updates to a project I'm doing to my Github account, but for whatever reason, my remote branches aren't being created.
These are the commands I am running:
git remote add origin git@github.com:<username>/first_app.git git push origin master After running the first line, everything seems to work fine and I don't get any error messages. BUT, when I check what remote branches I have, nothing will show. The command I ran for that was:
git branch -r Ignoring that I figured I would at least try the second command from above. When I did, naturally, it says:
ERROR: Repository not found If someone could help me figure this out it would be greatly appreciated. I've been trying to find information on this online but haven't run into anything yet.
-38315194 0Another way to customize is as following:
columns: [ { command: [{ name: 'edit', click: editButtonClick, template: editButtonTemplate }], title: 'Edit', width: '40px'}..] var editButtonTemplate = '<a class="btn btn-link btn-xs k-grid-edit" href="\\#"><span class="glyphicon glyphicon-pencil"></span></a>'; editButtonClick = function (e) { /* Changes default rendering of 'update' & 'cancel' buttons * but keeps default behaviour */ var btnCancel = $('.k-grid-cancel'); btnCancel.removeClass('k-button k-button-icontext').addClass('btn btn-link btn-xs'); btnCancel.text(''); btnCancel.append('<span class="glyphicon glyphicon-ban-circle"></span>'); var btnOk = $('.k-grid-update'); btnOk.removeClass('k-button k-button-icontext k-primary').addClass('btn btn-link btn-xs'); btnOk.text(''); btnOk.append('<span class="glyphicon glyphicon-ok-circle k-update"></span>'); }
This approach handles click event of standard edit command and modifies rendered html, but preserves standard functionality.
Important detail - grid's update functionality is coupled to element with k-update attribute, while cancel functionality rides on k-grid-cancel.
I write a WindowsForms-GUI for a touchscreen and used the auto-logout Code from How can I trigger an auto-logout within a Windows Forms Application? but i'm wondering if a tochscreen can trigger a MouseMoveEvent(Dont have a touchscreen to test). I figuered out that for WPF there are extra Touchevents, does anyone knows how it works with Forms Applications??
-37851143 0 24/August/2016 12:44 AM Not valid in Safari on MacI have done quite a bit to make sure the date my date picker creates is compatible for being converted into a javascript Date object. I followed the advice on this stack overflow entry: Invalid date in safari and removed dashes from the string using: new Date('24-August-2016 12:44 AM'.replace(/-/g, "/")); That made things compatible with every other operating system and browser, except browsers on a Mac. It still seems safari does not like the full month name in the string. What is the recommended approach to getting safari to recognize the string as a date if I am forced to use that format?
-15416778 0Like TGMCians says, a Toast will do the trick.
If you want to write it to the LogCat instead, then you can use
Log.i(tag, message) You can then view this in the LogCat in Eclipse by going to Window > Show View > Other > Android > LogCat
-4228434 0The reason your initial attempt is not working is that you're attempting to capitalize a symbol or a string that represents the field name and not the actual variable.
You could do something like this and then the data would be capitalized before it's sent to the view.
@sexes = Sex.all @sexes = @sexes.each{|sex| sex.name.capitalize} or
@sexes = Sex.all.each{|sex| sex.name.capitalize}
-39430328 0 How to set mongodb settings, like mongodb.debug in php.ini file? How to set mongodb settings, like mongodb.debug in php.ini file?
For example, here [ http://php.net/manual/en/mongodb.configuration.php#ini.mongodb.debug ] is described setting mongodb.debug with values "" / PHP_INI_ALL .
How to set it in php.ini?
-31038177 0 Why can't we specify a variable size when declaring a static array?Through dynamic memory allocation, the following the code works perfectly.
int *ptr; int size1; cin >> size1; ptr = new int[size1]; In static memory allocation, I get the following error: array bound is not an integer constant before ']' token
int size2; cin >> size2; int arr[size2]; Why is this so? Why can't we specify a variable size?
-15606677 0This is another approach, using more iterables and more relying on defaults:
from itertools import imap, islice, izip def find_min_diff(iterable, sort_func=sorted): sorted_iterable = sort_func(iterable) return min(imap( lambda a, b: b - a, izip(sorted_iterable, islice(sorted_iterable, 1)), ))
-29146259 0 When you say:-
var _db = new PortOfTroyCustomers.Models.PortOfTroyContext(); The compiler infers the type of the expression to the right of the assignment, this is known as implicit type in C#.
Now, you are trying to assign, your query like this, we have System.Data.Entity.DbSet on right & System.Linq.IQueryable on left which are different types:-
IQueryable<Accommodation> query = _db.Accommodations; Thus, you need an explicit typecast like this:-
IQueryable<Accommodation> query = (IQueryable<Accommodation>)_db.Accommodations;
-3483077 0 Applying the Y-Combinator to a recursive function with two arguments in Clojure? Doing the Y-Combinator for a single argument function such as factorial or fibonacci in Clojure is well documented: http://rosettacode.org/wiki/Y_combinator#Clojure
My question is - how do you do it for a two argument function such as this getter for example?
(Assumption here is that I want to solve this problem recursively and this non-idiomatic clojure code is there deliberately for another reason)
[non y-combinator version]
(defn get_ [n lat] (cond (empty? lat) () (= 0 (- n 1)) (first lat) true (get_ (- n 1) (rest lat)))) (get_ 3 '(a b c d e f g h i j))
-9476189 0 If you don't do any query then there is nothing to boost.
A dismax query is nothing more than a query which matches in any one of several fields. You can boost a dismax query in the way that you specified, but you need to do the query to boost it.
q.alt is only used when no query is specified.
-21735457 0I think Maximo will work with the java.sql package, which can be used like so:
import java.sql.* String connectionString = "Your JDBC connection string here"; Connection conn = java.sql.DriverManager.getConnection(connectionString); String sQuery = "SELECT SAMPLE_COLUMN FROM SAMPLE_TABLE"; Statement stmt= conn.createStatement(); ResultSet result = stmt.executeQuery(sQuery); Read here how to parse through a ResultSet to get the information you want: http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html
-12358861 0CATransaction works on Core Animation layer animations. CATransaction is cross-platform between iOS and Mac OS.
NSAnimationContext works with an NSAnimationContext. It's Mac OS specific.
(The NS animation stuff is Mac-only, and the UIView animation stuff is iOS only.)
I work in iOS more than Mac OS these days, and I always look for cross-platform ways to do things.
CAAnimation, CALayer, CAAnimationGroup, etc, are nearly identical between Mac and iOS. There are some differences (e.g. quicktime layers are not supported in iOS, Core Image support is more limited in iOS, etc.) but CA stuff is more alike than different.
-36265049 1 Can't escape a while loop, Python 2.7For some reason i can't escape while loop , i tried debugging it, and looks like for loop is untouched and i don't understand why. (it's fraction of mine tictactoe game code)
users_main = [] computers_main = [] while True: computers_storage = [] users_storage = [] if 0==0: condition = True while condition: guess_y = int(raw_input('Enter coordinate y:')) -1 guess_x = int(raw_input('Enter coordinate x:')) -1 users_storage.append(guess_y) users_storage.append(guess_x) users_main.append(users_storage) for a in computers_main: if a == users_storage: del users_storage[-2] del users_main[-1] condition = True break else: condition = False break break
-14870369 0 tranpose only the two outer words of three How to transpose "foo" and "bar" in "foo and bar" in emacs with the least number of key strokes?
input:
foo and bar output:
bar and foo
-23709460 0 When using the *sync functions in Node.js, what (if any) background operations continue to run When using the Node.js *Sync functions (I understand you shouldn't, and the reasons why), what (if any) background processes continue to run?
For example, if I'm using http.createServer, and from one of the requests I call fs.writeFileSync(), will the server continue to serve new clients whilst that write is in progress (not just accept the connection, but process the entire request)? I.e. would writeFileSync() block the entire process, or just the current call chain?
-35057308 0For me changing back to MAMPS standard port settings did the trick.
-4631207 0This should do the trick:
#!/bin/bash for file in `find $1 -type f -name "*.txt"`; do nlines=`tail -n 1 $file | grep '^$' | wc -l` if [ $nlines -eq 1 ] then echo $file fi done; Call it this way: ./script dir
E.g. ./script /home/user/Documents/ -> lists all text files in /home/user/Documents ending with \n.
If you want to totally throw it away:
import subprocess import os with open(os.devnull, 'w') as fp: cmd = subprocess.Popen(("[command]",), stdout=fp) If you are using Python 2.5, you will need from __future__ import with_statement, or just don't use with.
To get the value of the "first" key, you can use it
map.get(map.keySet().toArray()[0]);
-3529399 0 The solution for that problem seems to be this: you have to call the [player stop] before releasing it. It appears a little strange since I'm already receiving a notification about the player finished playing. Doing so the memory gets deallocated (only a small amount remains , ~100Kb from CoreMedia, but I believe is it normal
var ifExist = YourList.Any(lambda expression) checking if YourList<T> contains object whitch fulifill lambda expression . It's only return true or false. If you want to have list of objects you should use var YourNewList = YourList.Where(lambda expression).ToList().
shmat() is a typical example of same physical address being mapped as two different virtual address in two different processes. If you do pmap -x pid_A . you will you see the virtual mem map for process A similarly for Process B. Actual Phy mem is not exposed to the user-space program.
Now SayProcess A and B share a shared memory segment and shared memory pointer be sh_mem_ptr_A and Sh_mem_ptr_B. If you print these pointers their address(virtual) will be different. Because Sh_mem_ptr_A is a part of memory map of Process A, Similarly sh_mem_ptr_B for Process B.
Kernel maintains the maaping of Virtual-to- phy addr. By page table and offset. Higher bits map to the page table and offset maps to offset in the page table. So If you notice the Lower order bits of sh_mem_ptr_A and sh_mem_ptr_B they will be same(but may not be true always).
-38142733 0Are you making multiple connection to your database without closing them? If you are you should try implementing a check to see if only one connection is up.
To check if your database is open you can do:
if(yourConnection.isOpen()){ doSomething(); //Maybe you want to close it here, if thats the case yourConnection.close(); }
-34686824 0 Use django F() expression and update():
from django.db.models import F Model.objects.filter(condition=condition).update(field=F('field') * 1.5)) django doc about F() and update.
PS: Your model names are not following python class conventions. The should be capfirst with no underscores in between. Check pep8 doc for python class naming details.
-13597140 0Probably too late to be useful, but I was able to connect from Python 3.3 to a MySQL db on my Windows machine (!) using PyMySql (see https://code.google.com/p/pymysql/). Once installed, I used a variation on the code from your reference location here: Python 3 and mysql. I have a schema called "test" and a table called "users", here was the test code:
import pymysql conn = pymysql.connect(host='127.0.0.1', user='root', passwd='password', db='mysql') cur = conn.cursor() cur.execute("SELECT * FROM test.users") for r in cur: print(r) cur.close() conn.close()
-23349358 0 If your target systems are managed by reasonable people, the software will be managed by the packaging system. On Redhat, Fedora, CentOS or SUSE systems that will be RPM. On any system derived from Debian it will be APT.
So your script can check for one of those two packaging systems. Although be warned that you can install RPM on a Debian system so the mere presence of RPM doesn't tell you the system type. Packages can also be named differently. For example, SUSE will name things a bit differently from Redhat.
So, use uname and/or /etc/issue to determine system type. Then you can look for a particular package version with rpm -q apache or dpkg-query -s postgresql.
If the systems are managed by lunatics, the software will be hand-built and installed in /opt or /usr/local or /home/nginx and versions will be unknown. In that case good luck.
-4582120 0An update on the last post... the code now includes a class for the list data structure. I've removed some bugs from the code. It should deliver the right results now.
It seems that for one dimensional data structures, a list structure can actually be faster that an array. But for two dimensional structures, as in the code below, arrays are substantially faster than lists, and significantly faster than dictionaries.
But it all depends on what you want to use the data structures for. For relatively small data sets, dictionaries and lists are often more convenient structures to use.
public interface IDataStructureTimeTestHandler { void PerformTimeTestsForDataStructures(); } public class DataStructureTimeTestHandler : IDataStructureTimeTestHandler { // Example of use: //IDataStructureTimeTestHandler iDataStructureTimeTestHandler = new DataStructureTimeTestHandler(); //iDataStructureTimeTestHandler.PerformTimeTestsForDataStructures(); private IDataStructureTimeTest[] iDataStructureTimeTests; private TimeSpan[,] testsResults; public DataStructureTimeTestHandler() { iDataStructureTimeTests = new IDataStructureTimeTest[3]; testsResults = new TimeSpan[4, 3]; } public void PerformTimeTestsForDataStructures() { iDataStructureTimeTests[0] = new ArrayTimeTest(); iDataStructureTimeTests[1] = new DictionaryTimeTest(); iDataStructureTimeTests[2] = new ListTimeTest(); for (int i = 0; i < iDataStructureTimeTests.Count(); i++) { testsResults[0, i] = iDataStructureTimeTests[i].InstantiationTime(); testsResults[1, i] = iDataStructureTimeTests[i].WriteTime(); testsResults[2, i] = iDataStructureTimeTests[i].ReadTime(LoopType.For); testsResults[3, i] = iDataStructureTimeTests[i].ReadTime(LoopType.Foreach); } } } public enum LoopType { For, Foreach } public interface IDataStructureTimeTest { TimeSpan InstantiationTime(); TimeSpan WriteTime(); TimeSpan ReadTime(LoopType loopType); } public abstract class DataStructureTimeTest { protected IStopwatchType iStopwatchType; protected long numberOfElements; protected int number; protected delegate void TimeTestDelegate(); protected DataStructureTimeTest() { iStopwatchType = new StopwatchType(); numberOfElements = 10000000; } protected void TimeTestDelegateMethod(TimeTestDelegate timeTestMethod) { iStopwatchType.StartTimeTest(); timeTestMethod(); iStopwatchType.EndTimeTest(); } } public class ArrayTimeTest : DataStructureTimeTest, IDataStructureTimeTest { private int[,] integerArray; public TimeSpan InstantiationTime() { TimeTestDelegateMethod(new TimeTestDelegate(InstantiationTime_)); return iStopwatchType.TimeElapsed; } private void InstantiationTime_() { integerArray = new int[numberOfElements, 2]; } public TimeSpan WriteTime() { TimeTestDelegateMethod(new TimeTestDelegate(WriteTime_)); return iStopwatchType.TimeElapsed; } private void WriteTime_() { number = 0; for (int i = 0; i < numberOfElements; i++) { integerArray[i, 0] = number; integerArray[i, 1] = number; number++; } } public TimeSpan ReadTime(LoopType dataStructureLoopType) { switch (dataStructureLoopType) { case LoopType.For: ReadTimeFor(); break; case LoopType.Foreach: ReadTimeForEach(); break; } return iStopwatchType.TimeElapsed; } private void ReadTimeFor() { TimeTestDelegateMethod(new TimeTestDelegate(ReadTimeFor_)); } private void ReadTimeFor_() { for (int i = 0; i < numberOfElements; i++) { number = integerArray[i, 1]; } } private void ReadTimeForEach() { TimeTestDelegateMethod(new TimeTestDelegate(ReadTimeForEach_)); } private void ReadTimeForEach_() { foreach (int i in integerArray) { number = i; } } } public class DictionaryTimeTest : DataStructureTimeTest, IDataStructureTimeTest { private Dictionary<int, int> integerDictionary; public TimeSpan InstantiationTime() { TimeTestDelegateMethod(new TimeTestDelegate(InstantiationTime_)); return iStopwatchType.TimeElapsed; } private void InstantiationTime_() { integerDictionary = new Dictionary<int, int>(); } public TimeSpan WriteTime() { TimeTestDelegateMethod(new TimeTestDelegate(WriteTime_)); return iStopwatchType.TimeElapsed; } private void WriteTime_() { number = 0; for (int i = 0; i < numberOfElements; i++) { integerDictionary.Add(number, number); number++; } } public TimeSpan ReadTime(LoopType dataStructureLoopType) { switch (dataStructureLoopType) { case LoopType.For: ReadTimeFor(); break; case LoopType.Foreach: ReadTimeForEach(); break; } return iStopwatchType.TimeElapsed; } private void ReadTimeFor() { TimeTestDelegateMethod(new TimeTestDelegate(ReadTimeFor_)); } private void ReadTimeFor_() { for (int i = 0; i < numberOfElements; i++) { number = integerDictionary[i]; } } private void ReadTimeForEach() { TimeTestDelegateMethod(new TimeTestDelegate(ReadTimeForEach_)); } private void ReadTimeForEach_() { foreach (KeyValuePair<int, int> i in integerDictionary) { number = i.Key; number = i.Value; } } } public class ListTimeTest : DataStructureTimeTest, IDataStructureTimeTest { private List<int[]> integerList; public TimeSpan InstantiationTime() { TimeTestDelegateMethod(new TimeTestDelegate(InstantiationTime_)); return iStopwatchType.TimeElapsed; } private void InstantiationTime_() { integerList = new List<int[]>(); } public TimeSpan WriteTime() { TimeTestDelegateMethod(new TimeTestDelegate(WriteTime_)); return iStopwatchType.TimeElapsed; } private void WriteTime_() { number = 0; for (int i = 0; i < numberOfElements; i++) { integerList.Add(new int[2] { number, number }); number++; } } public TimeSpan ReadTime(LoopType dataStructureLoopType) { switch (dataStructureLoopType) { case LoopType.For: ReadTimeFor(); break; case LoopType.Foreach: ReadTimeForEach(); break; } return iStopwatchType.TimeElapsed; } private void ReadTimeFor() { TimeTestDelegateMethod(new TimeTestDelegate(ReadTimeFor_)); } private void ReadTimeFor_() { for (int i = 0; i < numberOfElements; i++) { number = integerList[i].ElementAt(1); } } private void ReadTimeForEach() { TimeTestDelegateMethod(new TimeTestDelegate(ReadTimeForEach_)); } private void ReadTimeForEach_() { foreach (int[] i in integerList) { number = i.ElementAt(1); } } }
-13422354 0 Since your parameters are named differently, not too big a deal to query for each one.
string ok = string.Empty; NavigationContext.QueryString.TryGetValue("ok", out ok); string ko = string.Empty; NavigationContext.QueryString.TryGetValue("ko", out ko);
-10953486 0 Sometimes it helps to rephrase the problem: if I read you well, you don't want users, that have a deny time with at least one specified DayID/Hour/Minute:
where !i.UserDeniedTimes.Any( p => (p.AllowedDate.AllowedTimes.Any( a1 => a1.DayID == aTime.DayID && a1.Hour == aTime.Hour && a1.Minute == aTime.Minute )) ) This should select the users you want. If not, please tell in some more words what exactly you are trying to achieve.
-187904 0If you used double quotes instead of single quotes it would work, but you'd be open to an injection attack if the variables weren't sanitized properly.
-27962384 0I found my way around it. I noticed it installs successfully globally. So I installed psycopg2 globally and created a new virtual environment with --system-site-packages option. Then I installed my other packages using the -I option.
Hope this helps someone else.
OK. I later found out that I had no gcc installed. So I had to install it first. And after that, I could pip install psycopg2. Thank you cel for the direction.
You need to know both, The RoR framework is an organizational and convenience system if you will, what it organizes is your ruby code.
If you have programmed before then here are most of your answers:
http://www.ruby-doc.org/core/
http://railsapi.com
You do not need globals for this. A simpler version might be something like:
Function mkArray() Const COLR_GREEN As Long = 11 Const COLR_RED As Long = 2 Dim areaArr As Variant, i As Long areaArr = ActiveSheet.Range("I1:J16").Value For i = 1 To UBound(areaArr, 1) Debug.Print areaArr(i, 1), areaArr(i, 2) Sheets("Sheet1").Shapes(areaArr(i, 1)).Fill.ForeColor.SchemeColor = _ IIf(areaArr(i, 2) > 500, COLR_GREEN, COLR_RED) Next i End Function If you really want to split into separate subs then you should use parameters in place of globals:
E.g.
Function mkArray() Dim areaArr As Variant, i As Long areaArr = ActiveSheet.Range("I1:J16").Value For i = 1 To UBound(areaArr, 1) ColorShape Cstr(areaArr(i, 1)), areaArr(i, 2) Next i End Function Sub ColorShape(shpName as string, shpVal) Const COLR_GREEN As Long = 11 Const COLR_RED As Long = 2 Sheets("Sheet1").Shapes(shpName).Fill.ForeColor.SchemeColor = _ IIf(shpVal > 500, COLR_GREEN, COLR_RED) End Sub
-32404260 0 Getting a 404 after starting Artifactory/Tomcat running on centos I'm trying to get Artifactory running on a centos server. This is what I did:
Created a new user called artifactory
switched to that user
wget https://bintray.com/artifact/download/jfrog/artifactory-rpms/jfrog-artifactory-oss-4.0.2.rpm
then followed instructions from artifactorys docs
rpm -ivh jfrog-artifactory-oss-4.0.2.rpm
service artifactory start
service artifactory check
I get a pid, which according to docs. Everything is working properly. I then navigate to the webpage, but I get a 404:
HTTP Status 404 - /artifactory
type Status report
message /artifactory
description The requested resource is not available.
Apache Tomcat/8.0.22
I want to check logs, which are apparently located at $ARTIFACTORY_HOME/logs/artifactory.log but dir is not found. Doing echo $ARTIFACTORY_HOME doesn't output anything. I did a find command on artifactory.log but no results. Super confused. Any tips would be appreciated.
UPDATE:
Here are some log updates as per the tips from JBaruch.
I navigated to /var/opt/jfrog/artifactory/tomcat/logs
ls showed catalina.2015-09-04.log catalina.out host-manager.2015-09-04.log localhost.2015-09-04.log manager.2015-09-04.log
Here is a output from catalina.out and from localhost.2015-09-04.log:
catalina.out
Sep 04, 2015 1:26:30 PM org.apache.coyote.AbstractProtocol init INFO: Initializing ProtocolHandler ["http-nio-8081"] Sep 04, 2015 1:26:30 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector INFO: Using a shared selector for servlet write/read Sep 04, 2015 1:26:30 PM org.apache.coyote.AbstractProtocol init INFO: Initializing ProtocolHandler ["ajp-nio-8019"] Sep 04, 2015 1:26:30 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector INFO: Using a shared selector for servlet write/read Sep 04, 2015 1:26:30 PM org.apache.catalina.core.StandardService startInternal INFO: Starting service Catalina Sep 04, 2015 1:26:30 PM org.apache.catalina.core.StandardEngine startInternal INFO: Starting Servlet Engine: Apache Tomcat/8.0.22 Sep 04, 2015 1:26:30 PM org.apache.catalina.startup.HostConfig deployDescriptor INFO: Deploying configuration descriptor /opt/jfrog/artifactory/tomcat/conf/Catalina/localhost/artifactory.xml Sep 04, 2015 1:26:32 PM org.apache.catalina.core.StandardContext startInternal SEVERE: One or more listeners failed to start. Full details will be found in the appropriate container log file Sep 04, 2015 1:26:32 PM org.apache.catalina.core.StandardContext startInternal SEVERE: Context [/artifactory] startup failed due to previous errors Sep 04, 2015 1:26:32 PM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesJdbc WARNING: The web application [artifactory] registered the JDBC driver [org.apache.derby.jdbc.AutoloadedDriver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered. Sep 04, 2015 1:26:32 PM org.apache.catalina.startup.HostConfig deployDescriptor INFO: Deployment of configuration descriptor /opt/jfrog/artifactory/tomcat/conf/Catalina/localhost/artifactory.xml has finished in 2,004 ms Sep 04, 2015 1:26:32 PM org.apache.catalina.startup.HostConfig deployDirectory INFO: Deploying web application directory /opt/jfrog/artifactory/tomcat/webapps/ROOT Sep 04, 2015 1:26:32 PM org.apache.catalina.startup.HostConfig deployDirectory INFO: Deployment of web application directory /opt/jfrog/artifactory/tomcat/webapps/ROOT has finished in 57 ms Sep 04, 2015 1:26:32 PM org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["http-nio-8081"] Sep 04, 2015 1:26:32 PM org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["ajp-nio-8019"] And for localhost.2015-09-04.log
04-Sep-2015 13:26:32.596 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.listenerStart Error configuring application listener of class org.artifactory.webapp.servlet.ArtifactoryHomeConfigListener java.lang.UnsupportedClassVersionError: org/artifactory/webapp/servlet/ArtifactoryHomeConfigListener : Unsupported major.minor version 52.0 (unable to load class org.artifactory.webapp.servlet.ArtifactoryHomeConfigListener) at org.apache.catalina.loader.WebappClassLoaderBase.findClassInternal(WebappClassLoaderBase.java:2476) at org.apache.catalina.loader.WebappClassLoaderBase.findClass(WebappClassLoaderBase.java:854) at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1274) at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1157) at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:520) at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:501) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:120) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4651) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5167) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717) at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:586) at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1750) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) 04-Sep-2015 13:26:32.598 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.listenerStart Error configuring application listener of class org.artifactory.webapp.servlet.logback.LogbackConfigListener java.lang.UnsupportedClassVersionError: org/artifactory/webapp/servlet/logback/LogbackConfigListener : Unsupported major.minor version 52.0 (unable to load class org.artifactory.webapp.servlet.logback.LogbackConfigListener) at org.apache.catalina.loader.WebappClassLoaderBase.findClassInternal(WebappClassLoaderBase.java:2476) at org.apache.catalina.loader.WebappClassLoaderBase.findClass(WebappClassLoaderBase.java:854) at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1274) at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1157) at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:520) at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:501) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:120) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4651) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5167) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717) at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:586) at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1750) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) 04-Sep-2015 13:26:32.600 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.listenerStart Error configuring application listener of class org.artifactory.webapp.servlet.ArtifactoryContextConfigListener java.lang.UnsupportedClassVersionError: org/artifactory/webapp/servlet/ArtifactoryContextConfigListener : Unsupported major.minor version 52.0 (unable to load class org.artifactory.webapp.servlet.ArtifactoryContextConfigListener) at org.apache.catalina.loader.WebappClassLoaderBase.findClassInternal(WebappClassLoaderBase.java:2476) at org.apache.catalina.loader.WebappClassLoaderBase.findClass(WebappClassLoaderBase.java:854) at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1274) at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1157) at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:520) at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:501) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:120) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4651) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5167) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717) at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:586) at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1750) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) 04-Sep-2015 13:26:32.607 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.listenerStart Skipped installing application listeners due to previous error(s)
-35573235 1 Why some part of code is not participate in execution process I am trying to split network into two groups (g1 and g2) according to the degree of nodes (if degree of node d>=691 then node is add in g1 otherwise node is add in g2)
import networkx as nx import random import numpy as np import os import sys from networkx.algorithms.assortativity.mixing import degree_mixing_matrix # \attribute_mixing_matrix, numeric_mixing_matrix from networkx.algorithms.assortativity.pairs import node_degree_xy #, \node_attribute_xy from operator import itemgetter from networkx.exception import NetworkXError import networkx.convert as convert g = nx.read_edgelist('/home/suman/Desktop/dataset/Email-Enron.txt',create_using=None,nodetype=int,edgetype=int) s=sorted(g.degree_iter(),key= itemgetter(1),reverse=True) perc=1 def modify_nw_random(g,perc): while(perc<=100): ntm = round((float(perc)/100)*len(g)) #print ntm while(ntm != 0): v = random.randrange(1,len(g)) print"node:", v d=g.degree(v) print"degree:", d g1=nx.Graph() g2=nx.Graph() if g.has_node(v) and (d>=691): g1.add_node(v) else: g2.add_node(v) g.remove_node(v) ntm = ntm-1 if(ntm<=0):break perc=perc+1 print "perc:",perc if(perc>100):break N1=nx.number_of_nodes(g1) print N1 r2=nx.degree_assortativity_coefficient(g1) print ("%f"%r2) N2=nx.number_of_nodes(g2) print N2 r3=nx.degree_assortativity_coefficient(g2) print ("%f"%r3) modify_nw_random(g,perc) here first loop are executed when perc = 1 and then perc is increase by 1 (perc=perc+1) this is not execute .it means following part of code is not participating in execution process
perc=perc+1 print "perc:",perc if(perc>100):break print "node in g1:", g1.nodes() print "node in g2:", g2.nodes() N1=nx.number_of_nodes(g1) print N1 r2=nx.degree_assortativity_coefficient(g1) print ("%f"%r2) N2=nx.number_of_nodes(g2) print N2 r3=nx.degree_assortativity_coefficient(g2) print ("%f"%r3) can any one help me that, for solving my mistakes in this code
-35866392 0 My imagePickerController didFinishPickingMediaWithInfo newer get calledI try to write an App that needs a screen where you can take multible photos. I have used a code example from http://makeapppie.com/2015/11/04/how-to-make-xib-based-custom-uiimagepickercontroller-cameras-in-swift/.
It seems to be working OK, but my imagePickerController didFinishPickingMediaWithInfo newer get called. I am getting an error message from Xcode "Snapshotting a view that has not been rendered results in an empty snapshot. Ensure your view has been rendered at least once before snapshotting or snapshot after screen updates." It sounds to me like this could be the problem, and I have googled it, but havn't gotten any wiser. A lot of people write it's an Apple bug and I havn't found anybody offering a solution.
So do anybody know if it is the Xcode error that is my problem, and in that case have a solution for that or have I written something wrong in my code:
import UIKit class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, CustomOverlayDelegate { var picker = UIImagePickerController() @IBAction func shootPhoto(sender: AnyObject) { if UIImagePickerController.availableCaptureModesForCameraDevice(.Rear) != nil { picker = UIImagePickerController() //make a clean controller picker.allowsEditing = false picker.sourceType = UIImagePickerControllerSourceType.Camera picker.cameraCaptureMode = .Photo picker.showsCameraControls = false //customView stuff let customViewController = CustomOverlayViewController( nibName:"CustomOverlayViewController", bundle: nil ) let customView:CustomOverlayView = customViewController.view as! CustomOverlayView customView.frame = self.picker.view.frame customView.cameraLabel.text = "Hello Cute Camera" customView.delegate = self //presentation of the camera picker.modalPresentationStyle = .FullScreen presentViewController(picker, animated: true,completion: { self.picker.cameraOverlayView = customView }) } else { //no camera found -- alert the user. let alertVC = UIAlertController( title: "No Camera", message: "Sorry, this device has no camera", preferredStyle: .Alert) let okAction = UIAlertAction( title: "OK", style:.Default, handler: nil) alertVC.addAction(okAction) presentViewController( alertVC, animated: true, completion: nil) } } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { print("didFinishPickingMediaWithInfo") let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage //get the image from info UIImageWriteToSavedPhotosAlbum(chosenImage, self,nil, nil) //save to the photo library } //What to do if the image picker cancels. func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } //MARK: Custom View Delegates func didCancel(overlayView:CustomOverlayView) { picker.dismissViewControllerAnimated(true, completion: nil) print("dismissed!!") } func didShoot(overlayView:CustomOverlayView) { picker.takePicture() overlayView.cameraLabel.text = "Shot Photo" print("Shot Photo") } func weAreDone(overlayView: CustomOverlayView) { picker.dismissViewControllerAnimated(true, completion: nil) print("We are done!") } }
-31242924 0 jQuery hide the divs based on the classes getting from server I have 3 div blocks. Based on the response getting from my AJAX request, I want to show or hide the specific block. Suppose I have gotten the response in JSON format like this:
var response = [{ "class":[ "firstBlock", "secondBlock" ] }] <div class="mianBlock"> <div class="firstBlock"> div content goes here </div> <div class="secondBlock"> div content goes here </div> <div class="thirdBlock"> div content goes here </div> </div> Using jQuery, how do I hide the 2 blocks?
-8754679 0//global flag to check condition var flag = true; $('#yourelement').click(function(){ if(flag == true){ flag = false; $('#yourotherelement').attr('rel', newValue); }else{ flag = true; $('#yourotherelement').attr('rel', oldValue); } });
-21879864 0 Check my library https://github.com/sergey-miryanov/linden-google-play. Now it supports Leaderboard, Achievements and CloudSave. Another my lib https://github.com/sergey-miryanov/linden-google-iap support in-app purchases for GooglePlay.
-17053885 0 ERROR - The specified data type is not valid. [ Data type (if known) = varchar ]I have recently installed SQL 2008 R2
CREATE TABLE TPERSONS( personid int PRIMARY KEY NOT NULL, lastname varchar(50) NULL, firstname varchar(50) NULL, salary money NULL, managerid int NULL -- foreign key to personid ) I do not understand why I receive this error.
Major Error 0x80040E14, Minor Error 26302 ) The specified data type is not valid. [ Data type (if known) = varchar ]
-18176980 0 You would have to have the @interface and @implementation have the same class name. Aside from that, it does not matter what file the @interface or @implementation is in as long as the @interface is accessable from the file the @implementation is in (in the same file or #imported.
So in your case, if you did @interface ReceiverViewController... you would be fine.
One reason for using different tablespaces would be a desire to use tablespace transportation for moving data between databases. If you have a limited set of data that you want to move without having to export and import it then tablespace transport is a good option, particularly if it is important for testing reasons that the data have exactly the same physical structure as the source system (for performance analysis work, for example).
-32068613 0May be unrelated to performance, but the code as it written now has strange parallelization structure.
I doubt it can produce correct results, because the while loop inside the parallel does not have barriers (omp master does not have barrier, omp for nowait also does not have barrier).
As a result, (1) threads may start omp for loop before the master thread finishes Tree.PreProcessing(), some threads actually may execute omp for any number of times before the master works on single pre-processing step; (2) master may run Tree.PropagatePositions() before other threads finish the omp for; (3) different threads may run different time steps; (4) theoretically the master thread may finish all steps of the while loop before some thread even enters parallel region, and thus some iterations of the omp for loop may be never executed at all.
Or am I missing something?
-3765952 0 ipad - keyboard inside popover?Is it possible to have the keyboard show inside a UIPopOver instead of filling the screen width?
something like the image...

I have an ASP.Net MVC3 application (it doesn't matter if it is ASP.NET MVC, PHP or RAILS coz in the end it is serving out plaing HTML) which is using jquery mobile and works great in all mobile browsers. The next step for me is to create a native ios app using Phonegap.
My guess is all I have to do is in the html page which I put in Phonegap, I will hook into page load event and dynamically load the contents of my MVC view from a remote server.
But I am looking for some examples if anyone else has done something similar.
-Thanks in advance Nick
UPDATE: I was able to accomplish this by writing the following index.html page. Hope it helps someone else.
STILL ISSUES THOUGH : But having done this...as you may notice I am requesting my ASP.NET MVC page via http://IP:8081 URL. This works fine and it loads my page too...but it is not jquery mobile formatted. So, if someone can help me out here, it will be great.
EXPLANATION : Since, the ajax.responseText contains the entire HTML starting from the <!DOCTYPE html> tag... I think it is pretty obvious that I end up inserting an entire HTML page inside my <div data-role="page" id="home"> tag which is obviously wrong but I don't have a solution for it yet :(
<!DOCTYPE html> <html> <head> <title>PhoneGap Ajax Sample</title> <meta name="viewport" content="width=device-width,initial-scale=1, target-densityDpi=device-dpi"/> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" /> <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script> <script type="text/javascript" src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript"> function onDeviceReady() { var ajax = new XMLHttpRequest(); ajax.open("GET", "http://192.168.2.30:8081/", true); ajax.send(); ajax.onreadystatechange = function () { alert(ajax.status); if (ajax.readyState == 4 && (ajax.status == 200 || ajax.status == 0)) { document.getElementById('home').innerHTML = ajax.responseText; } } } $(document).bind("mobileinit", function () { alert('mobileinit'); // Make your jQuery Mobile framework configuration changes here! $.support.cors = true; $.mobile.allowCrossDomainPages = true; }); document.addEventListener("deviceready", onDeviceReady, false); </script> </head> <body> <div data-role="page" id="home"> </div> <div data-role="page" id="search"> </div> <div data-role="page" id="recent"> </div> </body> </html>
-1318627 0 Looping with String.contains() is the way unless you want to move in some heavy artillery like Lucene.
-29423834 0 How to apply JSON data to an EmberJS Model AttributeI'm very new to JS and I'm retrying EmberJS due to the impending 2.0 but especially because of EMBER CLI which I really like the structure.
Anyways, I'm building a basic app and what I'm currently looking to do is make a JSON call to reddit to grab the subscriber number and apply that number to a models subscriber number attribute. I'll also be cycling through an array of models too.
So for my instance, I've got models of lets say sports teams. Each team as a subreddit and when someone clicks the league they want, I'll be displaying all of the teams in that league.
I've got the the JSON working from a pure JS aspect, and I've got the Ember app working w/o any JSON. So I'm just trying to figure out how to connect the two while also realizing I will probably need to do some tear down to properly connect the two.
So my question is, how do I go about selecting a single piece of data from Reddit API to a single model attribute?
Here is the JS I'm using currently to pull the subscriber number.
$.each( teamList, function( key, val ) { $.getJSON( "http://api.reddit.com/r/"+val+"/about", function foo(data) { $("#team").append(val + " : "); $("#team").append(data.data.subscribers + '<br>'); } ); }); My current ember model setup is normal, but I am using fixtures since all data is static other than this model attribute.
-31160772 0 how to create vertical scroll effect for slider using js ,html,csshttp://www.squarespace.com/ i want to create similar sliding effect for my website could someone suggest how to create such kind of effect I tried using fullpage.js but it doesnot give the same effect is there a plugin or js which could provide such kind of effect
-3322826 0The answer would be yes, assuming you consider this a good example of what you want to do:
http://pyjs.org/examples/Space.html
This browser-based version of Asteroids was created using Pyjamas, which enables you to write the code in python in one place, and have it run either on the browser, or on the desktop:
Having recently found Pyjamas, and also preferring to consolidate my code in one language (Python!) and location (instead of having some code server-side, and some browser/client-side, in different languages), it's definitely an exciting technology. Its authors have ported the Google Web Toolkit to Python, a really impressive feat, retaining the expressive power of Python (something like 80,000 lines of Java was shrunk to 8,000 lines of Python). More Pythonistas should know about it. :)
-10476158 0if (preg_match('/\b\d{4}-\d{2}-\d{2}\b/' $str)) { // ... } If the word boundary (\b) doesn't do the trick, you could try negative lookbehind and lookaheads:
if (preg_match('/(?<!\d)\d{4}-\d{2}-\d{2}(?!\d)/' $str)) { // ... } As an additional validation, you could use checkdate() to weed out invalid dates such as 9999-02-31 as mentioned in this answer.
We Have Contact Entities in contact Entitie one lookup filed company Name in that lookup having two values 1.Account and 2.Contact . When we are selecting contact show the address filed when we select account hide the address filed we needs to write the plugin to Execute that works. Kindly any one help me on the same.
Thanks!!
Rajesh Singh
-21176064 0You can use Regex when you search a string in MongoDB:
Query.Matches("story","<Regex for: moon or cow or Neil>"); Look here to see how to write a regex that matches multiple words. It's basically this:
^(?=.*\bmoon\b)(?=.*\bcow\b)(?=.*\bNeil\b) In conclusion:
collection.Find(Query.Matches( "story", "^(?=.*\bmoon\b)(?=.*\bcow\b)(?=.*\bNeil\b)")) .SetSortOrder(SortBy.Descending("Submitted")).Skip(skip).Take(limit);
-3867644 0 Grouped UITableView & edit-mode: strange behaviour recently I implemented an grouped UITableView with editing, but the problem is: if the UITableView is in edit-mode, the content of the cells is moved to the right and this looks really unattractive.
Thanks in advance.
Regards, Sascha
-9565209 0You can save popup window's text in webpart property in toolpart.
This property will be accessed in WebPart & ToolPart also.
For WebPart Properties see below example,
[Personalizable(PersonalizationScope.Shared)] [WebBrowsable(true)] [Category("Display")] [WebDisplayName("Popup Text")] [Description("You can configure this text from here in popup")] public string PopupText { get; set; } add above code in WebPart Class and use this "PopupText" property in assign Literal control OR direct render this property in overwrite Render method.
-33257995 0Navigate to closing/opening bracket feature in IntelliJ could also be useful for this. It works for XML/HTML, Java, etc. See documentation for more details.
The shortcuts are:
I guess you pass the wrong CGPoint coordinate to the hitTest:withEvent: method causing wrong behavior if the scroll view is scrolled.
The coordinate you pass to this method must be in the target views coordinate system. I guess your coordinate is in the UIScrollView's superview's coordinate system.
You can convert the coordinate prior to using it for the hit test using CGPoint hitPoint = [scrollView convertPoint:yourPoint fromView:scrollView.superview].
In your example you let the container view perform the hit testing, but the container can only see & hit the visible portion of the scroll view and thus your hit fails.
In order to hit subviews of the scroll view which are outside of the visible area you have to perform the hit test on the scroll view directly:
UIView *firstSubview = [_scrollView hitTest:number1RectanglePoint withEvent:nil]; UIView *fifthSubview = [_scrollView hitTest:number5RectanglePoint withEvent:nil];
-30948291 0 You can write some custom validation
validate do valid_phone_codes = [ "007", "042", ...] valid_phone_codes.each do |valid_code| # Also handle optional parenthesis return true if self.phone_number.starts_with?(valid_code, "(#{valid_code})") end errors.add(:phone_numbers, "Must start with a valid country code (one of #{valid_phone_codes.join(', ')}") false end Or if you prefer, you can declare this code in a function def valid_country_codes, and then add a line
validate :valid_country_codes
-15657151 0 It think you mean Sentinel nodes in a linked lists.
Some linked-list implementations put one or two extra nodes at the beginning and ending (or both of them) to implement some algorithms simpler. These nodes don't hold special data as a entry of data-structure. It's an alternative for usingNULL as first/last node indicators.

The std::list is supposed to be a list in the standards. It maybe uses sentinel nodes or not.
You might want to try parsing the HTML with jsoup and collect all the anchor tags from the page.
-8730788 0I did some of your work for you and found this date:duration function, which you seem to be trying to use. However, date:duration converts a number of seconds into a duration formatted string, whereas you want to find the difference (duration) between two datetime strings.
You probably want date:difference instead. If you read the documentation for this function/template, you'll find this about the arguments:
The two dates must both be right-truncated date/time strings in one of the formats defined in [XML Schema Part 2: Datatypes]. ... The permitted formats are as follows...
xs:dateTime (CCYY-MM-DDThh:mm:ss) ...
There are italics there in the original: CCYY-MM-DDThh:mm:ss except the T is not italicized. In other words, the time strings need a literal T between the date and the time, whereas yours have a space.
So I would suggest fixing that:
<start>2011-12-13T16:15:26</start> <end>2011-12-13T16:17:27</end> Pass the start and end strings as parameters to the template. You can do this by just passing the start and end element nodes, which will be automatically converted to strings based on their text content:
<xsl:variable name="time-diff-dur"> <xsl:call-template name="date:difference"> <xsl:with-param name="start" select="start" /> <xsl:with-param name="end" select="end" /> </xsl:call-template> </xsl:variable> <!-- The above returns a duration formatted string, so convert that to seconds: --> <xsl:variable name="time-diff-sec"> <xsl:call-template name="date:seconds"> <xsl:with-param name="seconds" select="$time-diff-dur" />? </xsl:call-template> </xsl:variable> This code assumes that the context node is the parent of the <start> and <end> elements. After the above code, the variable $time-diff-sec will contain a result tree fragment, which can be converted to a number using number($time-diff-sec) if necessary.
Let us know whether that works. If not, state specifically what the result was and how it differs from what you expected.
Update:
I just noticed that you are using xsltproc (which uses libxslt). According to this documentation, libxslt supports date:difference (and date:seconds) natively. So you can call these functions as functions instead of defining a named template and calling it as a template. That would be a lot less code for you, albeit less portable:
<xsl:variable name="time-diff-sec" select="date:seconds(date:difference(start, end))" /> As before, you will need to declare the date namespace prefix somewhere, usually on your xsl:stylesheet element:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:date="http://exslt.org/dates-and-times" extension-element-prefixes="date">
-24645174 0 How to parse json response from ajax? I am new to json and ajax this is my first example can any one help me out with this.
$.ajax({ type: "GET", url: "ajs/index", dataType: "JSON", success: function(data) { var obj = JSON.parse(data); $("#result").html(obj.name); } }); The output of data is of the form:
[Object {id=10, name="ss", title="ss", content="h", ...}, Object {id=12, name="lo", title="gi", content="c", ...}, Object {id=13, name="lo", title="gi", content="c", ...}, Object {id=14, name="lo", title="gi", content="c", ...}, Object {id=15, name="n", title="m", content="m", ...}] The output of obj(after parsing) is of the form:
[{"id":10,"name":"ss","title":"ss","content":"h","created_at":"2014-07-07T10:07:02.398Z","updated_at":"2014-07-07T10:07:02.398Z"}]{"id":12,"name":"lo","title":"gi","content":"c","created_at":"2014-07-08T05:26:05.816Z","updated_at":"2014-07-08T05:26:05.816Z"} when i use obj.name it is nt displaying any data how can i display all my data.
-40959957 0 Linux Timers in CI am working on some Linux applications that uses timers.I need to change the timer interval during runtime.So is there any API that could detect whether any previous timer is running or not.My idea is like i will detect any previous running timer and will delete it and then will re-create the timer with new time value.
I am using timer_create(),timer_settime() for timer creation and timer starting.
Thanks&Regards Amit Kumar
-13998098 0 MATLAB - Sort a matrix based off how a vector is sortedPossible Duplicate:
How can I sort a 2-D array in MATLAB with respect to one column?
Sort a matrix with another matrix
I have a vector 'A' of 429 values and a matrix 'B' of 429x200 values. Rows in A and B are share the same indices. My vector 'A' contains values 1:1:429 but they are randomly ordered throughout the vector. I want to reorder A so that it indexes in order from 1 to 429 and I also want to sort the rows in matrix 'B' in the same order as the newly sorted 'A'.
Can this be done quick and easy without a for-loop?
Here's an example to illustrate my point:
A = 5 3 1 2 4 B = 3 7 0 4 6 1 2 5 0 8 4 0 2 0 0 3 0 1 0 5 2 2 3 4 4 sortedA = 1 2 3 4 5 sortedB = 4 0 2 0 0 3 0 1 0 5 1 2 5 0 8 2 2 3 4 4 3 7 0 4 6 Thank you everyone!
-3635013 0 Add a row to h:dataTable via AJAX with request-scoped bean without losing the row dataI think the title tells it all: I want to add a row to dataTable over AJAX. The datatable has input fields where user can put text. As simple as that, a pretty common case.
With session-scoped bean this no issue, as the same bean is updated over and over again. However, I want to do this in request scope. For each request, I guess I want to create a new bean and to populate it with the values from my form. Then I want my commandButton's action to add a new row, finally render the dataTable over AJAX as usual.
The issue is that I don't know how to make JSF fill the newly-created request-bean with the current data from the dataTable component?
There was a similar question asked and answered. However, that solution seems to reload the contents of the dataTable each time it is refreshed and manually inserts empty elements for the newly-inserted rows like this:
// Preserve list with newly added items. ror (int i = 0; i < (Integer) count.getValue(); i++) { list.add(new Item()); } To me, it seems that this approach also wipes the possible changes that the user did to rows (new and old)... if he doesn't first save them.
Any pointers?
-36249651 0Simplest way to split array into chunks is array_chunk:
$farmland = array("Duck","Fox","Goose","Cow","Cat","Rabbit","Bull","Mouse","Sheep","Goat"); $chunks = array_chunk($farmland, 5); // get chunks with size of 5 print_r($chunks);
-24058310 0 The scope of count is just the single child you are processing. Move it to a higher scope:
$(xml).find('parent').each(function () { var body = $('body').addClass('nobg'); var count = 1; $(xml).find('child').each(function() { if ($(this).attr('title') > '') { var title = $('<p></p>').appendTo(body); headline.attr('id'), (count++)); } }) }) Also, to be on the safe side, I would replace count++ with ++count as you need it to increment before it is used. This is pure readability, though, in your case.
byte[] temp1 = BitConvert.GetBytes(num1); byte[] temp2 = BitConvert.GetBytes(num2); Array.Copy(temp1, 0, buf, 0, 4); Array.Copy(temp2, 0, buf, 4, 4); Array.Copy(buf, 8, headers.key3, 0, 8) buf[16] = 0; Array.Copy(buf, target, 16) target[16] = 0; Using MD5 hasher = new MD5CryptoServiceProvider() target = hasher.ComputeHash(buf); End Using
-3056997 0 My vote would be for XStream. The lack of generics support is a small price to pay for the amount of flexibility it offers. You can also easily implement generics by serializing the generic class type at serialization time, or build this into your domain objects. E.g.
class Customer { List<Order> orders; public List<Order> getOrders() { return orders; } } In the stream, the element type denotes the type of each object. When the type is an abstract type or interface, the element listed with the implementing class, unless that has been specified as the default for that interface type. (E.g. ArrayList as the default for instances of static type List.)
Generics are "rose coloured glasses" in java - they don't really change what you are seeing, just how you see it. The objects would be sent over the wire exactly the same if they were sent with generics support or not.
-26170064 0Is there an error of some sorts, or you just don't understand how that works?
navigator.webkitGetUserMedia expects 3 arguments. One for configuration data, one for a function to call on success (a success callback) and one to call on error.
Note that it expects a function. This code passes a reference to the function by name; it will be called with the appropriate parameter (from within webkitGetUserMedia).
Consider this code, it works in the same manner:
function hello(subject) { alert("Hello, " + subject + "!"); } function passWorldTo(callback) { callback("world"); } passWorldTo(hello); I have the situation where a list must contains at least the values of another list. So imagine we have list A with values 1, 2, 3. This is the list with the required values.
List B has the values 1, 5, 6, 7
List C has the values 1, 2, 3, 4, 7
List D has the values 2, 5, 6
In this situation I only want List C, since this is the only list which contains the values 1, 2 end 3.
I've tried this, but this doesn't work since it is always true:
query = from doc in query let tagIds = from t in doc.Tags select t.Id where parameters.TagIds.Except(tagIds).Count() <= parameters.TagIds.Count() select doc; And when using this:
query = from doc in query let tagIds = from t in doc.Tags select t.Id where !parameters.TagIds.Except(tagIds).Any<int>() select doc; I only get the lists where the list matches exactly the 'required' list.
My question is, how can I solve my situation in a Linq 2 SQL query?
-16569293 0 MySQL: Limit by a group of rows, not by a rowI have a MySQL table like the following. The id and name fields are just here to help identify the row, l represents many other fields whit not relevant data, and lat and lng are used to find duplicated entries.
CREATE TABLE v (`id` int, `lat` int, `lng` int, `l` varchar(3), `name` varchar(8)) ; INSERT INTO v (`id`, `lat`, `lng`, `l`, `name`) VALUES ( 1, 12, 12, 'a', 'group1-1'), ( 2, 12, 12, 'b', 'group1-2'), ( 3, 13, 12, 'c', 'single1'), ( 4, 13, 13, 'd', 'group2-1'), ( 5, 13, 13, 'e', 'group2-2'), ( 6, 13, 13, 'f', 'group2-3'), ( 7, 10, 13, 'g', 'group3-1'), ( 8, 10, 13, 'h', 'group3-2'), ( 9, 11, 12, 'h', 'group4-1'), (10, 11, 12, 'h', 'group4-2'), (11, 10, 14, 'i', 'group5-1'), (12, 10, 14, 'j', 'group5-2'), (13, 10, 14, 'j', 'group5-3') ; Now I want to get all rows where there is more than one row with the same lat and lng values (let's call that a group):
SELECT v.* FROM v INNER JOIN ( SELECT lat, lng FROM v GROUP BY lat, lng HAVING COUNT(*) > 1 ) AS vg USING (lat, lng) ORDER BY name ; Outputs:
ID LAT LNG L NAME 1 12 12 a group1-1 2 12 12 b group1-2 4 13 13 d group2-1 5 13 13 e group2-2 6 13 13 f group2-3 7 10 13 g group3-1 8 10 13 h group3-2 9 11 12 h group4-1 10 11 12 h group4-2 11 10 14 i group5-1 12 10 14 j group5-2 13 10 14 j group5-3 Works well so far, all but the "single1" rows are selected and ordered by group.
Now I want to add a limit to form different pages of this data. But all rows of the same group need to be on the same page (but not one page per group and it doesn't matter how many rows actually are on one page - just not too many). I don't see this done with a LIMIT statement, so I started to write my own:
SET @grp := 0, @last_lat := '', @last_lng := ''; SELECT * FROM ( SELECT v.*, @grp := IF((@last_lat = lat) && (@last_lng = lng), @grp, @grp + 1) AS grp, @last_lat := lat AS llat, @last_lng := lng AS llng FROM v INNER JOIN ( SELECT lat, lng FROM v GROUP BY lat, lng HAVING COUNT(*) > 1 ) AS vg USING (lat, lng) ORDER BY lat, lng ) AS vv WHERE grp BETWEEN 0 AND 7 ORDER BY grp ; This query whit out the WHERE part outputs this data:
ID LAT LNG L NAME GRP LLAT LLNG 1 12 12 a group1-1 6 12 12 2 12 12 b group1-2 6 12 12 5 13 13 e group2-2 7 13 13 6 13 13 f group2-3 7 13 13 4 13 13 d group2-1 7 13 13 7 10 13 g group3-1 8 10 13 8 10 13 h group3-2 8 10 13 10 11 12 h group4-2 9 11 12 9 11 12 h group4-1 9 11 12 13 10 14 j group5-3 10 10 14 11 10 14 i group5-1 10 10 14 12 10 14 j group5-2 10 10 14 The idea is to change the values in the line WHERE grp BETWEEN 0 AND 7 for each page. But the numbers from the group don't start at 1 and I can't see why (and that makes it unusable for the first page). The Start number is different depending on how many group are in the whole data. So what I need to have, is that the grp column start whit 1 and then continues whit always +1.
What is wrong with this query and are there any better ways to do this?
You can play whit this query here: http://sqlfiddle.com/#!8/86d3c/2
-11301960 0Using one floated span with a border:
<div class="heading"> <span></span> <h3>Heading<h3> </div> .heading { width: 100%; text-align: center; line-height: 100%; } .heading span { float: left; margin: 20px 0 -8px; border: 1px solid; width: 100%; } .heading h3 { display: inline; padding: 0px 0px 0 20px; width: auto; margin: auto; } The negative base margin on the span may need to be adjusted for different heading sizes. , The background colour of the heading should match the background of the overall container.
-8218801 0You should move the time logic into your database query - there's no point in fetching ALL rows, only to throw away some (most? all?) of the rows if there's nothing to do:
SELECT * FROM users WHERE `time` < (now() - INTERVAL 3 DAY) Once that's done, I'd suggest moving the actual mail() portion out of the database fetching loop, so that you can batch together each user's brochures first:
$users = array(); while($row = mysql_fetch_array($time_query_result)) { if (!array_key_exists($row['userID'], $users)) { $users[$row['userID']] = array('email' => $row['email'], 'brochures' => array()); $users[$row['userID']]['brochures'] = array('b' => $row['brochures'], 't' => $row['time']); } } You'd then loop over this $users array to build emails for the users:
foreach ($users as $user) { $text = '<html><body><p>Brochure reminder</p>'; $i = 1; foreach ($user['brochures'] as $brochure) { $text .= 'Brochures:<br />'.$i++ .$row['b']. $row['b']; } $text .= '</body></html>'; mail($user['email'], $subject, $text, $headers); } This way, you fetch all the user details in one go. You then build a SINGLE email to each user, listing all of their brochures, and (hopefully) problem solved.
-4867905 0Minimax with Alpha-beta pruning that Lirik mentioned is a good place to start, but it takes some time to wrap your mind around if you're not familiar with it.
Alternatively you can think about how you would play the game if you had a perfect memory and could do fast calculations and try to implement that. The upside is that's usually easier to understand.
Minimax would probably result in shorter but more difficult to understand (for those unfamiliar with it) code that depending on the game, could result in playing a perfect game if the game is simple enough (however it also has the disadvantage of favoring not losing to winning because it assumes the opponent will be playing perfectly as well)
Since it sounds like it's a game of complete information (the whole board is visible to all players at all times) a properly implemented Minimax with infinite look-ahead could give an AI that would never lose (assuming infinite computation time). In games using Minimax the difficulty level is often determined by how many moves ahead the algorithm looks at. It gets exponentially slower the more steps there are, so you will run into a hardware limitation if the game isn't super simple (which is why there isn't a perfect Chess playing AI yet, I think last I checked it would take a couple thousand years on the fastest computer at the time of the article I read, sorry no citations)
-34399776 0 Laravel 4.2 custom error handler not workingI am trying to handle InvalidArgumentException in a custom way. In app/start/global.php I have the following code block after the built in App::error(Exception $exception... block:
App::error(function(InvalidArgumentException $exception, $code){ // die('last'); $exceptionData['exception'] = $exception; $exceptionData['code'] = $code; ExceptionNotificationHandlerController::notify($exceptionData); }); die()ing, breakpoints, etc all suggest to me that it never goes into that block of code when I throw an InvalidArgumentException. Help?
-26220857 0You could add one event handler for each container you actually want to receive the event in (if this is feasable in your setup):
(somewhere:)
(function() { var container = document.getElementById('mainwrap'); container.addEventListener('click',handler,false); function handler(e) { e = e || window.event; var element = e.target || e.srcElement; console.log("Element actually clicked: ", element); console.log("Container receiving event: ", container); } })(); Or expand to (can register handler for multiple containers..):
function registerHandlerForContainer(container_id, handler) { var container = document.getElementById(container_id); container.addEventListener('click',delegating_handler,false); function delegating_handler(e) { handler(container, e); } } function handler(container, e) { e = e || window.event; var element = e.target || e.srcElement; console.log("Element actually clicked: ", element); console.log("Container receiving event: ", container); } registerHandlerForContainer('mainwrap', handler);
-34296585 0 SparkR error in Rstudio and Rcmd head(df) SparkR error
Error in invokeJava(isStatic = TRUE, className, methodName, ...) : org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 6.0 failed 1 times, most recent failure: Lost task 0.0 in stage 6.0 (TID 6, localhost): java.io.IOException: Cannot run program "Rscript": CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(Unknown Source) at org.apache.spark.api.r.RRDD$.createRProcess(RRDD.scala:407) at org.apache.spark.api.r.RRDD$.createRWorker(RRDD.scala:445) at org.apache.spark.api.r.BaseRRDD.compute(RRDD.scala:62) at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:300) at org.apache.spark.rdd.RDD.iterator(RDD.scala:264) at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38) at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:300) at org.apache.spark.rdd.RDD.iterator(RDD.scala:264) at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38) at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.sc
-12064456 0 This seemed to worked for me:
string schemaXPath = "//parent[@name='Iam']//toy[@name='wii']"; XPathNavigator schemaNavigator = oXmlDocument.CreateNavigator(); XPathNodeIterator nodeIter = schemaNavigator.Select(schemaXPath, namespaceMgr); while (nodeIter.MoveNext() == true) { Console.WriteLine(nodeIter.Current.Name); } Hopefully this is what you're looking for.
Cheers!
-17145193 0 How to let a specific android device (fonepad) use different layout folderI'm working on an Android app that has different layouts for phones (designed for portrait) and for tablets (designed for landscape).
Now I want to support the Asus Fonepad as a phone but since it has the size and resolution of a 7 inch tablet it always uses the layouts in the layout-sw600dp folder. But the fonepad understands itself as a phone and shows the fullscreen text edit window whenever text input is used in landscape.
How can I make this device use layouts and values from the phones and not from the -sw600dp folders? Is this even possible?
-38976399 0Answering question 2, with pandas 0.18.0 you can do:
store = pd.HDFStore('compiled_measurements.h5') for filepath in file_iterator: raw = pd.read_csv(filepath) store.append('measurements', raw, index=False) store.create_table_index('measurements', columns=['a', 'b', 'c'], optlevel=9, kind='full') store.close() Based on this part of the docs.
Depending on how much data you have, the index creation can consume enormous amounts of memory. The PyTables docs describes the values of optlevel.
-11384726 0Use EXPLAIN to see how MySQL handles the queries, it might give you a clue.
Also, try some other characters. Maybe MySQL is misinterpreting one of those as having a percent sign in it.
-36052505 0In standard css this would be:
button button But you have to be careful on other pages it can also select 3rd, 4th and so on.
That is to say, there is no ordinality in standard css - only classes and id's and their hierarchy level (parent/child) relationships, unlike xpath.
-39994056 0You are appending the same class : color-9999CC to all your rect elements, so once you hover the last legend item having color : #9999CC all rect element will be selected.
To create the required class properly, you can add the corresponding color info to each element in your layers object while creating it.
I added a color property that has as value the color of the corresponding headers item:
var layers = d3.layout.stack()( headers.map(function (count) { return fData.map(function (d,i) { return { x: d.orders, y: +d[count] , color: colorScale(count)}; /*color = current headers item color */ }); })); Then while creating your rect items you can add to each element a class by accessing its color property like this:
var rect = layer.selectAll("rect") .data(function (d) { return d; }) ..... .attr("class", function (d) { return "rect bordered " + "color-" +d.color.substring(1); }); var margin = {top:10, right: 10, bottom: 80, left: 50}, width =960, height=650; var svg = d3.select("body") .append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); var fData = [{"orders":"A","Total_Orders":76,"A_Lines":123,"B_Lines":0,"C_Lines":0,"D_Lines":0,"Total_Lines":123,"Total_Units":3267}, {"orders":"B","Total_Orders":68,"A_Lines":0,"B_Lines":107,"C_Lines":0,"D_Lines":0,"Total_Lines":107,"Total_Units":3115}, {"orders":"C","Total_Orders":81,"A_Lines":0,"B_Lines":0,"C_Lines":123,"D_Lines":0,"Total_Lines":123,"Total_Units":3690}, {"orders":"D","Total_Orders":113,"A_Lines":0,"B_Lines":0,"C_Lines":0,"D_Lines":203,"Total_Lines":203,"Total_Units":7863}, {"orders":"AB","Total_Orders":62,"A_Lines":70,"B_Lines":76,"C_Lines":0,"D_Lines":0,"Total_Lines":146,"Total_Units":1739}, {"orders":"AC","Total_Orders":64,"A_Lines":77,"B_Lines":0,"C_Lines":79,"D_Lines":0,"Total_Lines":156,"Total_Units":2027}, {"orders":"AD","Total_Orders":100,"A_Lines":127,"B_Lines":0,"C_Lines":0,"D_Lines":144,"Total_Lines":271,"Total_Units":6467}, {"orders":"BC","Total_Orders":64,"A_Lines":0,"B_Lines":80,"C_Lines":84,"D_Lines":0,"Total_Lines":164,"Total_Units":1845}, {"orders":"BD","Total_Orders":91,"A_Lines":0,"B_Lines":108,"C_Lines":0,"D_Lines":135,"Total_Lines":243,"Total_Units":4061}, {"orders":"CD","Total_Orders":111,"A_Lines":0,"B_Lines":0,"C_Lines":132,"D_Lines":147,"Total_Lines":279,"Total_Units":5011}, {"orders":"ABC","Total_Orders":45,"A_Lines":58,"B_Lines":63,"C_Lines":55,"D_Lines":0,"Total_Lines":176,"Total_Units":1245}, {"orders":"ABD","Total_Orders":69,"A_Lines":105,"B_Lines":87,"C_Lines":0,"D_Lines":116,"Total_Lines":308,"Total_Units":4538}, {"orders":"ACD","Total_Orders":66,"A_Lines":91,"B_Lines":0,"C_Lines":88,"D_Lines":132,"Total_Lines":311,"Total_Units":4446}, {"orders":"BCD","Total_Orders":68,"A_Lines":0,"B_Lines":84,"C_Lines":95,"D_Lines":111,"Total_Lines":290,"Total_Units":4187}, {"orders":"ABCD","Total_Orders":56,"A_Lines":96,"B_Lines":90,"C_Lines":93,"D_Lines":143,"Total_Lines":422,"Total_Units":6331}] var headers = ["A_Lines", "B_Lines", "C_Lines", "D_Lines"]; var colors = ["#9999CC", "#F7A35C", "#99CC99", "#CCCC99"]; var colorScale = d3.scale.ordinal() .domain(headers) .range(colors); var layers = d3.layout.stack()( headers.map(function (count) { return fData.map(function (d,i) { return { x: d.orders, y: +d[count] , color: colorScale(count)}; }); })); //StackedBar Rectangle Max var yStackMax = d3.max(layers, function (layer) { return d3.max(layer, function (d) { return d.y0 + d.y; }); }); // Set x, y and colors var xScale = d3.scale.ordinal() .domain(layers[0].map(function (d) { return d.x; })) .rangeRoundBands([25, width], .08); var y = d3.scale.linear() .domain([0, yStackMax]) .range([height, 0]); // Define and draw axes var xAxis = d3.svg.axis() .scale(xScale) .tickSize(1) .tickPadding(6) .orient("bottom"); var yAxis = d3.svg.axis() .scale(y) .orient("left") .tickFormat(d3.format(".2s")) var layer = svg.selectAll(".layer") .data(layers) .enter().append("g") .attr("class", "layer") .style("fill", function (d, i) { return colorScale(i); }); var rect = layer.selectAll("rect") .data(function (d) { return d; }) .enter().append("rect") .attr("x", function (d) { return xScale(d.x); }) .attr("y", height) .attr("width", xScale.rangeBand()) .attr("height", 0) .attr("class", function (d,i) { return "rect bordered " + "color-" +d.color.substring(1); }); layer.selectAll("text.rect") .data(function (layer) { return layer; }) .enter().append("text") .attr("text-anchor", "middle") .attr("x", function (d) { return xScale(d.x) + xScale.rangeBand() / 2; }) .attr("y", function (d) { return y(d.y + d.y0) - 3; }) .text(function (d) { return d.y + d.y0; }) .style("fill", "4682b4"); //********** AXES ************ svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis) .selectAll("text").style("text-anchor", "end") .attr("dx", "-.8em") .attr("dy", ".15em") .attr("transform", function (d) { return "rotate(-45)" }); svg.attr("class", "x axis") .append("text") .attr("text-anchor", "end") // this makes it easy to centre the text as the transform is applied to the anchor .attr("transform", "translate(" + (width / 2) + "," + (height + 60) + ")") // centre below axis .text("Order Velocity Group"); svg.append("g") .attr("class", "y axis") .attr("transform", "translate(20,0)") .call(yAxis) .append("text") .attr("transform", "rotate(-90)") .attr({ "x": -75, "y": -70 }) .attr("dy", ".75em") .style("text-anchor", "end") .text("No. Of Lines"); //********** LEGEND ************ var legend = svg.selectAll(".legend") .data(headers) .enter().append("g") .attr("class", "legend") .attr("transform", function (d, i) { return "translate(" + (headers.length-(i+1))*-100 + "," + (height + 50) + ")"; }); legend.append("rect") .attr("x", width - 18) .attr("width", 18) .attr("height", 18) .style("fill", function (d, i) { return colors[i]; }) .on("mouseover", function (d, i) { svg.selectAll("rect.color-" + colors[i].substring(1)).style("stroke", "blue"); }) .on("mouseout", function (d, i) { svg.selectAll("rect.color-" + colors[i].substring(1)).style("stroke", "white"); }); legend.append("text") .attr("x", width - 24) .attr("y", 9) .attr("dy", ".35em") .style("text-anchor", "end") .text(function (d) { return d; }); transitionStacked(); function transitionStacked() { y.domain([0, yStackMax]); rect.transition() .duration(500) .delay(function (d, i) { return i * 10; }) .attr("y", function (d) { return y(d.y0 + d.y); }) .attr("height", function (d) { return y(d.y0) - y(d.y0 + d.y); }) .transition() .attr("x", function (d) { return xScale(d.x); }) .attr("width", xScale.rangeBand()); }; <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.3.0/d3.min.js"></script> <body></body> According to the Molliza Developer Network documentation:
The HTML
<meta>element represents any metadata information that cannot be represented by one of the other HTML meta-related elements (<base>,<link>,<script>,<style>or<title>).
Charset (Character set) is a set of encodings used to represent characters to the screen. UTF-8 is a specific type capable of encoding all possible characters, or code points, in Unicode.
Q: In the above code what is the meaning of
<meta charset="utf-8"/>?
Adding this attribute declares, but don't guarantee the character encoding used for that specific web document.
Q: If i remove it from the code, there is no error.
Remember when I said there was no guarantee in the previous sentence? This is because the <meta ..> tag is only part of the algorithm that browsers use to apply. Again, referencing the mozilla docs, The HTTP Content-Type header and any BOM elements have precedence over this element. For a more comprehensive understanding, see whatwg.org.
You may ask then what is the point of implementing that line at all if the browser can perform shallow reasoning to include the charset encoding by default. The answer is simple:
I'm not quite sure what you want to do. Do you help aligning the divs in a row or vertically aligning the image in its own row? If the latter, you want to use vertical-align (http://www.w3schools.com/cssref/pr_pos_vertical-align.asp).
-12188339 0 Java write to StdinSo I have imported a jruby interpreter as a library to run an external ruby application. However I need to interact with the ruby application in some way. Right now I have the ruby application outputting information on stdout and requesting user options in stdin.
So if I want java to be able to handle inserting the options instead of a user, I'll need a way that I can write to the stdin somehow from java to choose the options. Does anyone know how I can do this? Or even a better way to do this?
I'm calling jruby like so:
String[] newargs = new String[2]; newargs[0] = "-S"; newargs[1] = "path_to_some_rubyfile.rb" org.jruby.Main jruby = new org.jruby.Main(); ruby.main(newargs); The ruby app outputs stuff like this:
How do you feel today? (1) Happy (2) Sad And then waits for the user input to enter 1 or 2. But I would like Java to input these options instead of having a user do it.
-36071414 0Check web.config file for invalid entries. For example, having "entityFramework" tag there causes this problem for me.
-36369918 0 Resizing C# Windows FormNot sure if this is the standard way of creating a form and opening, but the code the below does display the form properly. My problem is that I can't programatically change it's size. I'm guessing it has to do with the scope, "main" creates the form object, but I'd like to be resize it in the scope where it actually gets initialized (instead of in the [Design] tab of MS Studio) but I can't find the object/handle to it!
main.cs: class MainProgram { static void Main(string[] args) { // Create Form Object and Open Gui for user MainForm newFrm = new MainForm(); // Mainform is type Systems.Windows.Forms.Form Application.Run(newFrm); } } formFile.cs: public partial class MainForm : Form { public MainForm() { InitializeComponent(); //TODO: How to Resize Form from here? //this.Size.Height = 100; // ERROR! } }
-3115909 0 How to design a flash based website when user has different screen size and different resolution? I am developing a flash based website using mxml. My monitor's resolution is 1280x768 and is widescreen. The problem is while it appears properly in my screen it doesn't appear properly in others. Which is the best approach to solve the problem ?
I have 2 in mind.
- Let scrollbars take care of it : If the screen is 14 inch screen with 800x600 resolution it appears zoomed in. So thats a problem
- Get screen resolution and resize using scaleX and scaleY : The graphic components will get resized but fonts give problem.
Which is the best approach among these ? If there is a better approach please mention. Thanks
-14338792 0Unless you are doing something really special with it, you should not directly read the app.config file, but use ConfigurationManager class to read from it. If you really want to read it as XML, use XmlDocumen.Load() function, but plaease keep in mind that parsing config as an XML file is an unintended way of use.
Install the New Relic Standard addon - that will give you insight into your application and what's going on. The 'Dynos' tab will show you memory utilisation of your application, it sounds like an awfully high memory utilisation for the level of traffic you're reporting but it depends on your application - if you're seeing memory errors in the log then performance will be suffering see http://devcenter.heroku.com/articles/error-codes#r14__memory_quota_exceeded
Are you using any kind of error handling? You could install the Airbrake addon so you get notification of errors or use the Exception Notifier gem which will email you errors as they occur. Once you have these in place you'll know what's occuring - whether it's in the application or if you don't receive any then it's outside factors, like the visitors internet connection etc.
-26314758 0this could be easily done with just editing your css
$('.clampjs').click( function() { $(this).css({ //changes the css of the clicked content. 'height':'100px', //give what ever height you want. 'overflow':'hidden' }); }); just now tested in my page it works...
-11286379 0int main () { char *arr= "abt"; // This could be OK on some compilers ... and give an access violation on others arr++; *arr='e'; // This is where I guess the problem is occurring. cout<<arr[0]; system("pause"); } In contrast:
int main () { char arr[80]= "abt"; // This will work char *p = arr; p++; // Increments to 2nd element of "arr" *(++p)='c'; // now spells "abc" cout << "arr=" << arr << ",p=" << p << "\n"; // OUTPUT: arr=abc,p=c return 0; } This link and diagram explains "why":
-27055907 0http://www.geeksforgeeks.org/archives/14268
Memory Layout of C Programs
A typical memory representation of C program consists of following sections.
- Text segment
- Initialized data segment
- Uninitialized data segment
- Stack
- Heap
And a C statement like const char* string = "hello world" makes the string literal "hello world" to be stored in initialized read-only area and the character pointer variable string in initialized read-write area.
You cannot get the data from grid for searching, you need to store you data some where for using search. That is to store in a ViewState, Session or call DataBase on every search. Bellow code show data stored in a ViewState, you can acces your data any time by just using GridViewData where you can done search. (if you have very large amount of data first preference is calling data from database on every search.)
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { GridView1.DataSource = GridViewData; GridView1.DataBind(); } } public DataSet GridViewData { get { if (ViewState["GridViewData"] == null) { String str = "select * from tblEmployee where (Name like '%' + @search + '%')"; SqlCommand xp = new SqlCommand(str, objsqlconn); xp.Parameters.Add("@search", SqlDbType.NVarChar).Value = TextBox1.Text; objsqlconn.Open(); xp.ExecuteNonQuery(); SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = xp; DataSet ds = new DataSet(); da.Fill(ds, "Name"); objsqlconn.Close(); ViewState["GridViewData"] = ds; } return (DataSet)ViewState["GridViewData"]; } }
-1568664 0 Assuming that:
Your best solution is probably:
Rather than keeping a list of all the swaps you do as they are performed, compare your starting and finishing data at the end of the day, and then generate the swaps you would need to make that change. This would ignore any locations in the list that remain unchanged, even if they are only unchanged because a series of swaps "undid" some change. If you have your data take the form of a,b,a,b,... where a tells you the index of the next elements to leave in the same order they're in, and b tells you the index of the item to swap it with.
Because you're only doing swaps instead of shifts, you should very rarely end up with data like your sample data where 30, 40, and 50 are in the same order but in a slightly different location. Since the number of swaps will be between 1/4 and 1/10 the number of original items in the list, you'll usually have a big chunk of your data in both the same order and the same location it was in originally. Let's assume the following swaps were made:
1 <-> 9 4 <-> 2 5 <-> 2 The resulting list would be:
1. 90 2. 50 3. 30 4. 20 5. 40 6. 60 7. 70 8. 80 9. 10 So the change data could be represented as:
1,9,2,4,4,5 That's only six values, which could be represented as 16-bit numbers (assuming you won't have over 16,000 items in your initial list). So each "effective" swap could be represented with a single 32-bit number. And since the number of actual swaps will generally be 1/5 to 1/2 the size of the original list, you'll end up sending between 10% and 20% of the data in your original list over the wire (or less since the number of "effective" swaps may be even less if some of those swaps undo one another).
-6675678 0Here:
$('.someClass').live('click',function(){ // Handle here })
-20962068 0 Create a name system to html Id attibute so they do not repeat I'm not sure if I make sense, maybe there are easier ways.
I am building a web app, which will be based in Bootstrap models, what I want is to display a model to make CRUD operations to my database.
For example I will have a models like these:
public class Author { public int id { get; set; } public string Name { get; set; } } public class Book { public int id { get; set; } public string Name { get; set; } } What I want is to make a partial view that will display a dialog (modal) to add a new author to my app, same with books, and my 'n' classes my app will have, I want to render these partials wherever I need them. So I can add an author from any view of my page.
That part is ok, now I am having some 'troubles' because when I make an ajax post call to save my author in my data base I am facing that I already had a #Name field which was the one rendered for my books modal now when I call my field with jQuery, like this: $('#Name').val() it will grab the first #name.
That is easy to solve I will make a #AuthorName and a #BookName.
Now I am scared that my application will not be stable if my name system is not.
So is there any way to make an name system?
I am not sure how to do this but I would like to write my id's like this:
@Html.TextBoxFor(u => u.Id, new { @id = "@MyDialogs.Authors.Add.Name" }) that will return something like this: dialogs-authors-add-namefield
Is this possible or I am being too lazy?
-12334738 0There is a warning on the facebook website,
We are in the process of deprecating the REST API. If you are building a new Facebook app, please use the Graph API. While there is still functionality that we have not ported over yet, the Graph API is the center of Facebook Platform moving forward and where all new features will be found.
And according to this and that Stackoverflow questions, there is no implementation available right now.
-20371955 0Just make the value a String by concatenating an empty String:
function getObjects(obj, key, val, path) { var value = val + ""; for (var prop in obj) { if (prop == key && obj[key].toLowerCase().match(value)) { result.push(passName); matchFlag = 1; } } }
-902941 0 What's wrong with my ListView Callback retreiving subitems? I'm trying to retrieve the SubItem in my ListView from another thread, but I keep getting the Item instead of the SubItem. I'm not sure how to code this properly. Below is the code I'm using:
Delegate Function lvExtractedCallback(ByVal x As Integer) As String Private Function lvExtracted(ByVal x As Integer) As String Static Dim lvName As String If Me.OptionsList.InvokeRequired Then Dim lvEC As New lvExtractedCallback(AddressOf lvExtracted) Me.Invoke(lvEC, (New Object() {x})) Else lvName = OptionsList.Items.Item(x).SubItems.Item(0).Text End If Return lvName End Function Private Sub GetSubItem() Dim subItemText as String For i as Integer = 0 to 15 subItemText = lvExtracted(x) Debug.Print subItemText Next End Sub Any and all help appreciated!
-JFV
-10008125 0 SSRS Report, How do I have Group By on the ColumnsIn MS SQL 2008 R2 DB, I have a table:
Name, Value, Type A, 1, T1 B, 2, T1 C, 3, T1 D, 4, T1 A, 10, T2 B, 20, T2 C, 13, T2 D, 45, T2 A, 11, T3 B, 22, T3 C, 33, T3 D, 44, T3 What I want to do is to get this:
Name, Type T1, T2, T3 A, 1, 10, 11 B, 2, 20, 22 C, 3, 13, 33 D, 4, 45, 44 From the query, I can return this: Name, Value, Type A, 1, T1 B, 2, T1 C, 3, T1 D, 4, T1
A, 10, T2 B, 20, T2 C, 13, T2 D, 45, T2 A, 11, T3 B, 22, T3 C, 33, T3 D, 44, T3 Now I want to take this data and in SSRS, transform it into this form:
Name, Type T1, T2, T3 A, 1, 10, 11 B, 2, 20, 22 C, 3, 13, 33 D, 4, 45, 44 Types can change from one execution to another.
-39994037 0 How to perform a POST request with session data to an endpoint within the server node jsI am working on express and I need to perform a POST request to an endpoint within the server. My code for this is :
request({ url : 'http://localhost:3000/api/oauth2/authorize', qs:{ transaction_id:req.oauth2.transactionID, user:req.user, client : req.oauth2.client }, headers:{ 'Authorization':auth, 'Content-Type':'application/x-www-form-urlencoded' }, method:'POST' },function(err,res,bo){ console.log("Got response with body :"+bo); }); localhost is the current server, this works properly but the session data is lost when i perform the POST request.
Is there any other way to perform a POST within the same server or to save the session data such that it is maintained after the POST?
I have Codeigniter 3 project in root directory. I need to use it with kohana other project which is in subfolder (admin). I need to make redirect, when I will type mysite.xyz/admin that will redirect me to subfolder admin, where are kohana files: index.php etc.
Now CodeIgniter think that admin is a controller.
My .htacces file:
<IfModule mod_rewrite.c> RewriteEngine On RewriteBase /projekty/folder/ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?/$1 [L] RewriteRule admin/^(.*)$ /admin/ [L] </IfModule> <IfModule !mod_rewrite.c> ErrorDocument 404 /index.php </IfModule> Have any ideas, how to solve that? I was trying to find some solutions, but no success.
Here is Kohana .htaccess:
RewriteEngine On RewriteBase /projekty/folder/admin/ ###### Add trailing slash (optional) ###### RewriteCond %{REQUEST_METHOD} !POST RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [L,R=301,NE] RewriteCond %{REQUEST_METHOD} !POST RewriteRule ^(.*)home/u343855449/public_html/projekty/folder/admin/index.php/(.*)$ /$1$2 [R=301,L,NE] RewriteCond $1 ^(index\.php|robots\.txt|favicon\.ico|media) RewriteRule ^(?:application|modules|system)\b.* index.php/$0 [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.+)$ index.php?kohana_uri=$1 [L,QSA]
-20262402 0 Try this:
$title = explode('-', $title, 2); $title = trim($title[1]); First you split the title in the two parts, than you keep only the last one removing all extra whitespaces.
If you have at least PHP 5.4, you could do
$title = trim(explode('-', $title, 2)[1]);
-20520737 0 Although your device is capable of satisfying the usesdevice allocation, without a GPP or other ExecutableDevice, there is no place to run your component. There are two ways that allocation is performed when launching components:
Each implementation in the component's SPD has a list of dependencies that must be satisfied to run the entry point. Typically, for a C++ component, this will include the OS and processor type. Additional requirements can be defined based on the processing requirements of the component, such as memory or load average; these must be allocation properties known to the target device, just like with usesdevice. There is also an implicit requirement that the device selected for deployment should support the ExecutableDevice interface (there is slightly more nuance to it, but that's by far the most common case).
When launching a waveform, the ApplicationFactory tries to allocate all required devices and select an implementation for each component in sequence. Each possible implementation is checked against all of the devices in the domain to see if there is a device that meets its dependencies. If so, the entry point for that implementation will be loaded onto the device and executed, and the ApplicationFactory moves on to the next component. If no suitable device can be found, it throws a CreateApplicationError, as you are seeing.
For most cases, you can use the GPP device included with REDHAWK to support the execution of your components. You would usually only write your own ExecutableDevice if you have a specific type of hardware that does not work with GPP, like an FPGA. If you have installed from RPM, there should be a node tailored to your local system (e.g., processor type, Java and Python versions) in your $SDRROOT/dev/nodes directory. Otherwise you can create it yourself with the 'nodeconfig.py' script included with the GPP project; see the Ubuntu installation guide for an example (admittedly, somewhat buried in the REDHAWK Manual, Appendix E, Section 5).
-18781633 0Look at your AndroidManifest.xml file.
In application: Remove android:theme="@style/AppTheme"
In activity: Add android:screenOrientation ="landscape" or add android:screenOrientation ="portrait"
-736981 0 How do I deal with "Project Files" in my Qt application?My Qt application should be able to create/open/save a single "Project" at once. What is the painless way to store project's settings in a file? Should it be XML or something less horrible?
Of course data to be stored in a file is a subject to change over time.
What I need is something like QSettings but bounded to a project in my application rather than to the whole application.
You can use either, but fabric.api is specifically the better option. This is because it's where the other fabric modules are imported for simplicity's sake. See here:
$ cat fabric/api.py (env: selenium) """ Non-init module for doing convenient * imports from. Necessary because if we did this in __init__, one would be unable to import anything else inside the package -- like, say, the version number used in setup.py -- without triggering loads of most of the code. Which doesn't work so well when you're using setup.py to install e.g. ssh! """ from fabric.context_managers import (cd, hide, settings, show, path, prefix, lcd, quiet, warn_only, remote_tunnel, shell_env) from fabric.decorators import (hosts, roles, runs_once, with_settings, task, serial, parallel) from fabric.operations import (require, prompt, put, get, run, sudo, local, reboot, open_shell) from fabric.state import env, output from fabric.utils import abort, warn, puts, fastprint from fabric.tasks import execute fabric.api is importing fabric.operations.reboot for you already.
I'd like to insert CSV data into a SQL Server database at one time. I know about BULK INSERT but I need to select some fields only. So I try INSERT INTO like below -
try { OleDbConnection myOleDbConnection = new OleDbConnection("Provider=SQLOLEDB;Data Source=ServerName;Integrated Security=SSPI;Initial Catalog=DBName;User ID=sa;Password=password"); myOleDbConnection.Open(); string strSQL = null; strSQL = "INSERT INTO " + strTable + "(" + M_ItemCode + "," + M_ItemDesc + "," + M_UOM + ") " + "SELECT " + M_ItemCode + "," + M_ItemDesc + "," + M_UOM + " FROM [Text;DATABASE=E:\temp\\Item.csv]" ; OleDbCommand cmd = new OleDbCommand(strSQL, myOleDbConnection); return (cmd.ExecuteNonQuery() == 1); } catch (Exception ex) { Common.ShowMSGBox(ex.Message, Common.gCompanyTitle, Common.iconError); return false; } I got the error
Invalid object name 'Text;DATABASE=E:\temp\Item.csv'.
Is my syntax wrong?
-25540407 0 Summarize a list of Haskell recordsLet's say I have a list of records, and I want to summarize it by taking the median. More concretely, say I have
data Location = Location { x :: Double, y :: Double } I have a list of measurements, and I want to summarize it into a median Location, so something like:
Location (median (map x measurements)) (median (map y measurements)) That is fine, but what if I have something more nested, such as:
data CampusLocation = CampusLocation { firstBuilding :: Location ,secondBuilding :: Location } I have a list of CampusLocations and I want a summary CampusLocation, where the median is applied recursively to all fields.
What is the cleanest way to do this in Haskell? Lenses? Uniplate?
Edit: Bonus:
What if instead of a record containing fields we want to summarize, we had an implicit list instead? For example:
data ComplexCampus = ComplexCampus { buildings :: [Location] } How can we summarize a [ComplexCampus] into a ComplexCampus, assuming that each of the buildings is the same length?
You must use string formatting to substitute variable for its value
cursor.execute("UPDATE `ISEF_DB`.`attendance` SET `present`='1' WHERE `id` = '%s'" % data) Although be warned that this leaves you susceptible to SQL Injection. To prevent that you can use exceute like so (from the docs)
cursor.execute("UPDATE `ISEF_DB`.`attendance` SET `present`='1' WHERE `id` = '%s'", (data,)) i.e. pass the values as tuples to execute. More information about avoiding SQL injection when using MySQLDB can be found in this question
(Disclaimer: This is a good question even for people that do not use Bluebird. I've posted a similar answer here; this answer will work for people that aren't using Bluebird.)
Here's how you can use chai-as-promised to test both resolve and reject cases for a Promise:
var chai = require('chai'); var expect = chai.expect; var chaiAsPromised = require("chai-as-promised"); chai.use(chaiAsPromised); ... it('resolves as promised', function() { return expect(Promise.resolve('woof')).to.eventually.equal('woof'); }); it('rejects as promised', function() { return expect(Promise.reject('caw')).to.be.rejectedWith('caw'); }); You can accomplish the same without chai-as-promised like this:
it('resolves as promised', function() { return Promise.resolve("woof") .then(function(m) { expect(m).to.equal('woof'); }) .catch(function(m) { throw new Error('was not supposed to fail'); }) ; }); it('rejects as promised', function() { return Promise.reject("caw") .then(function(m) { throw new Error('was not supposed to succeed'); }) .catch(function(m) { expect(m).to.equal('caw'); }) ; });
-15486142 0 How to iterate over a node list and get child elements? I have some XML like this:
<?xml version="1.0" encoding="UTF-8"?> <person> <version>1.1</version> <lname>xxxx</lname> <fname>yyyy</fname> <address> <city>zzzz</city> <state>ffff</state> <country>aaaa</country> <address> <dob>xx-xx-xxxx</dob> <familymembers> <father> <fname>bbbb</fname> <lname>dddd</lname> </father> <mother> <fname>zzzz</fname> <lname>aaaa</lname> </mother> <sibling> <fname>bbbb</fname> <lname>dddd</lname> </sibling> </familymembers> </person> My requirement is that all child elements should be traversed and placed inside a map as key-value pairs like this:
persion.version --> 1.1 persion.lname --> xxxx persion.fname --> yyyy person.address.city --> zzzz person.address.state --> ffff person.address.country --> aaaa person.familymembers.father.fname --> bbbb person.familymembers.father.lname --> dddd person.familymembers.mother.fname --> zzzz person.familymembers.mother.lname --> aaaa person.familymembers.sibling.fname --> bbbb person.familymembers.sibling.lname --> dddd
-28361845 0 You can do this with block approach,
let views: NSArray = scroller.subviews // 3 - remove all subviews views.enumerateObjectsUsingBlock { (object: AnyObject!, idx: Int, stop: UnsafeMutablePointer<ObjCBool>) -> Void in object.removeFromSuperview() }
-40384993 0 Use the forecast package and use an ARIMAX function and specify the structure, it will be (1,0,0) in this case. The xreg argument will allow you to include additional covariates.
It should look something like this..
library(forecast) fit <- Arima(y, order=c(1,0,0),xreg = x)
-2005954 0 Center a position:fixed element I would like to make a position: fixed; popup box centered to the screen with a dynamic width and height. I used margin: 5% auto; for this. Without position: fixed; it centers fine horizontally, but not vertically. After adding position: fixed;, it's even not centering horizontally.
Here's the complete set:
.jqbox_innerhtml { position: fixed; width: 500px; height: 200px; margin: 5% auto; padding: 10px; border: 5px solid #ccc; background-color: #fff; } <div class="jqbox_innerhtml"> This should be inside a horizontally and vertically centered box. </div> How do I center this box in screen with CSS?
-16167075 0 I want to edit a wellformatted excel file with rubyI have a wellformatted excel file with a lot of macros and styling in it that I want to keep. Then i have this information I want to enter in the file. And I want to do it with ruby.
I've tried roo and spreadsheet but they don't seem able to actually edit the file, just create a new one and loosing all the formattin in the process.
It feels it should be simple to just edit the cells I want and save the file again but obviously it's more complex that I originally though(or I'm completely blind)
Any help is appreciated.
I'm learning ruby at the moment so that's why I would prefer a solution in ruby. If you know there are better suited laguages for this feel free to point me in the right direction and I'll check it out.
Thanks in advance
-634013 0If you are trying to return the script name, try:
Request.CurrentExecutionFilePath and if you just wanted the script name without the path, you could use:
Path.GetFileName(Request.CurrentExecutionFilePath) Path.GetFileName() requires the System.IO namespace
-10259939 0 Why do I see redefinition error in C?Following is my code, I am trying to run it in Visual Studio.
#include <stdio.h> #include <conio.h> int main() { //int i; //char j = 'g',k= 'c'; struct book { char name[10]; char author[10]; int callno; }; struct book b1 = {"Basic", "there", 550}; display ("Basic", "Basic", 550); printf("Press any key to coninute.."); getch(); return 0; } void display(char *s, char *t, int n) { printf("%s %s %d \n", s, t, n); } It gives an error of redefinition on the line where opening brace of function is typed.
-12826909 0 Hiding Etag to use cache-control in jboss for static contentI need to disable Etag header in response so that I can set the cache-control to a large value for static content for a web app which does not get updated say in 6 months. I am using jboss. I found a way to create filter to add the cache-control header. is there a way to not set the etag, a setting in configuration file or using filter.
-30310467 0I was getting a similar error when the file used to create the output stream already had data. If you are looking to append data to the file, you must indicate so in the file output stream object:
FileOutputStream out = new FileOutputStream("/Users/muratcanpinar/Downloads/KNVBJ/build/classes/knvbj/ClubInformation.xlsx", true); When you do this, wb.write(out) should work as expected.
I have url
http://www.website.com/shopping/books/?b=9
I have disallow /?b=9 from robots.txt
as
User-agent: * Disallow: /?b=9
But when i test this from Google Webmaster Robots.txt Test Tools.
Showing allowed while it should be display disallowed...
Please tell any wrong with my robots.txt
URL - http://www.website.com/shopping/books/?b=9
User-agent: * Disallow: /?b=9
Also
there /?b=9 this will be same in all cases and /shopping/books/ will be change with different category.
How to Block this types of string ?
Disallow: /?b=9
Is it correct ?
-23557108 0for non GNU sed (or with --posix option) where | is not available
If TGG is not occuring or could be included
sed 's/T[AG][AG]$//' YourFile if not
sed 's/T[AG]A$//;s/TAA$//' YourFile
-9312322 0 You need to annotate the collection with DataMember or it will not get serialized at all. You will also need to annotate the DataContract with KnownType(typeof(ChildCollection)) as otherwise it doesn't know what type of "thing" the ICollection is and therefore how to serialize it
Similarly you will need to add [DataMember] to Child_A Name property or it will not get serialized
Do you mean something like this?
List<Cabbage> = new ArrayList<Cabbage>(); // an arraylist that holds cabbages (good or otherwise) N_GOOD_CABBAGES = 10 //in a separate interface for(int j = 0; j < N_GOOD_CABBAGES; j++){ Cabbage good = new GoodCabbage(); // make a good cabbage cabbages.add(good); // add it to the list }
-4471044 0 The 3.5 version of the Framework is sufficient. However, you will need the Crystal viewer control to view any Crystal report (assuming you are displaying Crystal reports to a user via a WinForms).
-39237567 0Well according to the Lua documentation on the require call (using Lua 5.2 here), there are a few places the loader looks for these loadable modules.
It seems that require() uses what are called "searchers" (docs linked to in above) to determine where to find these modules. There are four searchers in total. From the docs:
The first searcher simply looks for a loader in the package.preload table.
The second searcher looks for a loader as a Lua library, using the path stored at package.path. The search is done as described in function package.searchpath.
The third searcher looks for a loader as a C library, using the path given by the variable package.cpath. Again, the search is done as described in function package.searchpath. For instance, if the C path is the string
"./?.so;./?.dll;/usr/local/?/init.so"the searcher for module foo will try to open the files./foo.so,./foo.dll, and/usr/local/foo/init.so, in that order. Once it finds a C library, this searcher first uses a dynamic link facility to link the application with the library. Then it tries to find a C function inside the library to be used as the loader. The name of this C function is the string "luaopen_" concatenated with a copy of the module name where each dot is replaced by an underscore. Moreover, if the module name has a hyphen, its prefix up to (and including) the first hyphen is removed. For instance, if the module name is a.v1-b.c, the function name will be luaopen_b_c.The fourth searcher tries an all-in-one loader. It searches the C path for a library for the root name of the given module. For instance, when requiring a.b.c, it will search for a C library for a. If found, it looks into it for an open function for the submodule; in our example, that would be luaopen_a_b_c. With this facility, a package can pack several C submodules into one single library, with each submodule keeping its original open function.
The searcher of use to us is the third one: it is used for any shared libraries (.dll or .so) which is generally how our custom C modules are built.
Using the template string (the one with the question marks), the searcher will look in each of the specified paths, substituting the argument of require() in place of the question mark. In order to specify the path for this third searcher, one must set (or append to) package.cpath and then call require().
So perhaps you have a directory structure as
- ROOT |-lua |-bin where lua contains script.lua and bin contains mylib.so
To load mylib.so, you just need these two lines of code in script.lua:
package.cpath = '/ROOT/bin/?.so;' .. package.cpath libfuncs = require('mylib') NOTE: Notice the semicolon. If you append (as opposed to the prepending above), make sure to lead with the semicolon on your added path. It is not there buy default. Otherwise your new path will be merged to the current default cpath, which is just ./?.so.
I have an issue with my codeigniter application deployed on an EC2 instance on Amazon.
$config['base_url'] = 'http://XX.XX.XXX.107/'; $config['index_page'] = 'index.php'; This is my route.php (without any particular rule)
$route['default_controller'] = 'home'; $route['404_override'] = ''; $route['translate_uri_dashes'] = FALSE; Actually if I call http://xx.xx.xxx.107/ it correctly show my first page (it loads my default controller Home.php and shows home.php view). But if I call for example http://52.59.107.107/index.php/Home/sign_in_form, instead of showing sign_in form view, it shows again home view.
I enabled log, and this is what I get
INFO - 2016-08-08 15:43:25 --> Config Class Initialized INFO - 2016-08-08 15:43:25 --> Hooks Class Initialized DEBUG - 2016-08-08 15:43:25 --> UTF-8 Support Enabled INFO - 2016-08-08 15:43:25 --> Utf8 Class Initialized INFO - 2016-08-08 15:43:25 --> URI Class Initialized DEBUG - 2016-08-08 15:43:25 --> No URI present. Default controller set. INFO - 2016-08-08 15:43:25 --> Router Class Initialized INFO - 2016-08-08 15:43:25 --> Output Class Initialized INFO - 2016-08-08 15:43:25 --> Security Class Initialized DEBUG - 2016-08-08 15:43:25 --> Global POST, GET and COOKIE data sanitized INFO - 2016-08-08 15:43:25 --> Input Class Initialized INFO - 2016-08-08 15:43:25 --> Language Class Initialized INFO - 2016-08-08 15:43:25 --> Loader Class Initialized INFO - 2016-08-08 15:43:25 --> Helper loaded: file_helper INFO - 2016-08-08 15:43:25 --> Helper loaded: form_helper INFO - 2016-08-08 15:43:25 --> Helper loaded: url_helper INFO - 2016-08-08 15:43:25 --> Database Driver Class Initialized INFO - 2016-08-08 15:43:25 --> Database Driver Class Initialized INFO - 2016-08-08 15:43:25 --> Session: Class initialized using 'files' driver. INFO - 2016-08-08 15:43:25 --> XML-RPC Class Initialized INFO - 2016-08-08 15:43:25 --> Controller Class Initialized INFO - 2016-08-08 15:43:25 --> Model Class Initialized INFO - 2016-08-08 15:43:25 --> Model Class Initialized INFO - 2016-08-08 15:43:25 --> Model Class Initialized INFO - 2016-08-08 15:43:25 --> Model Class Initialized INFO - 2016-08-08 15:43:25 --> Form Validation Class Initialized DEBUG - 2016-08-08 15:43:25 --> Session class already loaded. Second attempt ignored. INFO - 2016-08-08 15:43:25 --> File loaded: /var/www/core_ci/application/views/header.php INFO - 2016-08-08 15:43:25 --> File loaded: /var/www/core_ci/application/views/home.php INFO - 2016-08-08 15:43:25 --> File loaded: /var/www/core_ci/application/views/footer.php INFO - 2016-08-08 15:43:25 --> Final output sent to browser DEBUG - 2016-08-08 15:43:25 --> Total execution time: 0.1061 As you can see in the log, I'm getting DEBUG - 2016-08-08 15:43:25 --> No URI present. Default controller set., even if I'm calling this url http://xx.xx.xxx.107/index.php/Home/sign_in_form
Here some data about my server:
PHP Version 5.5.35 System Linux ip-xx-x-x-xxx 4.4.8-20.46.amzn1.x86_64 #1 SMP Wed Apr 27 19:28:52 UTC 2016 x86_64 Build Date May 2 2016 23:29:10 Server API FPM/FastCGI Here the vhost Apache file:
<VirtualHost *:80> # Leave this alone. This setting tells Apache that # this vhost should be used as the default if nothing # more appropriate is available. ServerName default:80 # REQUIRED. Set this to the directory you want to use for # your “default” site files. DocumentRoot /var/www/html # Optional. Uncomment this and set it to your admin email # address, if you have one. If there is a server error, # this is the address that Apache will show to users. #ServerAdmin you@example.com # Optional. Uncomment this if you want to specify # a different error log file than the default. You will # need to create the error file first. #ErrorLog /var/www/vhosts/logs/error_log <Directory /var/www/html> AllowOverride All </Directory> ProxyPassMatch ^/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9000/var/www/html/$1 DirectoryIndex /index.php index.php </VirtualHost> Is there anyone that can tell me where I'm failing?
Thanks in advance.
UPDATED
Home.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Home extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('Home_model'); $this->load->model('Users_model'); $this->load->model('Credit_model'); $this->load->library('form_validation'); $this->load->library('language'); $this->load->library('alerts'); $this->load->library('session'); $this->load->helper('url'); // $this->load->helper('captcha'); } public function test() { print_r('my test method'); } As you can see I prepared for simplicity a test method in Home controller. If I call http://xx.xx.xxx.107/index.php/Home/test I get the same log sequence and it shows the home view instead of printing my raw data.
It seems that as it is not able to get correct URi, it run default controller.
-2399610 0-12149337 0The simplest way to create a site map is to create an XML file named Web.sitemap that organizes the pages in the site hierarchically. This site map is automatically picked up by the default site-map provider for ASP.NET.
double[] array is object. So, you get address and entire array is added at index 0.
You may use Arrays.toString(x.get(0)) to get readable array print.
toString() for an array is to print [, followed by a character representing the data type of the array's elements, followed by @ then the memory address.
-15253144 0If you're using Java, you may want to check out Sikuli-API instead. It tries to be more of a standard Java library.
Sikuli-API uses SLF4J, so you just connect it to whatever logging framework you use (I like Logback a lot), and it will use that configuration.
-2557207 0 Selectively replacing words outside of tags using regular expressions in PHP?I have a paragraph of text and i want to replace some words using PHP (preg_replace). Here's a sample piece of text:
This lesson addresses rhyming [one]words and ways[/one] that students may learn to identify these words. Topics include learning that rhyming words sound alike and these sounds all come from the [two]ending of the words[/two]. This can be accomplished by having students repeat sets of rhyming words so that they can say them and hear them. The students will also participate in a variety of rhyming word activities. In order to demonstrate mastery the students will listen to [three]sets of words[/three] and tell the teacher if the words rhyme or not.
If you notice there are many occurances of the word 'words'. I want to replace all the occurances that don't occur inside any of the tags with the word 'birds'. So it looks like this:
This lesson addresses rhyming [one]words and ways[/one] that students may learn to identify these birds. Topics include learning that rhyming birds sound alike and these sounds all come from the [two]ending of the words[/two]. This can be accomplished by having students repeat sets of rhyming birds so that they can say them and hear them. The students will also participate in a variety of rhyming word activities. In order to demonstrate mastery the students will listen to [three]sets of words[/three] and tell the teacher if the birds rhyme or not.
Would you use regular expressions to accomplish this?
Can a regular expression accomplish this?
Sure. You can use the magic constant __FILE__ which contains the path to the file that you use it in:
class MyClass def initialize puts File.read(__FILE__) end end This will print the contents of the file containing the definition of MyClass every time you create a MyClass object.
If you run your application in debug mode you can find it by this path:
"%PARTITION%:\\...PATH TO YOUR APP...\bin\Debug\\...
-26582458 0 i think you are using $routeProvider for your angular app. but in your example angular app is using $stateProvider.so you have to install angular-ui-router.js and give reference to it to the index.html . and also you have to put dependency 'ui.router' in to app.js
-16375887 0 Unable to start main activity which has build by mavenI had three proejct: parent, source and a library project. My problem is the following: after successful mvn install android:deploy android:run the application get`s crash with the following message:
05-04 17:22:10.564: E/AndroidRuntime(6574): FATAL EXCEPTION: main 05-04 17:22:10.564: E/AndroidRuntime(6574): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.fruit.apple/com.fruit.apple.SplashScreenActivity}: java.lang.ClassNotFoundException: com.fruit.apple.SplashScreenActivity in loader dalvik.system.PathClassLoader[/system/framework/com.google.android.maps.jar:/mnt/asec/com.fruit.apple-1/pkg.apk] Actually I don`t know what should be there problem, I really appreciate your help.
Thanks, Karoly
PS part of pom.xml
<plugin> <groupId>com.jayway.maven.plugins.android.generation2</groupId> <artifactId>android-maven-plugin</artifactId> <version>3.2.0</version> <configuration> <sign> <debug>true</debug> </sign> <androidManifestFile>${project.basedir}/AndroidManifest.xml</androidManifestFile> <assetsDirectory>${project.basedir}/assets</assetsDirectory> <resourceDirectory>${project.basedir}/res</resourceDirectory> <sourceDirectory>${project.basedir}/src/main/java</sourceDirectory> <testSourceDirectory>${project.basedir}/src/test/java</testSourceDirectory> <sdk> <path>${android.sdk.path}</path> <platform>17</platform> </sdk> <deleteConflictingFiles>true</deleteConflictingFiles> <undeployBeforeDeploy>false</undeployBeforeDeploy> </configuration> <extensions>true</extensions> </plugin>
-13312846 0 You're defining a function prototype with a reference as the return value. The function returns a reference to an integer. As such its return value can be set to another value.
-7735251 0You are not initializing p. It's an uninitialized pointer that you are writing to.
Since you are writing this in C++, not C, I'd suggest using std::string and std::reverse:
#include <string> #include <algorithm> #include <iostream> int main() { std::string str = "Saw my reflection in snow covered hills"; std::reverse(str.begin(), str.end()); std::cout << str; return 0; } Output:
sllih derevoc wons ni noitcelfer ym waS
See it working online at ideone
-13829295 0You cannot perform append operation on array. Try the following.
String[] list = new String[6];
list[0] = "One";
list[1] = "Two";
list[2] = "Three";
list[3] = "Four";
list[4] = "Five";
list[5] = "Six";
String[] list2 = new String[list.length / 2];
for (int i = 0, j = 0; i < list.length; i++, j++)
{
list2[j] = list[i] + list[++i];
}
Assuming that the menu screen has sky and ground (i.e. that stuff isn't part of the game), then so far so good. Looks like you have the actors in separate classes, which is good. "MenuScreen" is the sort of thing that would make sense as a single responsibility.
-26057790 0 Redis key not removed even after Resque job completes successfullyHere is my scenario, i'm using resque to queue a job in redis, the usual way its done in ROR. The format of my key looks something like this (as per my namespace convention)
"resque:lock:Jobs::XYZ::SomeCreator-{:my_ids=>[101]}" The job runs successfully to completition. But the key still exists in redis. For a certain flow, i need to queue and execute the job again for the same parameters (the key will essentially be same). But seems like the job does not get queued.
My guess is that since the key already exists in Redis, it does not queue the job again.
Questions:
Is this behavior of resque normal (not removing the key after successful completition)?
If Yes, how should i tackle this scenario (as per best practices)?
If No, can you help me understand what is going wrong?
-21157531 0Please assign an event SelectedIndexChanged and AutoPostBack = true is this is a web Application in C#
Since I do not have an iPad, I am unable to troubleshoot this. I can confirm that the desktop version of Safari works fine though. Have you tried this on newer versions of DotNetNuke? The browser and telerik definitions are updated with every release. If you cannot upgrade for some reason, I would try upgrading just your telerik controls. For example, you can try the latest release of the DNN 5 RadEditor Provider by dnnWerk.
-17801689 0I believe there are three different concepts: initializing the variable, the location of the variable in memory, the time the variable is initialized.
When a variable is allocated in memory, typical processors leave the memory untouched, so the variable will have the same value that somebody else stored earlier. For security, some compilers add the extra code to initialize all variables they allocate to zero. I think this is what you mean by "Zero Initialization". It happens when you say:
int i; // not all compilers set this to zero However if you say to the compiler:
int i = 10; then the compiler instructs the processor to put 10 in the memory rather than leaving it with old values or setting it to zero. I think this is what you mean by "Static Initialization".
Finally, you could say this:
int i; ... ... i = 11; then the processor "zero initializes" (or leaves the old value) when executing int i; then when it reaches the line i = 11 it "dynamically initializes" the variable to 11 (which can happen very long after the first initialization.
There are: stack-based variables (sometimes called static variables), and memory-heap variables (sometimes called dynamic variables).
Variables can be created in the stack segment using this:
int i; or the memory heap like this:
int *i = new int; The difference is that the stack segment variable is lost after exiting the function call, while memory-heap variables are left until you say delete i;. You can read an Assembly-language book to understand the difference better.
A stack-segment variable is "zero-initialized" or statically-initialized" when you enter the function call they are defined within.
A memory-heap variable is "zero-initialized" or statically-initialized" when it is first created by the new operator.
You can think about static int i; as a global variable with a scope limited to the function it is defined in. I think the confusion about static int i; comes because static hear mean another thing (it is not destroyed when you exit the routine, so it retains its value). I am not sure, but I think the trick used for static int i; is to put it in the stack of main() which means it is not destroyed until you exit the whole program (so it retains the first initialization), or it could be that it is stored in the data segment of the application.
i have hidden the spinbox arrows from an input type="number" but the number restrictions doesn't work already. Hence, the numberbox now accepts alphanumeric characters.
I used this code when i was able to hide the spinner arrows:
input::-webkit-outer-spin-button, input::-webkit-inner-spin-button { /* display: none; <- Crashes Chrome on hover */ -webkit-appearance: none; margin: 0; /* <-- Apparently some margin are still there even though it's hidden */ } hi @BenM! thanks for editing my question. Now, thanks for the idea of using javascript @FakeRainBrigand but it didn't work for me.
This worked for me though. I'm using MVC and Razor
` function keeypress(e) { var unicode = e.keyCode ? e.keyCode : e.charCode
if (unicode == 8) { return; }; if (unicode == 37 || unicode == 39 || unicode == 38 || unicode == 40 || unicode == 27) { return; } else { }; if (unicode == 13) { e.preventDefault(); }; if ($.isNumeric(String.fromCharCode(unicode)) == false) { e.preventDefault(); }; } `
-40728071 0From your MainActivity:
Intent intent = new Intent(this, mySensor.class); intent.putExtra("type", Sensor.TYPE_LIGHT); and within your service:
@Override public IBinder onBind(Intent intent) { mSensorManager= (SensorManager) getSystemService(Context.SENSOR_SERVICE); int type = intent.getExtras().get("type"); s= mSensorManager.getDefaultSensor(type); return null; } then you can remove:
public mySensor(int type){ ... } and eventually the code you wrote within the onCreate.
I found another situation that could cause this to happen. I was converting a PHP function to a JS function and I had the following line:
ticks += "," . Math.floor(yyy * intMax); Changing it to
ticks += "," + Math.floor(yyy * intMax); solved the problem
-39275662 0 Google not crawling my pages even using history.pushState()I read a lot on SEO compatibility with google crawler before starting my new project. And everything tends to say that Google know execute javascript, and so can render my template. For example here.
But it seems that the crawler never execute my javascript, and the templating with some api's data isn't done. (I seen that after using the "fetch as google tool")
I started my router like this
Backbone.history.start({pushState: true, hashChange: false}); And so route are handled like this:
Backbone.history.navigate(url, { trigger: true }); So I probably miss something somewhere but where ?
-4663649 0if it's only calculating pairs of 2 (and no higher), you can simply count the other two arrays.
for anyone in array1, simply count(array2) + count(array3) = number of pairs
browserify needs an absolute path to retrieve the file and it leaves that as the bundle key. The way to fix it is to use the expose option...
In your build..
var dependencies = [ 'lodash', {file: './test.js', expose: 'test'}, ]; and in app.js...
var _ = require('lodash'); var test = require('test');
-38646755 0 This will match exactly the words "Mac" and "ExchangeWebServices" with anything else between them:
\bMac\b.*\bExchangeWebServices\b Regex 101 Example: https://regex101.com/r/sK2qG1/4
-38384837 0 Binary Search Tree node deletion errorI've created my binary search tree and gave the pointer to the node which I want to delete into my *p.
The delete method is supposed to be deleting the node which is pointed at by *p and should add the subtrees with addtree to my root. *pBaum is the pointer which points to my root.
However im getting an error message called "conflict types" on addtree everytime I declare
Baum = addtree(Baum, p->right); I also get a warning "assignment makes pointer from integer without a cast"
My struct contains left & right pointer to the subtrees and a pointer to the content.
struct tnode { int content; struct tnode *left; /* linker Teilbaum */ struct tnode *right; /* rechter Teilbaum */ }; // Deletes the node where *p is pointing at struct tnode *deletenode(struct tnode *p, struct tnode *pBaum) { struct tnode *Baum = pBaum; if ((p->left == NULL) && (p->right == NULL)) { free(p); } if ((p->left == NULL) && (p->right != NULL)) { Baum = addtree(Baum, p->right); free(p); } if ((p->right == NULL) && (p->left !=NULL)) { Baum = addtree(Baum, p->left); free(p); } if ((p->left != NULL) && (p->right !=NULL)) { Baum = addtree(Baum, p->right); Baum = addtree(Baum, p->left); free(p); } return Baum; } // Adds the Subtrees to my root struct tnode *addtree(struct tnode *top, struct tnode *p) { if (p == NULL) return top; else return addtree(addtree(addelement(top, p->content),p-> right), p->left); // Adds a node to my Tree struct tnode *addelement(struct tnode *p, int i) { int cond; if (p == NULL) { p = talloc(); /* make a new node */ p->content = i; p->left =p->right =NULL; } else if (p->content == i) { return p; } else if (i < p->content) /* goes into left subtree */ p->left =addelement(p->left, i); else /* goes into right subtree */ p->right = addelement(p->right, i); return p; } // Looks for the node which is supposed to get deleted and returns a pointer to it struct tnode *searchnode(struct tnode *p, int nodtodelete) { if (p == NULL) { printf("Baum ist leer oder Element nicht vorhanden \n"); return NULL; } if ( p -> content == nodtodelete) { return p; } if (p->content < nodtodelete) { return searchnode (p->right, nodtodelete); } if (p->content > nodtodelete) { return searchnode(p->left, nodtodelete); } } } int main() { struct tnode *Baum = NULL; struct tnode *tmpPos = NULL; Baum = addelement (Baum, 32); Baum = addelement(Baum, 50); Baum = addelement(Baum, 60); tmpPos = searchnode(Baum,50); Baum = deletenode(tmpPos, Baum); }
-23666955 0 Adding JButton using loop (for) does nothing I'm trying to add various JButtons to a JPanel using "for" but doesn't work. No compilation or other errors. Buttons just won't appear.
A bit of context, I create an ArryList in another class ("GestorFrigo") that gets data from DataBase, this works fine, the array has all the data and there's no problem getting back the data from the array.
This is my code: Thanks in advance.
import gestor.GestorFrigo; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseListener; import java.util.ArrayList; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JButton; import javax.swing.JScrollBar; @SuppressWarnings("serial") public class VentanaInterior extends JFrame { private JPanel contentPane; private JButton btnPerfiles; private JButton btnAadir; private JButton btnRecetas; private JScrollBar scrollBar; private GestorFrigo frigo; private ArrayList<JButton> botones; private ArrayList<Object> boton; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { VentanaInterior frame = new VentanaInterior(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public VentanaInterior() { //Componentes setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 556, 363); setLocationRelativeTo(null); setTitle("Tu Frigorífico Inteligente"); setIconImage(new ImageIcon(getClass().getResource("img/logo.png")).getImage()); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); btnPerfiles = new JButton("Perfiles"); btnPerfiles.setBounds(0, 302, 96, 23); contentPane.add(btnPerfiles); btnAadir = new JButton("A\u00F1adir alimento"); btnAadir.setBounds(369, 302, 148, 23); contentPane.add(btnAadir); btnRecetas = new JButton("Recetas"); btnRecetas.setBounds(96, 302, 103, 23); contentPane.add(btnRecetas); scrollBar = new JScrollBar(); scrollBar.setBounds(523, 0, 17, 325); contentPane.add(scrollBar); JButton btnQueso = new JButton(); btnQueso.setBounds(24, 35, 62, 61); contentPane.add(btnQueso); frigo = new GestorFrigo(); //creamos el gestor String imagen = frigo.getArray().get(1).getImagen(); //cogemos la imagen asociada al alimento btnQueso.setIcon(new ImageIcon("src/img/"+imagen)); for(int i=0;i<frigo.getArray().size();i++){ JButton boton = new JButton(); String imagen2 = frigo.getArray().get(i).getImagen(); boton.setIcon(new ImageIcon("src/img/"+imagen2)); contentPane.add(boton); } } }
-16999624 0 Can I load a new page when someone click on close button on browser? Can I do it? If yes, than how? I tried unonload, but that works only when I click on an url.
-33730402 0Optimized
if ($buyoption != 'With Validation' && $buyoption != "No Validation") { $buyoptionError = "Please select a buy option"; echo "$buyoptionError <br>"; $YesorNo = 0; }
-5328972 0 Why don't you add null validation for password before calling ValidateCredentials? On a side note, client side authentication might help as well.
-1017600 0the mex endpoint is necessary during development as it provides an http location where the wsdl is built. the wsdl describes to the client how to communicate with the server through named pipes, or TCP/IP, or anything else. once the client app has built the proxy to the named pipes binding and set up the configuration, the mex endpoint is no longer necessary. hence, the mex endpoint can be removed prior to deployment through the environments if desired.
-34307400 0 PHP Codeigniter site_url produce HTML link errorin my view, i try to print URL to my controller, below the code :
<p id="demo"> <a href="<?php echo site_url('HT');?>"> Goto Controller </a> </p> However those code provide HTML link error like this :
<a href="http://::1/cidLab/index.php/HT"> Goto Controller </a> The link should be go to http://localhost/cidLab/index.php/HT but why must http://::1/ ?
I've try to use base_url, but still face same Error...
-24501764 0 Speeding up an Insert TSQL procedureI need some tip on tuning some TSQL to execute faster, it's taking way too long although it works. This may be because I'm fetching a key from another table before I can do the insert, any ideas anyone?
DECLARE db_cursorReads CURSOR FOR SELECT [MeterId] ,[MeterRead] FROM MdsReadsImports; declare @PremiseMeterId int; declare @MeterId nvarchar(24); declare @MeterRead int; OPEN db_cursorReads; FETCH NEXT FROM db_cursorReads INTO @MeterId ,@MeterRead; WHILE @@FETCH_STATUS = 0 BEGIN set @PremiseMeterId = (select top 1 PremiseMeterId from PremiseMeters where MeterId = @MeterId) insert into PremiseMeterReads (MeterRead,PremiseMeterId) values (@MeterRead, @MPremiseMeterId) FETCH NEXT FROM db_cursorReads INTO @MeterId ,@MeterRead; END; CLOSE db_cursorReads; DEALLOCATE db_cursorReads;
-29898371 0 You are hiding your adMobBannerView in your displayiAdsOrNot function. This function is called every time the viewWillAppear. Remove this and you should get the results you desire.
As for the rest of your code, you have a lot going on here. First, to simplify things you should move all of your code that is creating and laying out your adBanner and adMobBannerView under viewWillAppear when [[NSUserDefaults standardUserDefaults] boolForKey:@"IAPSuccessful"] is false, and set both banners .hidden = YES automatically. This will eliminate the need for your displayiAdsOrNot and displayAdMobBannerOrNot where you are repeating a lot of the same if statements checking for IAP and which device the user is using. After doing this, in your delegate methods you can simply hide or show the correct banner depending on if iAd fails or not now. For example, iAd loads so set its hidden value to NO and AdMob’s to YES, and vice versa if iAd fails to load an ad. I’m sure you were checking the IAP every time in case the user purchased it while in the current session so you could remove the ads. An easier solution would be to move the ads outside of the screen bounds on completion of the IAP and then on the next launch of your application simply do not create either banner at all if [[NSUserDefaults standardUserDefaults] boolForKey:@"IAPSuccessful"] is true. A few other things to point out are, you should remove your request.testDevices AdMob request before submitting your application, and it seems you are defining your NSLayoutConstraint *myConstraint multiple times. I’m not exactly sure what you’re trying to do here. Also, in didFailToReceiveAdWithError you have self.adBanner.hidden = true, it should be self.adBanner.hidden = YES.
If you're using em's then you first need to define a base value for the font. Ex.:
body { font-size: 16px }
Now 1em = 16px.
Most browsers have a default user-agent font-size of 16px but you shouldn't rely on it. Set the base value then start using em's.
-5143719 0A relative path is specified like this:
System.IO.File.ReadAllLines("myfile.txt"); which will search myfile.txt relative to the working directory executing your application. It works also with subfolders:
System.IO.File.ReadAllLines(@"sub\myfile.txt"); The MapPath function you are referring to in your question is used in ASP.NET applications and allows you to retrieve the absolute path of a file given it's virtual path. For example:
Server.MapPath("~/foo/myfile.txt") and if your site is hosted in c:\wwwroot\mysite it will return c:\wwwroot\mysite\foo\myfile.txt.
You can now do this with JSONModel.
Assume we have the following model:
@class MyModel @property (strong, nonatomic) NSString *name; @property (strong, nonatomic) NSArray *products; @end If the complete JSON doc looks like this:
{ "productType1": { "name": "foo", "products": [] }, "productType2": { "name": "foo", "products": [] }, "productType3": { "name": "foo", "products": [] } } then you should use one of the [MyModel dictionaryOfModelsFrom...]; methods.
If it looks like this:
{ "productTypes": { "productType1": { "name": "foo", "products": [] }, "productType2": { "name": "foo", "products": [] }, "productType3": { "name": "foo", "products": [] } } } Then you should use another model like this:
@class MyModelContainer @property (strong, nonatomic) NSDictionary <MyModel> *productTypes; @end
-31453817 0 Getting first image from content in silverstripe I have the following method where it is suppose to get the first image that is displayed from the content.
public function FirstImage($content) { $dom = new DOMDocument(); $dom->loadHTML($content); Debug::dump($content); } The wierd thing is when i do $dom->loadHTML I get the following error Empty string supplied as input, but as soon as I dump it I do get the correct data. How can I fix this problem ?
I also done $this->owner->Content which has the same thing.
-14632866 0If you want to use it more times in your program then it's maybe a good idea to make a custom class inherited from StreamReader with the ability to skip lines.
Something like this could do:
class SkippableStreamReader : StreamReader { public SkippableStreamReader(string path) : base(path) { } public void SkipLines(int linecount) { for (int i = 0; i < linecount; i++) { this.ReadLine(); } } } after this you could use the SkippableStreamReader's function to skip lines. Example:
SkippableStreamReader exampleReader = new SkippableStreamReader("file_to_read"); //do stuff //and when needed exampleReader.SkipLines(number_of_lines_to_skip);
-37419607 0 If you set:
$this->table = 'selstock_product'; Prestashop will look for a Key Column named Id_{tablename} , so, you need to rename your PK Field according to the prestashop sintax, That is: Id_selstock_product
greetings
-31658826 0 Scraping dynamic web pages using Python 3.4 and beautifulsoupOK, using Python 3.4 and beautifulsoup4 on a windows 7 VM. Having trouble scraping the data resulting from making a selection with a drop-down list. As a learning experience, I'm trying to write a scraper that can select the 4 year option on this page: www.nasdaq.com/symbol/ddd/historical and print the rows of the resulting table. So far, it just prints out the default 3 month table, along with some junk at the beginning that I don't want. Eventually I would like to scrape this data and write it to DB using mysql python connector, but for now I would just like to figure out how to make the 4 year selection in the drop down list. (also, would like to get rid of the text encoding that causes it to be in the b'blahblah' format. My code so far:
from bs4 import BeautifulSoup import requests url = 'http://www.nasdaq.com/symbol/ddd/historical' with requests.Session() as session: session.headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36'} response = session.get(url) soup = BeautifulSoup(response.content) data = { 'ddlTimeFrame': '4y' } response = session.post(url, data=data) soup = BeautifulSoup(response.content) for mytable in soup.find_all('tbody'): for trs in mytable.find_all('tr'): tds = trs.find_all('td') row = [elem.text.strip().encode('utf-8') for elem in tds] print (row) I get no errors, but it doesn't print out the 4 year data. Thanks for your time/patience/help!
-38639066 0 Angular textarea validation errorI have a textarea in my app like so:
<textarea type="text" class="form-control" name="bioBackground" ng-model="obj.background" value="obj.background" ng-change="autosave()" maxlength="1500" required></textarea> This is a required field and as you can see I have added a required tag in the code. But this required tag is causing errors with Angular.
For example:
If I type in the field and backspace and remove all the text it removes the object from the scope. see example below:
Before Backspacing
You can see background variable is in the scope.
After backspacing and removing the text:
You can see the background variable is gone from scope.
This only happens if I use required tag. If I don't use the required tag it works fine and even after removing all the text the background variable stays within the scope.
What am I doing wrong.
-2616378 0 can't write to physical drive in win 7?I wrote a disk utility that allowed you to erase whole physical drives. it uses the windows file api, calling :
destFile = CreateFile("\\\\.\\PhysicalDrive1", GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,createflags, NULL); and then just calling WriteFile, and making sure you write in multiples of sectors, i.e. 512 bytes.
this worked fine in the past, on XP, and even on the Win7 RC, all you have to do is make sure you are running it as an administrator.
but now I have retail Win7 professional, it doesn't work anymore! the drives still open fine for writing, but calling WriteFile on the successfully opened Drive now fails!
does anyone know why this might be? could it have something to do with opening it with shared flags? this is always what I have done before, and its worked. could it be that something is now sharing the drive? blocking the writes? is there some way to properly "unmount" a drive, or at least the partitions on it so that I would have exclusive access to it?
some other tools that used to work don't any more either, but some do, like the WD Diagnostic's erase functionality. and after it has erased the drive, my tool then works on it too! leading me to believe there is some "unmount" process I need to be doing to the drive first, to free up permission to write to it.
Any ideas?
Update:
the error code returned from WriteFile is '5', ERROR_ACCESS_DENIED but again, if I 'erase' the drive first using WD Diag, I can then access and write to the drive fine. when I initialize the drive again, and give it a partition, I go back to getting the ERROR_ACCESS_DENIED error.
That’s how I usually annotate my test classes:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { JPAUnitTestConfiguration.class }) @Transactional //rollback if exception occurs during test method @TransactionConfiguration(defaultRollback = true) //rollback at end of method @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) public class FooBarTest { } Add @TransactionConfiguration(defaultRollback = true) to your test class.
My transaction configuration:
import java.sql.SQLException; import javax.sql.DataSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.FilterType; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import org.springframework.transaction.annotation.EnableTransactionManagement; import ch.ams.pois.repository.AuthTokenRepository; import ch.ams.pois.repository.GroupRepository; import ch.ams.pois.repository.InvitationRepository; import ch.ams.pois.repository.LocationRepository; import ch.ams.pois.repository.UserRepository; @Configuration @EnableTransactionManagement @EnableJpaRepositories(basePackages = JPAConfiguration.JPA_REPOSITORIES_BASE_PACKAGES, includeFilters = @ComponentScan.Filter(value = { UserRepository.class, LocationRepository.class, GroupRepository.class, AuthTokenRepository.class, InvitationRepository.class }, type = FilterType.ASSIGNABLE_TYPE)) public class JPAUnitTestConfiguration extends JPAConfiguration { @Bean public DataSource dataSource() throws SQLException { EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); return builder.setType(EmbeddedDatabaseType.H2).build(); } } The dependencies for the persistence layer:
<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>1.3.4.RELEASE</version> </dependency> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.0-api</artifactId> <version>1.0.1.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.0.1.Final</version> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>1.3.173</version> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>9.2-1003-jdbc4</version> </dependency>
-10893435 0 import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; public class MainActivity extends Activity { /** Called when the activity is first created. */ Button btnTakePhoto; ImageView imgTakenPhoto; private static final int CAM_REQUREST = 0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btnTakePhoto = (Button) findViewById(R.id.button1); imgTakenPhoto = (ImageView) findViewById(R.id.imageView1); btnTakePhoto.setOnClickListener(new btnTakePhotoClicker()); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); if (requestCode == CAMERA_PIC_REQUEST) { Bitmap thumbnail = (Bitmap) data.getExtras().get("data"); imgTakenPhoto.setImageBitmap(thumbnail); } } class btnTakePhotoClicker implements Button.OnClickListener { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST); } } }
-32854613 0 The password-reset token that Firebase generates when you call resetPassword() expires after 24 hours. That time period is not configurable, nor can the token be extended.
According to the JLS:
15.9.5 Anonymous Class Declarations An anonymous class declaration is automatically derived from a class instance creation expression by the compiler.
An anonymous class is never abstract (§8.1.1.1). An anonymous class is always an inner class (§8.1.3); it is never static (§8.1.1, §8.5.2). An anonymous class is always implicitly final (§8.1.1.2).
This seems like it was a specific design decision, so chances are it has some history.
If I choose to have a class like this:
SomeType foo = new SomeType() { @Override void foo() { super.foo(); System.out.println("Hello, world!"); } }; Why am I not allowed to subclass it again if I so choose?
SomeType foo = new SomeType() { @Override void foo() { super.foo(); System.out.println("Hello, world!"); } } { @Override void foo() { System.out.println("Hahaha, no super foo for you!"); } }; I'm not saying I necessarily want to, or can even think of a reason why I would. But I am curious why this is the case.
-23000592 0I have run into similar issues. Most of the times, I fixed it by casting it to any.
Try this -
(<any>grid.dataSource.transport).options.read.url = newDataSource; Or, you can try this too -
(<kendo.data.DataSource>.grid.dataSource).transport.options.read.url = newDataSource; But, fist option should work for sure!
Hope, this helps
-31691685 0Change this line:
this.css("text-shadow", sh); to
$(this).css("text-shadow", sh); .css is a jQuery function and it works on a proper selector
Demo: https://jsfiddle.net/wwqxdjvp/
-15402703 0There are a couple of known fixes that have managed to sort this similar problem out.
The AVD does not have enough RAM. Try increasing the RAM of the AVD by editing it from the AVD Manager. Source: http://stackoverflow.com/a/9384040/450534
The AVD you are using may have been corrupted. The solution is to delete the current AVD and create new one with the same settings (if that is important to your apps functioning). Source: http://stackoverflow.com/a/2199621/450534
Why is this code not working?
@echo off set /p param=Enter Parameters: echo %param% Output:
(Nothing) I have searched all relative posts, but I can't find what is wrong with it. There is no space problem, or syntax problem that I can identify
Update: As rojo stated, since the code block is working, here is the full code, which is not working.
@echo off for /f %%j in ("java.exe") do ( set JAVA_HOME=%%~dp$PATH:j ) if %JAVA_HOME%.==. ( echo java.exe not found ) else ( set /p param=Enter Parameters: echo %param% (statement using JAVA_HOME) ) pause Output:
Enter Parameters: jfdklsaj ECHO is off. ...
-31815894 0 I need a Hexadecimal Number List I need a script that generates all 65536 Hexadecimal numbers from 0000 to FFFF and puts them in a text file like this:
0000 0001 0002 0003 ... FFFF I don`t care what programming language it is written in, but please not one that I have to run a web server (PHP) or that is Windows only.
-375843 0Using includeInLayout ="true" or "false" will toggle the space that it takes in the flow of items being rendered in that section.
Important note: If you don't specify visible="false" when using includeInLayout = "false" then you will usually get something that is undesired which is that your item (boxAddComment) is still visible on the page but stuff below id="boxAddComment" will overlap it visually. So, in general, you probably want "includeInLayout" and "visible" to be in synch.
You're constantly multiplying the noOfYears variable by -1, so it keeps switching between -1 and 1. Try using noOfYears * -1 instead (without the equals-sign).
Just a simple question I want to ask. I am beginner for Perl script, sorry if you feel this question is stupid.
The question is can I return a variable and apply "uc" when return.
Here is the code:
my $desc = ""; @names = ("thor-12345-4567"); $size = @names; Thor(); print $desc; sub Thor() { if ($size ne "0") { return uc ($desc=$names[0]); } $desc = "NA"; return $desc; } I just want to know that is "uc" can be use when we return to a variable?
When I try to print $desc, it did not return to uppercase.
Thank you very much!
-28475696 0 Differences when using functions for casper.evaluateI'm using PhantomJS v2.0 and CasperJS 1.1.0-beta3. I want to query a specific part inside the page DOM.
Here the code that did not work:
function myfunc() { return document.querySelector('span[style="color:#50aa50;"]').innerText; } var del=this.evaluate(myfunc()); this.echo("value: " + del); And here the code that did work:
var del=this.evaluate(function() { return document.querySelector('span[style="color:#50aa50;"]').innerText; }); this.echo("value: " + del); It seems to be the same, but it works different, I don't understand.
And here a code that did also work:
function myfunc() { return document.querySelector('span[style="color:#50aa50;"]').innerText; } var del=this.evaluate(myfunc); this.echo("value: " + del); The difference here, I call the myfunc without the '()'.
Can anyone explain the reason?
-8389545 0Your problem is not occuring at the GROUP BY level, but rather in the JOIN. The rows with a NULL qualifier cannot be JOINed and, because you're using INNER JOIN, they fall out of the result set.
Use LEFT OUTER JOIN to see all the rows.
-9323906 0 how to substitute underscore of a string in hamlI use rails_admin
One of my partial is like this :
%b= questionnaire.title - CSV.parse(questionnaire.content, :headers => true, :col_sep => ",") do |row| - row.to_hash.each do |key, value| = succeed value do %b= key + " : " but key is sometimes like this "I_dont_want_underscore"
I tried this :
%b= questionnaire.title - CSV.parse(questionnaire.content, :headers => true, :col_sep => ",") do |row| - row.to_hash.each do |key, value| = succeed value do %b= key.gsub!-'_',' ') + " : " but then I've got this error showing : Can't convert frozen string (or something like this) Then I tried to duplicate
%b= questionnaire.title - CSV.parse(questionnaire.content, :headers => true, :col_sep => ",") do |row| - row.to_hash.each do |key, value| = succeed value do %b= key.dup.gsub!-'_',' ') + " : " But then server does not respond anymore...how come ? finally I tried to put a def in my application_helper.rb
def sub_underscore self.dup.gsub!-'_',' ') end and
%b= questionnaire.title - CSV.parse(questionnaire.content, :headers => true, :col_sep => ",") do |row| - row.to_hash.each do |key, value| = succeed value do %b= key.sub_underscore + " : " But I get this error : "no method sub_underscore for this string"
Any ideas ?
-29367249 0Try by changing the tint color of the searchable in xib or in code as [self.searchDisplayController setTintColor:[UIColor whiteColor]];searchDisplayController
Acoording to https://regex101.com/ regexp '^[-+]?[0-9]*\.?[0-9]$' for strings like "g2", "a8" etc. (one digit preceded by one letter) should return "false" (no match), but if I use it in JavaScript using RegExp test method "true" is returned. What is the reason of that behaviour?
<!DOCTYPE html> <html> <body> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { var str = "g2"; var patt = new RegExp('^[-+]?[0-9]*\.?[0-9]$'); var res = patt.test(str); document.getElementById("demo").innerHTML = res; } </script> </body> </html> Try
Object result = expr.evaluate(doc, XPathConstants.NODESET); // Cast the result to a DOM NodeList NodeList nodes = (NodeList) result; for (int i=0; i<nodes.getLength();i++){ System.out.println(nodes.item(i).getNodeValue()); }
-4262521 0 Professional Excel Development by Stephen Bullen describes how to register UDFs, which allows a description to appear in the Function Arguments dialog:
Function IFERROR(ByRef ToEvaluate As Variant, ByRef Default As Variant) As Variant If IsError(ToEvaluate) Then IFERROR = Default Else IFERROR = ToEvaluate End If End Function Sub RegisterUDF() Dim s As String s = "Provides a shortcut replacement for the common worksheet construct" & vbLf _ & "IF(ISERROR(<expression>, <default>, <expression>)" Application.MacroOptions macro:="IFERROR", Description:=s, Category:=9 End Sub Sub UnregisterUDF() Application.MacroOptions Macro:="IFERROR", Description:=Empty, Category:=Empty End Sub From: http://www.ozgrid.com/forum/showthread.php?t=78123&page=1
To show the Function Arguments dialog, type the function name and press CtrlA. Alternatively, click the "fx" symbol in the formula bar:

You can have a maven-war-plugin and configure to include empty folders.
<plugin> <artifactId>maven-war-plugin</artifactId> <version>2.4</version> <configuration> <includeEmptyDirectories>true</includeEmptyDirectories> </configuration> </plugin>
-31575692 0 You are going to want to change the settings in your plist for the app transport security. Do this in watch extension plist if you are doing the network call on the watch. Here is a helpful link
Also for your url you are going to need to use either http:// or https:// in order for this to work.
-33361777 0l = [1,2,3,4, 5, 6, 7, 8] print [[l[:i], l[i:]] for i in range(1, len(l))] If you want all combinations. you can do like this.
print [l[i:i+n] for i in range(len(l)) for n in range(1, len(l)-i+1)] or
itertools.combinations
-33051015 0 Since the price requires a decimal value we should supply it a decimal value. Try the following view:
def get_queryset(self, *args, **kwargs): qs = super(ProductListView, self).get_queryset(*args,**kwargs) query = self.request.GET.get("q", False) # provide default value or you get a KeyError if query: filter_arg = Q(title__icontains=query) | Q(description__icontains=query) try: filter_arg |= Q(price=float(query)) except ValueError: pass qs = self.model.objects.filter(filter_arg) return qs qs = super(ProductListView, self).get_queryset(*args,**kwargs) This is used to obtain the queryset provided by the parent classes of our view class ProductListView. Look in to python classes and inheritance here: http://www.jesshamrick.com/2011/05/18/an-introduction-to-classes-and-inheritance-in-python/
filter_arg |= Q(price=float(query)) this is used to append to our filter_arg value. It's the same as filter_arg = filter_arg | Q(price=float(query)
float(query) with this we are trying to convert the query variable to a float and we put this in a try statement because it could give us a ValueError in which case the query value is not a float.
The opensource framework Impromptu-Interface was designed to do this. It generates a cached lightweight proxy with a static interface and uses the dlr to forward the invocation to the original object.
using ImpromptuInterface; public interface ISimpeleClassProps { string Prop1 { get; } long Prop2 { get; } Guid Prop3 { get; } } -
dynamic tOriginal= new ExpandoObject(); tOriginal.Prop1 = "Test"; tOriginal.Prop2 = 42L; tOriginal.Prop3 = Guid.NewGuid(); ISimpeleClassProps tActsLike = Impromptu.ActLike(tOriginal);
-22968999 0 Here you go: Fiddle http://jsfiddle.net/fx62r/2/
inline-block leaves white-space between elements. I would use float: left; instead of inline block
Write elements on same line to avoid white-space. Like this:
<div class="icon"></div><div class="title"></div><div class="icon"></div>
And remove Margin:
.icon { margin: 0 0.2em 0.2em 0; //Remove. } .title { margin: 0 0.2em 0.2em 0; //Remove }
-6303813 0 I've got two approaches for you:
Firstly using Activator.CreateInstance
public static IEnumerable<TV> To<TU, TV>(this IEnumerable<TU> source) { return source.Select(m => (TV) Activator.CreateInstance(typeof(TV), m)); } Secondly, you could use interfaces to define properties rather than use parameterized constructors:
public interface IRequiredMember {} public interface IHasNeccesaryMember { IRequiredMember Member { get; set; } } public static IEnumerable<TV> To<TU, TV>(this IEnumerable<TU> source) where TV : IHasNeccesaryMember, new() where TU : IRequiredMember { return source.Select(m => new TV{ Member = m }); } The first method works but feels dirty and there is the risk of getting the constructor call wrong, particularly as the method is not constrained.
Therefore, I think the second method is a better solution.
-33523070 0Which CodeIgniter version are you running?
If CodeIgniter 2.*. Try looking at this page: CodeIgniter Guides - Views
Under Loading a View it shows you the code of how to load your ViewMessages.php inside your controller
-24987866 0Make sure that you are using the proper yourtablename and following name conventions. The table name is always lower-case and pluralized.
For example, if your model name is User, your table name is users. If your model name is Image, your table name will be images.
Let me know if this solved the problem.
-11503342 0You are looking for the two properties:
In your case, you have to set the combobox's ValueMember property to value1 and the DisplayMember property to option1.
Update: The following is an exmple of how you can populate the items of a combobox from list of some entity Foo:
public class Foo(){ public string Id { get; set; } public string Name { get; set; } } var ds = new List<Foo>(){ new Foo { Id = "1", Name = "name1" }, new Foo { Id = "2", Name = "name2" }, new Foo { Id = "3", Name = "name3" }, new Foo { Id = "4", Name = "name4" }, }; comboboxName.DataSource = ds; comboboxName.ValueMember = "Id"; comboboxName.DisplayMember = "Name"; Update2: That's because you are adding the same object each time. In the following block of your code:
Foo categoryInsert = new Foo(); foreach (string s in categories) { categoryInsert.path = s; categoryInsert.name = s; combo3data.Add(categoryInsert); } Each time The foreach iterate over the categories, all what it does, is changing the same object categoryInsert's values path and name not creating a new one. Thus, you end up with the same object added in each iteration to the combo3data. What you need is create a new Foo object inside the foreach itself each time, i.e: move the Foo categoryInsert = new Foo(); inside the foreach loop. Something like:
foreach (string s in categories) { Foo categoryInsert = new Foo(); categoryInsert.path = s; categoryInsert.name = s; combo3data.Add(categoryInsert); }
-38534312 0 In Firebase 3.0 together with Angularjs, it seems onAuthStateChanged fires on every route change. Is that expected? I have an app using Firebase and Angularjs. If I put a listener on onAuthStateChanged, it seems to fire every time I navigate to a new url in my site, and the Angularjs Route changes. This seems undesirable/incorrect? Anyone else experience this? E.g. if I do this in a controller:
firebase.auth().onAuthStateChanged(function(user) { if (user) { alert("changed"); } }); every time the route changes the alert pops up.
Since the logged in state of the user doesn't seem to be changing, why would this listener fire? I think I am missing something. Anyone understand what's going on?
-22195715 0There are multiple ways to do what you are trying to do, the easiest one would be the following:
OutputDict = {} for key in Dict1.iterkeys(): if key in Dict2: OutputDict[key] = Dict1[key] + Dict2[key][2] Since all the operations are O(1), and we run it for each key on Dict1 (or Dict2 depending) all this runs in O(min(n,m)) where n is the length of Dict1 and m the length of Dict2
-2093416 0 Group by and non distinct columns and data normalizationI have a large table(60 columns, 1.5 million records) of denormalized data in MS SQL 2005 that was imported from an Access database. I've been tasked with normalizing and inserting this data into our data model.
I would like to create a query that used a grouping of, for example "customer_number", and returned a result set that only contains the columns that are non distinct for each customer_number. I don't know if it's even possible, but it would be of great help if it was.
Edit:if my table has 3 columns(cust_num,cust_name_cust_address) and 5 records
|cust_num|cust_name|cust_address |01 |abc |12 1st street |02 |cbs |1 Aroundthe Way |01 |abc |MLK BLVD |03 |DMC |Hollis Queens |02 |cbs |1 Aroundthe Way the results from my desired query should just be the data from cust_num and cust_name because cust_address has different values for that grouping of cust_num. A cust_num has many addresses but only one cust_name.
Can someone point me in the right direction?
Jim
-28064493 0An IBAction method has the format
-(IBAction)name:(id)sender
-40464006 0 Try like this :
progressDialog = new ProgressDialog(getActivity()); And if you wish to customize your dialog and put self created Layout in it.
/** * Created by vivek on 18/10/16. */ public class CustomDialog { private static Dialog dialog; private static Context context; public CustomDialog(Context context) { this.context = context; } /** * Comman progress dialog ... initiates with this * * @param message * @param title */ public static void showProgressDialog(Context context, String title, String message) { if (dialog == null) { dialog = new Dialog(context); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.custom_loader); dialog.setCancelable(false); dialog.setCanceledOnTouchOutside(false); dialog.show(); } } public static boolean isProgressDialogRunning() { if (dialog != null && dialog.isShowing()) { return true; } else return false; } /** * Dismiss comman progress dialog */ public static void dismissProgressDialog() { if (dialog != null && dialog.isShowing()) { dialog.dismiss(); dialog = null; } } } // End of main class over here ...
-4381251 0 The simpliest solution depends from wich method did you like to send mails.
If you have for example already installed sendmail - in this case to send the mail with notification log you can call it with params. It depend on your system settings.
-951425 0I think this is an implementation detail of the Linux file system. While on Windows .h and .H files are effectively the same, on Linux you can have a traditional.h and a traditional.H in the same directory.
If I am understanding you correctly, you just need to specify the capital H in the files that include your headers.
-35944923 0Disclaimer: Do not down vote without explaining why, because OP didn't include his entire code base or hardware/infrastructure design. But if i've made critical errors in my code or logic, explain them and down vote accordingly.
Lets start off with defining the bottle-necks you'll encounter (some obvious, some not).
In regards to a CSV reader, they're fine but maybe not so efficient.
Since you're going to read through both files anyway I would consider the following:
Read the 13GB file line by line and save the ID in a dictionary without checking if the key/value exists. (why? Because checking if the value exists is slower than just overwriting it and dictionaries also has a added bonus that keys are unique so duplicates will be weeded out) or add it to a set() as described by many others.
followed by reading the smaller file line by line and checking your dict or set if it contains the ID.
dict() vs set() vs list()Here's a comparison between the three data types set(), list() and dict():
code used: test.py
(11.719028949737549, 999950, 'Using dict() for inserts') (1.8462610244750977, 'dict() time spent looking through the data') (11.793760061264038, 999961, 'Using set() for inserts') (7.019757986068726, 'set() time spent looking through the data') (15min+, 'Using list()') # Honestly, I never let it run to it's finish.. It's to slow. As you can see dict is marginally quicker than set, while list() just falls behind completely (see description of why by Antti). I should point out my data is a bit skewed since it's a quick and dirty demo of the speed difference, but the general idea should still come across.
So if you do not have access to a database version of the source-data, and you need to use Python, id go with something along the lines of:
delimiter = b'\x01' big_source = {} with open('13_gig_source.log', 'rb') as fh: for line in fh: csv = line.split(delimiter) big_source[csv[4]] = None # 5:th column, change to match CUSTOMER_ID output = open('result.log', 'wb') with open('smaller_file.log', 'rb') as fh: for line in fh: csv = line.split(delimiter) if csv[4] in big_source: output.write(csv[4] + b'\n') output.close() Since I didn't know which column the data exists on i didn't optimize the split().
For instance, if it's the last column you're trying to fetch, do line.rsplit(delimiter, 1)[-1] instead. Or if it's the 3:d column do line.split(delimiter, 3)[2] because it will abort the process of looking for the next position of the delimiter in the split() functions.
Yes, some tools might be better off suited for this such as awk because of the fact that it's a specific tool written in C to perform a very specific task. Even tho Python is based on C it still has a lot of abstraction layers on-top of that C code and will for the most part be slower than the counterpart C tools written for specific tasks.
Now I have no data to test this with, nor am i a PRO With Nix-Commands or PWN-C for short. So I'll leave someone else to give you examples of this, but i found this:
And it might be helpful.
-6338456 0 sequentially including various View classes in a parent layoutI have a main layout in which I'd like to sequentially display / hide various custom layouts according to timers and user input.
In my example, I'd like the following timeline:
show an initial layout, created by the class MainStart. The user will click on the button when they're ready to start.
after the user clicks, we'll run a countdown timer, displaying the countdown to the screen. This is done by MainCountdown.
once the countdown is complete, MainLast is displayed. It has a button allowing the user to click "Again?" when they want to start over.
if the user clicks "Again?" then go to step 1.
According to this question, I may have to use removeView() and addView() to achieve what I want.
I pushed to GitHub a trimmed down version of what I want to do: Hide and Show Layouts so you can see everything, but the problem seems to boil down to myView still being visible after this:
myView = inflate(mContext, R.layout.main_start, _view_group); myView.setVisibility(View.GONE); Can I make a small change to my code/layouts to make the views hide/appear the way I want?
Am I completely Doing It Wrong?
-40125667 0Have a look at LinqToDb. It also has a version for Mono and it should work with Unity3D.
Good luck.
-11665717 0If you are using c#, you can simplify your life and use two separate regex:
bool res = false; string str = // your string if (str < 8) { res = Regex.IsMatch(str, @"^[0-9]+$"); } else { res = Regex.IsMatch(str, @"^(?=[a-zA-Z0-9]*[a-zA-Z])[a-zA-Z0-9]*$"); }
-39856475 0 You can use :
git config --get-regexp user.name For the user name. for the repository name, you may have different repositories with different names, so I guess parsing :
git remote get-url origin could help if you only care about the origin ? The format would be (prefixes would differ between ssh or https) git@github.com:{github_handle}/{repo_name}.git
I recognized that (insert/delete)-XQueries executed with the BaseX client always returning an empty string. I find this very confusing or unintuitive.
Is there a way to find out if the query was "successful" without querying the database again (and using potentially buggy "transitive" logic like "if I deleted a node, there must be 'oldNodeCount-1' nodes in the XML")?
-16450393 0You're asking for the filesize of a directory, which in this case is 4,096 bytes. This number will vary for a directory depending on what sort of filesystem you're using and how many files are in it.
-2940823 0 generateUrl problemI am trying to generate a url but I keep getting a strange warning even though it works. I am making an api xml page and I use the following call in the controller:
public function executeList(sfWebRequest $request) { $this->users = array(); foreach($this->getRoute()->getObjects() as $user) { $this->users[$this->generateUrl('user_show', $user, true)] = $user->asArray($request->getHost()); } } The user_show route is as follows:
# api urls user_show: url: /user/:nickname param: { module: user, action: show } And the xml outputs as follows:
<br /> <b>Warning</b>: array_diff_key() [<a href='function.array-diff-key'>function.array-diff-key</a>]: Argument #1 is not an array in <b>/opt/local/lib/php/symfony/routing/sfRoute.class.php</b> on line <b>253</b><br /> <br /> <b>Warning</b>: array_diff_key() [<a href='function.array-diff-key'>function.array-diff-key</a>]: Argument #1 is not an array in <b>/opt/local/lib/php/symfony/routing/sfRoute.class.php</b> on line <b>253</b><br /> <br /> <b>Warning</b>: array_diff_key() [<a href='function.array-diff-key'>function.array-diff-key</a>]: Argument #1 is not an array in <b>/opt/local/lib/php/symfony/routing/sfRoute.class.php</b> on line <b>253</b><br /> <?xml version="1.0" encoding="utf-8"?> <users> <user url="http://krowdd.dev/frontend_dev.php/user/danny"> <name>Danny tz</name> <nickname>danny</nickname> <email>comedy9@gmail.com</email> <image></image> </user> <user url="http://krowdd.dev/frontend_dev.php/user/adrian"> <name>Adrian Sooian</name> <nickname>adrian</nickname> </user> </users> So it outputs the correct xml but I do not know why it throws thows warning when calling the generateurl method.
Thanks!
-20927866 0With mapsforge you cannot do this. You have to use a routing library like graphhopper is one. See here how to use it: http://graphhopper.com/#developers.
But there are other offline and online routers as well. Have a look here: http://wiki.openstreetmap.org/wiki/Routing/offline_routers and here http://wiki.openstreetmap.org/wiki/Routing
-5703509 0If there is some PHP behind, the problem could be calling a function empty($var) in this way:
if(empty($var = getMyVar())) { ... } Instead of this You should call it this way:
$var = getMyVar(); if(empty($var)) { ... } Or better (as deceze has pointed out)
if(!getMyVar()) { ... } Problem causes also other similar functions (isset, is_a, is_null, etc).
-37488877 0I assume that you don't use nginx to serve static assets in development? Runserver can serve static files, but very much slower than nginx, which becomes a problem once you have more than a single web site visitor at a time. You can remove the nginx alias for static and reload nginx to let runserver serve the files, to confirm whether it's a problem in the nginx config. Håken Lid
I removed nginx and made the Django server load the static files, and now I can show it to my future users. This answered my question, though it did not solve the problem itself! Thanks anyway !
-38976434 0 Can't show value with json format on apache tomcat serverI've been trying to make a certain API and I need it to show result of a method on server in JSON format. If I try simple
import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path("/messages") public class MessageResource { @GET @Produces(MediaType.TEXT_PLAIN) public String getMessages() { return "Hello World!"; } } it works but when I try to use my class where I return values in JSON format it shows some errors on the server (it works in ordinary console).
I'm new to this, hope I explained it well enough.
type Exception report message org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: org/codehaus/jackson/map/ObjectMapper description The server encountered an internal error that prevented it from fulfilling this request. exception javax.servlet.ServletException: org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: org/codehaus/jackson/map/ObjectMapper org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:489) org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) root cause org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: org/codehaus/jackson/map/ObjectMapper org.glassfish.jersey.servlet.internal.ResponseWriter.rethrow(ResponseWriter.java:278) org.glassfish.jersey.servlet.internal.ResponseWriter.failure(ResponseWriter.java:260) org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:509) org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:334) org.glassfish.jersey.internal.Errors$1.call(Errors.java:271) org.glassfish.jersey.internal.Errors$1.call(Errors.java:267) org.glassfish.jersey.internal.Errors.process(Errors.java:315) org.glassfish.jersey.internal.Errors.process(Errors.java:297) org.glassfish.jersey.internal.Errors.process(Errors.java:267) org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317) org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305) org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154) org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473) org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) root cause java.lang.NoClassDefFoundError: org/codehaus/jackson/map/ObjectMapper valendor.messenger.ReturnJson.main(ReturnJson.java:27) sun.reflect.GeneratedMethodAccessor19.invoke(Unknown Source) sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) java.lang.reflect.Method.invoke(Unknown Source) org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81) org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144) org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161) org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$VoidOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:143) org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99) org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389) org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347) org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102) org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326) org.glassfish.jersey.internal.Errors$1.call(Errors.java:271) org.glassfish.jersey.internal.Errors$1.call(Errors.java:267) org.glassfish.jersey.internal.Errors.process(Errors.java:315) org.glassfish.jersey.internal.Errors.process(Errors.java:297) org.glassfish.jersey.internal.Errors.process(Errors.java:267) org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317) org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305) org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154) org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473) org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) note The full stack trace of the root cause is available in the Apache Tomcat/8.0.36 logs. thats the error
-28591521 0Check the following tutorial, it appears to be for the latest version of TinyMCE (and it is updated recently).
https://www.gavick.com/blog/wordpress-tinymce-custom-buttons
The tutorial you linked is probably for the TinyMCE that was in WordPress prior to 3.9.
Edit: Did a quick test. Seems to be working. :)

A quick guide to get it working:
plugins_url( '/text-button.js', __FILE__ ); with get_bloginfo('stylesheet_directory') . /text-button.js (might need adjusting if the file is in a subdirectory).(note this is just a quick example for implementing it in a theme so you can get the main idea, if you are actually building a plugin, you should use the plugins_url( '/text-button.js', __FILE__ ) syntax).
http://codex.wordpress.org/Function_Reference/plugins_url
-23283640 0 Is my code below secure enough to be used in production?What is the best practice to securely upload an image to a php script based on my code below? I'm using the file transfer cordova plugin to upload the image to a php script.
Javascript (file transfer cordova plugin)
var options = new FileUploadOptions(); options.fileKey = "file"; options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1); options.mimeType = "image/jpeg"; var params = new Object(); params.imageLink = "test"; options.params = params; options.chunkedMode = false; var ft = new FileTransfer(); ft.upload(imageURI, "http://example.com/upload.php", win, fail, options); alert("Post Uploading"); function win(r) { console.log("Code = " + r.responseCode); console.log("Response = " + r.response); console.log("Sent = " + r.bytesSent); alert(r.response); } function fail(error) { $.mobile.loading('hide'); navigator.notification.alert("An error has occurred: Code = " + error.code, null, 'Alert', 'OK'); } PHP
<?php if(isset($_POST['imageLink'])) { $imageLink = $_POST['imageLink']; print_r($_FILES); $new_image_name = $imageLink.".jpg"; move_uploaded_file($_FILES["file"]["tmp_name"], “uploads/“.$new_image_name); } ?> Any suggestions?
-40629380 0For basic types like int, NoneType, dict and other simple cases there's a natural "factory" in Python - it is ast.literal_eval.
>>> import ast >>> ast.literal_eval('None') is None True >>> ast.literal_eval('{1: 2}') {1: 2} >>> ast.literal_eval('1e6') 1000000.0 So if your data is a superposition of basic types (something json-like for instance), then you can parse it with single ast.literal_eval call. Unlike exec and eval, ast.literal_eval is much safer as you can't run any code with it.
When start the development server, Java will crash What is the cause?
(OS)
Mac OS X 10.6.6 (Java)
Java(TM) SE Runtime Environment (build 1.6.0_24-b07-334-10M3326) Java HotSpot(TM) 64-Bit Server VM (build 19.1-b02-334, mixed mode) (GAE) Version 1.4.2
(console)
admin$ ./dev_appserver.sh --port=8080 /Users/admin/projects/sample1/war/ 2011-03-10 12:51:02.582 java[2542:903] [Java CocoaComponent compatibility mode]: Enabled 2011-03-10 12:51:02.583 java[2542:903] [Java CocoaComponent compatibility mode]: Setting timeout for SWT to 0.100000 2011/03/10 3:51:03 com.google.apphosting.utils.jetty.JettyLogger info ####: Logging to JettyLogger(null) via com.google.apphosting.utils.jetty.JettyLogger 2011/03/10 3:51:04 com.google.apphosting.utils.config.AppEngineWebXmlReader readAppEngineWebXml ####: Successfully processed /Users/admin/projects/sample1/war/WEB-INF/appengine-web.xml 2011/03/10 3:51:04 com.google.apphosting.utils.config.AbstractConfigXmlReader readConfigXml ####: Successfully processed /Users/admin/projects/sample1/war/WEB-INF/web.xml 2011/03/10 3:51:04 com.google.apphosting.utils.jetty.JettyLogger info ####: jetty-6.1.x 2011/03/10 3:51:04 com.sun.jersey.api.core.PackagesResourceConfig init ####: Scanning for root resource and provider classes in the packages: sample1.resources jp.tryden.resources.test 2011/03/10 3:51:04 com.sun.jersey.api.core.ScanningResourceConfig logClasses ####: Root resource classes found: class sample1.resources.CheckinsResource class sample1.resources.UsersResource class sample1.resources.ItemsResource 2011/03/10 3:51:04 com.sun.jersey.api.core.ScanningResourceConfig init ####: No provider classes found. 2011/03/10 3:51:05 com.sun.jersey.server.impl.application.WebApplicationImpl initiate ####: Initiating Jersey application, version 'Jersey: 1.1.5.1 03/10/2010 02:33 PM' 2011/03/10 3:51:06 com.google.apphosting.utils.jetty.JettyLogger info ####: Started SelectChannelConnector@127.0.0.1:8080 2011/03/10 3:51:06 com.google.appengine.tools.development.DevAppServerImpl start ####: The server is running at http://localhost:8080/ admin$ ( <- Stopped!! ) (crash log)
Process: java [3466] Path: /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/java Identifier: java Version: 1.0 (1.0) Code Type: X86-64 (Native) Parent Process: java [3465] Date/Time: 2011-03-10 14:22:12.206 +0900 OS Version: Mac OS X 10.6.6 (10J567) Report Version: 6 Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Codes: KERN_INVALID_ADDRESS at 0x0000000000000000 Crashed Thread: 10 Dispatch queue: com.apple.root.low-priority Thread 0: Dispatch queue: com.apple.main-thread 0 ??? 0x000000010301f383 0 + 4345426819 1 ??? 0x000000010300685a 0 + 4345325658 2 ??? 0x0000000103006e8d 0 + 4345327245 3 ??? 0x00000001030069b3 0 + 4345326003 4 ??? 0x00000001030069b3 0 + 4345326003 5 ??? 0x0000000103006e8d 0 + 4345327245 6 ??? 0x000000010300685a 0 + 4345325658 7 ??? 0x000000010300685a 0 + 4345325658 8 ??? 0x000000010300685a 0 + 4345325658 ...
-38679399 0 When you create your documents, you must set the creation date:
MyCollection.insert({ text: "abc", createdAt: new Date() }); then, you can filter your data:
If you want the documents created in an interval:
MyCollection.find( {createdAt: { $gte: new Date("Sat Jul 30 2016 8:00:00"), $lt: new Date("Sat Jul 30 2016 9:00:00"), }}, {sort: {createdAt:1}});
Or documents created exactly at 8am:
MyCollection.find({createdAt: new Date("Sat Jul 30 2016 8:00:00")});
Hope it helps.
-10093352 0You can use product from itertools module.
itertools.product(range(3), range(2))
-13607556 0 The problem was a bit tricky but I manage to solve it.
The fact is: if a real postback is not executed (responding with a file is not considered so) the value is still considered "changed".
The only way to solve this problem seems to be "resetting" manually the value of the hiddenfield.
I came up with this:
self.getExcel = function (stringBase64) { $("#hiddenFiedlName").val(stringBase64); __doPostBack(); $("#hiddenFieldName").val(""); } After the postback the value is restored to the initial one (which is always the empty string). By doing this the "ValueChanged" event is not triggered.
As stated in the comment of jbl the change() was useless (please refer to his comment in the question).
so i have this XMl
<a>blah</a> And i want to change it to
<a>someValueIDoNotKnowAtCompileTime</a> Currently, I am looking at this SO question . However, this just changes the value to "2"
What i want is exactly the same thing, but to be able to define the value (so that it can change at runtime - i am reading the values from a file!)
I tried passing the value into the overridden methods, but that didn't work - compile errors everywhere (obviously)
How can i change static xml with dynamic values?
ADDING CODE
var splitString = someString.split("/t") //where someString is a line from a file val action = splitString(0) val ref = splitString(1) xmlMap.get(action) match { //maps the "action" string to some XML case Some(entry) => { val xmlToSend = insertRefIntoXml(ref,entry) //for the different XML, i want to put the string "ref" in an appropriate place } ...
-23416410 0 I have found the solution. The problem was that I was trying to use the adapter to get an reference to the views above and below the list item clicked. Instead I could find the appropriate views by using the getChildAt() method on the parent view (the listview itself).
It was as easy as writing:
View aboveView = parent.getChildAt(position -1) View aboveViewShadow = aboveView.findViewById(R.id.settingsListRowShadowAbove); aboveViewShadow.setVisibility(View.VISIBLE);
-38390423 0 Try by giving margins and padding to enlarge view
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="1dp" android:weightSum="1"> <TextView android:id="@+id/itemLabel" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="0.6" android:background="#00ffff" android:layout_margin="20dp" android:padding="10dp" android:gravity="center_vertical" android:text="Settings Item: " android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="@android:color/holo_blue_dark"/> <EditText android:id="@+id/et_item_value" android:layout_margin="20dp" android:layout_width="0dp" android:padding="10dp" android:layout_height="match_parent" android:layout_weight="0.4" android:background="#ffff00" android:textColor="@android:color/holo_blue_dark" android:textColorHint="@android:color/darker_gray"/> </LinearLayout>
-26012730 0 Running time of Construction Heuristic in OptaPlanner I am using the OptaPlanner to optimize a chained planning problem which is similar to the VehicleRoutingExample. My planning entities have a planning variable which is another planning entity.
Now I am testing a huge dataset with ca. 1500 planning entities. I am using an EasyJavaScoreCalculator to get a HardSoftScore. The Score includes several time and other factors which are calculated in loops.
My Problem is that the ConstrucionHeuristic (FIRST_FIT or FIRST_FIT_DECREASING) takes more than ten minutes to initialize a Solution.
I have already reduced the number of constraints and the number of loops with which I am calculating the score, but it did not have a real effect on the running duration.
Is there a way to make the CH need less time? (I thought that it would take less time than the LocalSearch stuff but it isn’t…)
-19523981 0This appears to be basically a duplicate of SQL Server Random Sort which is basically a duplicate of How to request a random row in SQL?.
The latter has a comprehensive answer for multiple RDBMSs referencing this post:
SQL to Select a random row from a database table
An answer for Microsoft SQL Server would be:
SELECT TOP 10 * FROM table ORDER BY NEWID();
This will not perform well on large tables. It scans the entire table, generating a unique number (a 16-bit GUID) for each row, and then sorts the results by that unique number.
Simply ordering by RAND() in SQL Server will not result in a random list of records. RAND() is evaluated once at the beginning of the statement, so you are effectively ordering by a constant, which isn't really ordering at all. You'll get the same results without the ORDER BY. Indeed, in my instance of SQL Server 2005, the query plans and results were the same with and without the ORDER BY RAND().
RAND() in SQL Server takes a seed value, so you might think that you could pass a varying table column value into the RAND function and get random results. In some sense, you can. You could pass an IDENTITY or other unique column into the RAND function and you won't get the same order as without. And the order will be random in the sense that it appears so to a casual observer. But it's repeatable. The RAND() function in SQL Server will always return the same value for the same seed on the same connection:
"For one connection, if RAND() is called with a specified seed value, all subsequent calls of RAND() produce results based on the seeded RAND() call."
http://technet.microsoft.com/en-us/library/ms177610.aspx
So while you would get what appeared to be a random list, if you executed it multiple times in the same connection, you would get the same list. Depending on your requirements, that might be good enough.
Based on my limited tests on a small table, the RAND with a unique column seed had a very slightly lower estimated query cost.
-15371413 0 How to convert a SPARQL query into an RDF file in Jena?I am trying to output an RDF/XML file directly from an SPARQL query from an Oracle database. The query is working fine as I've verified the results in the ResultSet object.
However, I'm not sure how to proceed from there. I think I want to create a Statement for each QuerySolution and then add it to the Model. However I can't figure out a way to do it, because I can't find a way to get the predicate value.
Any help would be appreciated, as well as hints whether I am going down the right path.
QueryExecution qe = QueryExecutionFactory.create(query, oracleSemModel) ; ResultSet results = qe.execSelect(); Model model = ModelFactory.createDefaultModel(); while (results.hasNext()) { QuerySolution result = results.next(); Resource subject = result.getResource("s"); // get the subject Property predicate = result.getProperty("p"); // <-- THIS FUNCTION DOESN'T EXIST RDFNode object = result.get("o"); // get the object Statement stmt = ResourceFactory.createStatement(subject, predicate, object); model.add(stmt); } model.write(System.out, "RDF/XML-ABBREV");
-21949630 0 Say you have two versions of the gem foo installed:
$ gem list foo *** LOCAL GEMS *** foo (2.0.1, 2.0.0) If you use only require, the newest version will be loaded by default:
require 'foo' # => true Foo::VERSION # => "2.0.1" If you use gem before calling require, you can specify a different version to use:
gem 'foo', '2.0.0' # => true require 'foo' # => true Foo::VERSION # => "2.0.0" Note: using gem without subsequently calling require does not load the gem.
gem 'foo' # => true Foo::VERSION # => NameError: uninitialized constant Foo
-1415446 0 Is the performance due to network latency rather than the approach you're taking? What kind of volumes are you dealing with etc.
I note they won't do replication or log shipping but could you talk them in to do doing some scheduled bulk exports which could be compressed and sent across for an automated routine at the other end to do a bulk insert?
-35844227 0 While loop in shellI am trying to run while loop in shell
NODESTATE="0" LOOPC="1" while [ "$NODESTATE" -ne "UP" ]; do echo "node is up " but it is throwing me an error with [: UP: integer expression expected or shoud i use != instead of -ne
-33860977 0Need to install the actual APK to be able to debug the application
https://blog.nraboy.com/2015/02/properly-testing-ionic-framework-mobile-application/
-2645871 0One goal of Groovy is to have transparent interoperability with Java. Groovy is by design "a Java dependent language with scripting features". However, I don't think that these features are minor - Groovy has many features that are not found in static programming languages (such as Java).
To summarize: If you don't care at all about Java, then use a more general-purpose scripting language, such as Python or Perl. If you want to use the Java code-base in a script-ish way, Groovy is a good option.
-12826718 0Why don't you use ruby's coverage capability or a code coverage tool like SimpleCov?
-12036376 0Please use theDate.ToString({format as you need}) . May be format of date in your locale contains "bad" symbols(slashes).
Formats can be found at http://msdn.microsoft.com/en-us/library/az4se3k1.aspx
-7725822 0If it were
if (mNotification!=null) { mNotification(this, null); } mNotification could be set to null by another thread between if (mNotification!=null) and mNotification(this, null);
I can think of two and a half pure CSS solutions.
First solution requires to wrap all four div's in a container element with position: relative set to it.
Then the blue div can be positioned absolutely and forced to inherit the containers/wrappers height (which comes from the total height of the yellow and green div's) like so:
position: absolute; top: 0; right: 0; bottom: 0; The width of the blue div can be set explicitly, or with left, depending on how responsive the layout needs to be. And the horizontal space taken up by the blue div can be compensated on the wrapper with padding-right.
But no-one really wants extra DOM elements to achieve proper layout, do they.
Another option would be to set position: relative on the green div and place the blue div as a child of the green div in the DOM. Then position the blue div so:
position: absolute; left: 100%; top: -x; /* Whatever is the height of the top yellow div and margin between*/ bottom: x; /* Whatever is the height of the bottom yellow div and margin between */ width: x; /* Set explicitly for example */ This is possible due to the fact that yellow div's are of fixed height.
And extending it further, the entire blue div can be accomplished by the ::after pseudo element on the green div (same CSS applies as for the second solution), but it's suitability depends on what the contents of the blue div need to be.
What is the best yet simple CMS for closed-source programming project hosting? I'd like to keep webpage plain and simple, include screenshot, basic features and blog headlines on main page, then have project blog, screenshots gallery, feature list and downloads on separate pages.
My goal is somethong between http://www.videolan.org/vlc/index.html , http://www.7-zip.org/ and http://winmerge.org/
Suitable themes for general-purpose CMSes are welcome too, but I'm affraid Wordpress or Drupal may too complex for such purposes. Or am I wrong? If I am wrong, please do not post "+1 for WP", but please link theme that meets requirements.
I'd like to host webpage on my own, so Google Code and similar does not fit.
-32250351 0we faced same problem on Galaxy s4 with 5.0 update, after trying many solutions we finally changed protocol of url from http to rtsp (e.g. "http://some/file/url" with "rtsp://some/file/url")and it resolved the issue
-39078600 0The image on a UIImageView is an UIImage optional, meaning that it can have a value (contain an image) or it can be nil.
So, when you're saying:
let ocrSample = myImageView.image your ocrSample is now an UIImage optional, which you then have to unwrap before you use it.
When you then say:
tesseract.image = ocrSample!.fixOrientation().g8_blackAndWhite() you are force unwrapping your ocrSample by using !, meaning that you are telling the compiler to just unwrap and use the optional, regardless of it being nil or not. This causes a crash when you then try to use that unwrapped optional if it contains nil.
What you can do is unwrap ocrSample using an if let like so:
func checkWithOCR() throws{ if let ocrSample = myImageView.image { tesseract.image = ocrSample.fixOrientation().g8_blackAndWhite() if(tesseract.recognize()){ let recognizedText = tesseract.recognizedText if recognizedText != nil{ print("recognizedText: \(recognizedText)") let trimmedText = String(recognizedText.characters.filter { !" \n\t\r,".characters.contains($0) }) myImageView.image = tesseract.image convertCurrency(Float(trimmedText)!) //convert the tesseract text } } SwiftSpinner.hide() } else { //No value could be found, do your error handling here } } Here:
if let ocrSample = myImageView.image you are trying to unwrap the value of myImageView.image into ocrSample, if that succeeds, then you know for sure that ocrSample is not nil and can use it onwards. If it fails, then you can do your error handling, show an alert view and whatever else you need to do.
Hope that helps you.
-12091730 0You need to call rect for each colour that you want to draw, and have those colours in a categorical column in your data frame so that you can filter the data per category for each call to rect.
I don't know what your original data is like, so here's something similar:
# set up simple plotting window plot.new() plot.window(xlim=c(0,6),ylim=c(0,8)) # example data. Using colour as the categorical value we will filter on sample.d <- data.frame(x=c(3,4,5,6), yb=c(1,3,5,7), yt=c(0,2,4,6), colour=c("black","black","red","red")) # draw black rectangles black.d <- sample.d[sample.d$colour == "black",] rect(0, black.d$yb, black.d$x, black.d$yt, col="black") # draw red rectangles red.d <- sample.d[sample.d$colour == "red",] rect(0, red.d$yb, red.d$x, red.d$yt, col="red")
-6582792 0 document.getElementById("theButton").onclick(); Here is an example fiddle.
-13697945 0You Can not disable camera in your regular application.but it is possible to disable using admin setting in ICS and higher versions..check it here http://developer.android.com/guide/topics/admin/device-admin.html
-18899613 0You need to set an expectation on the UsarioService to say what will be returned when usarioService.save(...) is called.
Before getting to that point, you need to say in the test mockUsarioService.createMock() which will create the actual instance of the mock object, that's what you will pass to the controller usarioService attribute. Copied the code below from the Grails documenation. http://grails.org/doc/1.1/guide/9.%20Testing.html
String testId = "NH-12347686" def otherControl = mockFor(OtherService) otherControl.demand.newIdentifier(1..1) {-> return testId } // Initialise the service and test the target method. def testService = new MyService() testService.otherService = otherControl.createMock()
-17684793 0 Stacked shield doesn't have enough power -- dim PWR light I'm stacking a SeeedStudio Bluetooth Shield on top of a Olimex EKG/EMG Shield.
At first, I stacked the two loading only bluetooth shield demo code and all the LEDs lit up brightly and worked fine.
Now (having only taken a shield off and put it back on), the lower shield's (Olimex) power LED appears dim and the upper shield (Bluetooth) is not powered at all. The lower shield's power LED brightens when I remove the top shield.
Not sure what happened here -- both shields work perfectly if they are the ONLY shield on top of the Arduino. Is there any way for me to check the output voltage coming from the lower shield (Olimex) to the higher shield (Bluetooth) with a multimeter to see if it's sufficient (3.3V)?
-26240115 0According to the docs (http://emberjs.com/api/classes/Ember.Handlebars.html#method_registerBoundHelper) you should be using Ember.Handlebars.registerBoundHelper to get this data binding. registerHelper by default is unbound.
Try this tutorial: http://idevzilla.com/2010/10/04/uiscrollview-and-zoom/
It addresses simple zooming and centering.
-29660854 0How about invalidate the current session? Something like this:
public String logout(HttpSession session) { session.invalidate(); .... }
-3153279 0 Are you trying to pass args on the command line?
If so, $0 will contain the script name, and $1..n will contain command line args.
$@ will contain all command line args, space-separated.
-31566473 0 adding hebrew value to sql using PDOI am trying to add a Hebrew value to a database using php's PDO class.
After finally succeeding doing that (by using: array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"), I found out that COLLATE HEBREW_CI_AS is added to my value.
Is there any way to prevent this addition?
thank you, and sorry for my bad English.
-17236454 0This function takes a string argument as input
The first thing it does is checks the recursive base case. We'll get back to that
If the base case is not satisfied, it then checks to see if the first character matches the last character using this code:
if (substr($string,0,1) == substr($string,(strlen($string) - 1),1)) If that does match, then the function recursively calls itself again but this time with the first and last character removed, this is done with this line
return Palindrome(substr($string,1,strlen($string) -2)); If ever the first character does not match the last character, the function automatically outputs to html "STRING IS NOT A PALINDROME via echo
Now back to the base case I mentioned before, if the function successfully matches and removes the first and last character until there are one or no characters left, then the string has been confirmed to be a palindrome and it echos that string.
If you need help with recursion let me know, I'll post a tutorial link
-23070095 0 Better understanding Ajax CORSI have 3 domains that need to work along...
My flow basically works like this:
How "can I"/"should I" implement this behavior?
I set the xhrFields "withCredentials: true" in B.com ajax, but inspecting the request using fiddler, no cookies are sent...
Ps: im kinda lost... if extra info needed pls ask!
-39927552 0 Determining if a node stream is in objectModeGiven a node js stream object how do I determine if it is an object stream in objectMode?
Say I have a readable stream instance
const myReadableStream = new ReadableStreamImplementation({ options: { objectMode : true } }); How can I determine that the myReadableStream is in objectMode. Is there a method or property that can be read? Could not find the answer from skimming through node streams documentation.
EDIT Is there a way to tell without tapping into the stream and given only the stream object itself?
-39622214 0 Disable certain Android Studio compilation errorsI'm extending a hidden java class so I run into the error
Error:Execution failed for task ':app:transformClassesWithInstantRunForDebug'. > class com.company.class.CustomVersion cannot access its superclass java.class.JavaVersion However, if I don't rely on Android Studio, output a jar, and then add the jar as a dependency to the same project I don't get the above compilation error and the app can launch. Since I'm writing my own library, I'd prefer not to have to create and export a jar every time I want to test some code change. Is there a way of disabling compilations errors like the above for a class?
EDIT:
For more information I was trying to extend a hidden Android class in the java.net package.
-26104618 0The li elements are hard coded into your list. To put them into a div you can either hard code them into the preferred div or use javascript to dynamically change the html code. It would probably be easier to just code a short list into the adjacent div, but if this is a list that gets generated in some way, css can change how things are displayed, but the location of you li items are still part of the parent div. Css is for styling and placing on the screen not for changing parent elements.
-7691666 0You should go with the second approach.
One possible solution is a greedy algorithm. Define your set of transformations as a regular expression (used to test the pattern) and a function which is given the regexp match object and returns the transformed string.
Regular expressions aren't quite powerful enough to handle what you want directly. Instead you'll have to do something like:
m = re.match(r"C\[(\d+)\]H\[(\d+)]\]", formula) if m: C_count, H_count = int(m.group(1)), int(m.group(2)) match_size = len(m.group(0)) if C_count*2+2 == H_count: replacement = alkane_lookup[C_count] elif C_count*2 == H_count: replacement = alkene_lookup[C_count] ... else: replacement = m.group(0) # no replacement available (plus a lot more for the other possibilities)
then embed that in a loop which looks like:
formula = "...." new_formula = "" while formula: match_size, replacement = find_replacement(formula) new_formula += replacement formula = formula[match_size:] (You'll need to handle the case where nothing matches. One possible way is to include a list of all possible elements at the end of find_replacement(), which only returns the next element and counts.)
This is a greedy algorithm, which doesn't guarantee the smallest solution. That's more complicated, but since chemists themselves have different ideas of the right form, I wouldn't worry so much about it.
-19338908 0Linear Diophantine equations take the form ax + by = c. If c is the greatest common divisor of a and b this means a=z'c and b=z''c then this is Bézout's identity of the form

with a=z' and b=z'' and the equation has an infinite number of solutions. So instead of trial searching method you can check if c is the greatest common divisor (GCD) of a and b (in your case this translates into bx - dy = c - a)
If indeed a and b are multiples of c then x and y can be computed using extended Euclidean algorithm which finds integers x and y (one of which is typically negative) that satisfy Bézout's identity

and your answer is:
a = k*x, b = k*y, c - a = k * gcd(a,b) for any integer k.
(as a side note: this holds also for any other Euclidean domain, i.e. polynomial ring & every Euclidean domain is unique factorization domain). You can use Iterative Method to find these solutions:
By routine algebra of expanding and grouping like terms (refer to last section of wikipedia article mentioned before), the following algorithm for iterative method is obtained:
pseudocode:
function extended_gcd(a, b) x := 0 lastx := 1 y := 1 lasty := 0 while b ≠ 0 quotient := a div b (a, b) := (b, a mod b) (x, lastx) := (lastx - quotient*x, x) (y, lasty) := (lasty - quotient*y, y) return (lastx, lasty) So I have written example algorithm which calculates greatest common divisor using Euclidean Algorithm iterative method for non-negative a and b (for negative - these extra steps are needed), it returns GCD and stores solutions for x and y in variables passed to it by reference:
int gcd_iterative(int a, int b, int& x, int& y) { int c; std::vector<int> r, q, x_coeff, y_coeff; x_coeff.push_back(1); y_coeff.push_back(0); x_coeff.push_back(0); y_coeff.push_back(1); if ( b == 0 ) return a; while ( b != 0 ) { c = b; q.push_back(a/b); r.push_back(b = a % b); a = c; x_coeff.push_back( *(x_coeff.end()-2) -(q.back())*x_coeff.back()); y_coeff.push_back( *(y_coeff.end()-2) -(q.back())*y_coeff.back()); } if(r.size()==1) { x = x_coeff.back(); y = y_coeff.back(); } else { x = *(x_coeff.end()-2); y = *(y_coeff.end()-2); } std::vector<int>::iterator it; std::cout << "r: "; for(it = r.begin(); it != r.end(); it++) { std::cout << *it << "," ; } std::cout << "\nq: "; for(it = q.begin(); it != q.end(); it++) { std::cout << *it << "," ; } std::cout << "\nx: "; for(it = x_coeff.begin(); it != x_coeff.end(); it++){ std::cout << *it<<",";} std::cout << "\ny: "; for(it = y_coeff.begin(); it != y_coeff.end(); it++){ std::cout << *it<<",";} return a; } by passing to it an example from wikipedia for a = 120 and b = 23 we obtain:
int main(int argc, char** argv) { // 120x + 23y = gcd(120,23) int x_solution, y_solution; int greatestCommonDivisor = gcd_iterative(120, 23, x_solution, y_solution); return 0; } r: 5,3,2,1,0,
q: 5,4,1,1,2,
x: 1,0,1,-4,5,-9,23,
y: 0,1,-5,21,-26,47,-120,
what is in accordance with the given table for this example:

The answer is highly situational. In general, you want to handle exceptions elegantly whenever possible. That is, try to resolve / ignore them where you can. An IndexOutOfBoundsException is very often an example of where this is not possible.
Hard breaks because of exceptions is a last-resort. Do this only when your program cannot continue.
This question's answer has a good post on it. When to throw an exception?
-31633257 0I think you forget array like this:
1 0 0 9 1 1 0 1 0 1 1 1 0 0 0 1 your recursive function will not be finished in the previous example, please check the size of array to finish recursion.
Also your algorithm does not use up and right to find cheese
EDIT
you should handle the 4 directions, and don't repeat the square you visit before, I will add pseudo code here to explain the main idea of solution:
public class MAZE { static int x, y; static boolean result = false; public static void main(String[] args) { int [][] matrix =new int[5][];// fill your array // fill x and y // x= cheese x value // y = cheese y value isPath(matrix, x, x); // print result } static void isPath(int[][] matrix, int i, int j) { if (i - 1 > -1 && matrix[i - 1][j] == 1) { // subarray1 = copy starting from [0][0] to matrix[i-1][j] // checkSPath(subarray1,i-1,j); } if (j - 1 > -1 && matrix[i][j - 1] == 1) { // subarray1 = copy starting from [0][0] to matrix[i][j-1] // checkLPath(subarray1,i,j-1); } if (i + 1 < x && matrix[i + 1][j] == 1) { // subarray1 = copy starting from [0][0] to matrix[i+1][j] // checkNPath(subarray1,i+1,j); } if (j + 1 < y && matrix[i][j + 1] == 1) { // subarray1 = copy starting from [0][0] to matrix[i][j+1] // checkRPath(subarray1,i,j+1); } } static void checkRPath(int[][] matrix, int i, int j) { if (i == 0 && j == 0) { result = true; } else { if (i - 1 > -1 && matrix[i - 1][j] == 1) { // subarray1 = copy starting from [0][0] to matrix[i-1][j] // checkSPath(subarray1,i-1,j); } if (i + 1 < x && matrix[i + 1][j] == 1) { // subarray1 = copy starting from [0][0] to matrix[i+1][j] // checkNPath(subarray1,i+1,j); } if (j + 1 < y && matrix[i][j + 1] == 1) { // subarray1 = copy starting from [0][0] to matrix[i][j+1] // checkRPath(subarray1,i,j+1); } } } static void checkLPath(int[][] matrix, int i, int j) { if (i == 0 && j == 0) { result = true; } else { if (i - 1 > -1 && matrix[i - 1][j] == 1) { // subarray1 = copy starting from [0][0] to matrix[i-1][j] // checkSPath(subarray1,i-1,j); } if (j - 1 > -1 && matrix[i][j - 1] == 1) { // subarray1 = copy starting from [0][0] to matrix[i][j-1] // checkLPath(subarray1,i,j-1); } if (i + 1 < x && matrix[i + 1][j] == 1) { // subarray1 = copy starting from [0][0] to matrix[i+1][j] // checkNPath(subarray1,i+1,j); } } } static void checkNPath(int[][] matrix, int i, int j) { if (i == 0 && j == 0) { result = true; } else { if (j - 1 > -1 && matrix[i][j - 1] == 1) { // subarray1 = copy starting from [0][0] to matrix[i][j-1] // checkLPath(subarray1,i,j-1); } if (i + 1 < x && matrix[i + 1][j] == 1) { // subarray1 = copy starting from [0][0] to matrix[i+1][j] // checkNPath(subarray1,i+1,j); } if (j + 1 < y && matrix[i][j + 1] == 1) { // subarray1 = copy starting from [0][0] to matrix[i][j+1] // checkRPath(subarray1,i,j+1); } } } static void checkSPath(int[][] matrix, int i, int j) { if (i == 0 && j == 0) { result = true; } else { if (i - 1 > -1 && matrix[i - 1][j] == 1) { // subarray1 = copy starting from [0][0] to matrix[i-1][j] // checkSPath(subarray1,i-1,j); } if (j - 1 > -1 && matrix[i][j - 1] == 1) { // subarray1 = copy starting from [0][0] to matrix[i][j-1] // checkLPath(subarray1); } if (j + 1 < y && matrix[i][j + 1] == 1) { // subarray1 = copy starting from [0][0] to matrix[i][j+1] // checkRPath(subarray1); } } } } You can merge these 5 methods in one. here I am trying to explain the solution not writing optimized code.
-10684657 0 DataGrid not displaying dataI am trying to display a DataGrid on my mobile application after reading a CSV file and processing it. Here is what I have so far:
private void btOpenFile_Click(object sender, EventArgs e) { try { // Process all data into an array of Object // this.records array contains objects of type MyRecord // Create datatable and define columns DataTable dt = new DataTable("myDt"); dt.Columns.Add( new DataColumn("String A",typeof(string))); dt.Columns.Add( new DataColumn("Int 1", typeof(int))); // Loop through and create rows foreach(MyRecord record in records) { DataRow row = dt.NewRow(); row[0] = record.stringA; row[1] = record.int1; dt.Rows.Add(row); } // Create dataset and assign it to the datasource.. DataSet ds = new DataSet("myDs"); ds.Tables.Add(dt); dataGrid.DataSource = ds; dataGrid.Refresh(); } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message,"Error"); } } All I get is a blank data grid component when running my application. Can somebody point out my mistake? or how to do this correctly?
-34294372 0 What are the cases in general which require template argument to be complete?Consider simple code :
struct x; template<typename> void func(){} int main() { func<x>(); return 0; } This above code doesn't requires class x to be complete, are there any other cases which don't require x to be complete? . Also in general what are the cases which require template argument to be complete?
Try to add method atribute for form, like
<form action="'+url+'" method="post" target="_blank"></form> UPDATED But you can't store data in your url. Post should send params in body, not in URL. So your url should be like '/index.php'. And your params should be in body, so add all your page, action, etc to form's hidden fields.
<form action="/index.php" method="post" target=...> <input type="hidden" name="action" value="InvoicePrint"/> ............ </form> or use jQuery post
$.ajax({ type: "POST", url: '/index.php', data: data, success: success }); Where data is object with all your params
-2828051 0Extend java.util.Properties, override both put() and keys():
import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Properties; import java.util.HashMap; public class LinkedProperties extends Properties { private final HashSet<Object> keys = new LinkedHashSet<Object>(); public LinkedProperties() { } public Iterable<Object> orderedKeys() { return Collections.list(keys()); } public Enumeration<Object> keys() { return Collections.<Object>enumeration(keys); } public Object put(Object key, Object value) { keys.add(key); return super.put(key, value); } }
-25249886 0 The batch script below will print out the existing default JRE. It can be easily modified to find the JDK version installed by replacing the Java Runtime Environment with Java Development Kit.
@echo off setlocal ::- Get the Java Version set KEY="HKLM\SOFTWARE\JavaSoft\Java Runtime Environment" set VALUE=CurrentVersion reg query %KEY% /v %VALUE% 2>nul || ( echo JRE not installed exit /b 1 ) set JRE_VERSION= for /f "tokens=2,*" %%a in ('reg query %KEY% /v %VALUE% ^| findstr %VALUE%') do ( set JRE_VERSION=%%b ) echo JRE VERSION: %JRE_VERSION% ::- Get the JavaHome set KEY="HKLM\SOFTWARE\JavaSoft\Java Runtime Environment\%JRE_VERSION%" set VALUE=JavaHome reg query %KEY% /v %VALUE% 2>nul || ( echo JavaHome not installed exit /b 1 ) set JAVAHOME= for /f "tokens=2,*" %%a in ('reg query %KEY% /v %VALUE% ^| findstr %VALUE%') do ( set JAVAHOME=%%b ) echo JavaHome: %JAVAHOME% endlocal
-20114461 0 adding a layer mask to UIToolBar/UINavigationBar/UITabBar breaks translucency Im upgrading my UI to iOS 7, and have been using a custom tab bar which has a CAShapeLayer used as a mask. Ive been trying to add dynamic blur by having a UIToolBar underneath, but if i try setting the layer.mask property on the toolbar translucency is gone, and i just have it semi transparent (but masking works of course). Is there a way to get this working? Ive also seen this behavior when adding a subview to these classes.
-27517010 0Do you set the constraint for the label. or the label is too height for the superview , so it covers the all subviews , so you can use the lldb po the label size ,when you set the text into the label.
-28169229 0on the second approach i will get a notification if the 'controller' object on self was replaced
I would rephrase by saying that on the second approach you'll get notified if the controller object gets replaced or if its isEnabled property changes. In other word when controller.isEnabled changes (as explained by Ken's answer).
Check this example:
- (void)viewDidLoad { [super viewDidLoad]; self.controller = [[ViewController2 alloc] init]; [self.controller addObserver:self forKeyPath:@"isEnabled" options:NSKeyValueObservingOptionNew context:nil]; [self addObserver:self forKeyPath:@"controller.isEnabled" options:NSKeyValueObservingOptionNew context:nil]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ self.controller.isEnabled = !self.controller.isEnabled; // replace controller [self.controller removeObserver:self forKeyPath:@"isEnabled"]; self.controller = [[ViewController2 alloc] init]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ self.controller.isEnabled = !self.controller.isEnabled; }); }); } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { NSLog(@"KVO %d %@ %p", self.controller.isEnabled, keyPath, self.controller); } We'll get 4 KVO notifications:
KVO 1 controller.isEnabled 0x7fbbc2e4b4e0 <-- These 2 fire together when we toggle isEnbled KVO 1 isEnabled 0x7fbbc2e4b4e0 <-- So basically 1. and 2. behave the same KVO 0 controller.isEnabled 0x7fbbc2e58d30 <---- controller was replaced KVO 1 controller.isEnabled 0x7fbbc2e58d30 <---- Toggle on the new instance
-14697454 0 Where can I get debug symbols (PDB) for Windows.Live.dll? I am using the Microsoft Live SDK for Windows Phone to access SkyDrive and get an exception in Microsoft.Live.dll. I'd like to step through the source to debug the issue, but fetching symbols from symbol server http://msdl.microsoft.com/download/symbols fails.
I followed these instructions on how to set up the symbol server in my dev environment. The environment variable _NT_SYMBOL_PATH is set to srv*c:\symbols*http://msdl.microsoft.com/download/symbols. This seems to work for other assemblies. While debugging I see the symbol cache at c:\symbols grow with entries, but Microsoft.Live is missing.
Where can I get debug symbols for Microsoft.Live.dll?
-31292398 0The way to do this is to use the <script> tag instead of <% ... %> for your code block:
<script language="vbscript" runat="server"> Response.Write "<%= Count %>" </script> Output:
<%= Count %>
-1947215 0 after searching for all available options , I found that the best way to set a variable in a process definition through the tag
-5833026 0 Extract IPTC information from JPEG using JavascriptI'm trying to extract IPTC photo caption information from a JPEG file using Javascript. (I know I can do this server-side, but I'm looking specifically for a Javascript solution.)
I found this script, which extracts EXIF information ... but I'm not sure how to adapt it to grab IPTC data.
Are there any existing scripts that offer such functionality? If not, how would you modify the EXIF script to also parse IPTC data?
UPDATE
I've modified the EXIF script I linked above. It sorta does what I want, but it's not grabbing the right data 100 percent of the time.
After line 401, I added:
else if (iMarker == 237) { // 0xED = Application-specific 13 (Photoshop IPTC) if (bDebug) log("Found 0xFFED marker"); return readIPTCData(oFile, iOffset + 4, getShortAt(oFile, iOffset+2, true)-2); } And then elsewhere in the script, I added this function:
function readIPTCData(oFile, iStart, iLength) { exif = new Array(); if (getStringAt(oFile, iStart, 9) != "Photoshop") { if (bDebug) log("Not valid Photoshop data! " + getStringAt(oFile, iStart, 9)); return false; } var output = ''; var count = 0; two = new Array(); for (i=0; i<iLength; i++) { if (getByteAt(oFile, iStart + i) == 2 && getByteAt(oFile, iStart + i + 1) == 120) { var caption = getString2At(oFile, iStart + i + 2, 800); } if (getByteAt(oFile, iStart + i) == 2 && getByteAt(oFile, iStart + i + 1) == 80) { var credit = getString2At(oFile, iStart + i + 2, 300); } } exif['ImageDescription'] = caption; exif['Artist'] = credit; return exif; } So let me now modify my question slightly. How can the function above be improved?
-12835598 0So in other words, your query is vulnerable with SQL Injection. Better use PDO or MySQLi Extension since you tagged `PHP.
Take time to read on this article: Best way to prevent SQL injection in PHP?
-32368788 0 Filter NSDictionary from NSArrayI have One NSArray That contains NSDictionary Object with keys{"name","age","weight"} where the key name is NSString ,age is NSInteger ,weight is float Value
I need to filter the NSArray with the following conditions 1.name contains 'abc' 2.age below 18 3.weight less than 50
Answer will be Appreciated
-36404693 0 Get latest version of table using hive union-all operatorI have versioned hive tables containing metrics partitioned by date that I want to join with other versioned hive tables containing different (but related) metrics also partitioned by date. For example:
Table A_v1 (exists for day 1) | col1 | col2 | | a1 | b1 | | a2 | b2 | Table A_v2 (exists for day 2, represents metrics derivation algorithm change) | col1 | col2 | | a3 | b3 | | a4 | b4 | Table B_v1 (exists for both day 1 and day 2) | col3 | col4 | | a1 | c1 | | a2 | c2 | | a3 | c3 | | a4 | c4 | I know I can use the UNION ALL Hive operator to basically concatenate tables A_v1 and A_v2. What I would like to do however is write something like
select a.col1, a.col2, b.col4 from union(A_v1, A_v2) a, B_v1 b where a.col1=b.col3 I know the above syntax is wrong (intended only as a pseudo-code query) but is there some way of accomplishing the same thing in Hive?
-35703569 0The image you've shown is probably a UISegmentedControl. That's how you tap something so that it stays selected (and other choices are deselected). It's easy to customize a segmented control so that the background image is different when a segment is selected vs. when it is not.
-40971656 0 Data not storing in SQLite databaseNew to PHP. I am trying to create a register and Log In form using PHP and SQLite. Below is my code.
register.php
<?php class MyDB extends SQLite3 { function __construct() { $this->open('db/db.db'); } } $db = new MyDB(); if(!$db) { echo $db->lastErrorMsg(); } else { echo 'Open successfull'; } ?> <!DOCTYPE html> <html lang="en"> <head> <title>admin portal</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="css/style.css" media="screen"> </head> <body> <div align="center"> <div class="form-area"> <form action="" method="post" enctype="multipart/form-data"> <input type="text" name="fname" value="" placeholder="First Name"> <input type="text" name="lname" value="" placeholder="Last Name"> <input type="text" name="username" value="" placeholder="Username"> <input type="email" name="email" value="" placeholder="Email"> <input type="password" name="password" value="" placeholder="Password"> <input type="password" name="cfpassword" value="" placeholder="Confirm Password"> <input type="submit" name="register" value="Register"><br> </form> </div> </div> </body> </html> <?php if (isset($_POST["submit"])) { $fname = $_POST['fname']; $lname = $_POST['lname']; $username = $_POST['username']; $email = $_POST['email']; $password = $_POST['password']; $cfpassword = $_POST['cfpassword']; $sql = <<<EOF INSERT INTO USERS (ID, FNAME, LNAME, USERNAME, EMAIL, PASSWORD, PASSCONFIRM) VALUES (1, '$fname', '$lname', '$username', '$email', '$password', $cfpassword ); EOF; $ret = $db->exec($sql); if(!$ret){ echo $db->lastErrorMsg(); } else { echo "Registered Successfully\n"; } $db->close(); } ?> db.php
<?php class MyDB extends SQLite3 { function __construct() { $this->open('db/db.db'); } } $db = new MyDB(); if(!$db) { echo $db->lastErrorMsg(); } else { echo 'Open successfull'; } $sql =<<<EOF CREATE TABLE USERS (ID INT PRIMARY KEY NOT NULL, EMAIL VARCHAR(250) NOT NULL, PASSWORD VARCHAR(250) NOT NULL, FNAME VARCHAR(250) NOT NULL, LNAME VARCHAR(250) NOT NULL, ACCESS VARCHAR(250) NOT NULL, IMAGE VARCHAR(250) NOT NULL, DATE DATETIME NOT NULL, USERNAME VARCHAR(250) NOT NULL, PASSCONFIRM VARCHAR(250) NOT NULL); EOF; $ret = $db->exec($sql); if(!$ret){ echo $db->lastErrorMsg(); } else { echo "Table created successfully"; } ?> Please what's wrong with this code. The database opens but registered data is no stored into database. Would also appretiate if i can be linked to a material to read on SQLite3 and HTML forms.
-14199897 0Question abandoned because it seems unanswerable. Will update if I find a solution at a later date.
-23214589 0this values set in CWebUser class, in login method, look this and this.
"8f9f85051824e063ad61f50fedc52f93" is prefix generated in method getStateKeyPrefix
-7716729 0 java.lang.ClassCastException: org.hibernate.hql.ast.tree.SqlNode cannot be cast to org.hibernate.hql.ast.tree.FromReferenceNodeIm trying to update a record with a HQL query but I am getting a CastException. If anyone could help me out I would really appreciate it. I have checked the Internet for a while now but I cant find any information on this. Please let me know if you have more information on this exception.
The full error message its returning:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: org.hibernate.hql.ast.tree.SqlNode cannot be cast to org.hibernate.hql.ast.tree.FromReferenceNode at org.hibernate.hql.ast.HqlSqlWalker.generateSyntheticDotNodeForNonQualifiedPropertyRef(HqlSqlWalker.java:495) at org.hibernate.hql.ast.HqlSqlWalker.lookupNonQualifiedProperty(HqlSqlWalker.java:488) at org.hibernate.hql.antlr.HqlSqlBaseWalker.propertyRef(HqlSqlBaseWalker.java:1102) at org.hibernate.hql.antlr.HqlSqlBaseWalker.assignment(HqlSqlBaseWalker.java:1008) at org.hibernate.hql.antlr.HqlSqlBaseWalker.setClause(HqlSqlBaseWalker.java:729) at org.hibernate.hql.antlr.HqlSqlBaseWalker.updateStatement(HqlSqlBaseWalker.java:349) at org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:237) at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:228) at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:160) at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:111) at org.hibernate.engine.query.HQLQueryPlan.(HQLQueryPlan.java:77) at org.hibernate.engine.query.HQLQueryPlan.(HQLQueryPlan.java:56) at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:72) at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:133) at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:112) at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1623) at Database.HibernateConnection.updateFlight(HibernateConnection.java:161) at Controller.Controller.ChangeFlight(Controller.java:527) at View.CreateChangeFlightView.btnSaveActionPerformed(CreateChangeFlightView.java:738) at View.CreateChangeFlightView.access$1000(CreateChangeFlightView.java:45) at View.CreateChangeFlightView$6.actionPerformed(CreateChangeFlightView.java:299) at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995) at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318) at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387) at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236) at java.awt.Component.processMouseEvent(Component.java:6263) at javax.swing.JComponent.processMouseEvent(JComponent.java:3267) at java.awt.Component.processEvent(Component.java:6028) at java.awt.Container.processEvent(Container.java:2041) at java.awt.Component.dispatchEventImpl(Component.java:4630) at java.awt.Container.dispatchEventImpl(Container.java:2099) at java.awt.Component.dispatchEvent(Component.java:4460) at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4574) at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238) at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168) at java.awt.Container.dispatchEventImpl(Container.java:2085) at java.awt.Window.dispatchEventImpl(Window.java:2478) at java.awt.Component.dispatchEvent(Component.java:4460) at java.awt.EventQueue.dispatchEvent(EventQueue.java:599) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161) at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
query: deleted
-35813904 0If your compiler supports C++ 2011 then you can write the following way providing that letters will be listed in the order in which they are present in the string
#include <iostream> #include <string> #include <map> int main() { std::string s( "slowly" ); auto comp = [&]( char c1, char c2 ) { return s.find( c1 ) < s.find( c2 ); }; std::map<char, int, decltype( comp )> m( comp ); for ( char c : s ) ++m[c]; for ( auto p : m ) std::cout << p.first << ": " << p.second << std::endl; } The program output is
s: 1 l: 2 o: 1 w: 1 y: 1 Otherwise if the compiler does not support C++ 2011 then instead of the lambda you have to use a function class defined before main. Also youi should substitute the range-based for loop for an ordinary loop.
-13420281 0You can store the values in MySQL as INT UNSIGNED which occupies 4 bytes (i.e. 32 bits).
To insert the values into the database, you must use sprintf() with %u format on 32 bit machines:
$hash = crc32("The quick brown fox jumped over the lazy dog."); $stmt = $db->prepare('INSERT INTO mytable VALUES (:hash)'); $stmt->execute(array( ':hash' => sprintf('%u', $hash), )); Update
You could also make sure that you're always working with int32 types (signed long) on both 32 and 64-bit platforms. Currently, you can only accomplish this by using pack() and unpack():
echo current(unpack('l', pack('l', $hash))); // returns -2103228862 on both 32-bit and 64-bit platforms The idea for this was contributed by mindplay.dk
-40314237 0 Progress Bar with Ajax JQuery and PHP for import a .csv file to MySQLI tried to write a code for a progress bar using PHP, JQuery and HTML. So, I made a Ajax Request for a PHP file and in the success Ajax parameter I search a data requested from PHP File like this..
success: function(data){ if(data == 'Error1'){ alert("The File is not a .csv"); }else if(data == "Error2"){ alert("Please select a file to import!"); }else{ $('#consumidor_table').html(data); alert("The importation has been made!"); } } That else does print a Table with MySql DB lines. The PHP file read a .csv from a HTML input and insert those lines in DB.
Actually, my code to do a progress bar is it: Before at success parameter
xhr: function(){ var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener("progress", function(evt){ if (evt.lengthComputable) { var percentComplete = evt.loaded / evt.total; console.log(evt.loaded); console.log(evt.total); console.log(percentComplete*100); addProgress(percentComplete*100); } }); return xhr; }, The entire codes: JQuery; PHP URL
The Error: When a upload a file and submit the form, the console.log(evt.total); and console.log(evt.loaded); print the same value, and them the progress bar is fully, but the Ajax continues requesting the PHP file and my table is empty yet.
So what I can do to my progress bar work with the response from PHP file?
-1338585 0I've found that qTip has met all of my tooltip needs:
-28075373 0Here's the corresponding docs for testing iphone/ipad: https://github.com/angular/protractor/blob/master/docs/mobile-setup.md#setting-up-protractor-with-appium---iossafari
I would suggest you test using a local device first if sauce doesn't work for you at first try, so you can narrow down the issue (unless you don't have a mac or physical ipad to test with that is).
-12824913 0SO, you don't want the lower bound to be inclusive, right?
SET @value = 2; SELECT * FROM table WHERE from > @value AND @value <= to;
-27554301 0 The problem is that you have the same id for both accordions (which is invalid html to start with) which makes the plugin always match the first one.
If you use classes it works fine
<div class="accordion"> <h3>Home</h3> <div class="accordion"> <h3>Sub-Div1</h3> <div> <p>This is a sub-div</p> </div> </div> </div> and
$(".accordion").accordion({ header: "> h3:not(.item)", heightStyle: "content", active: false, collapsible: true }); Demo at http://jsfiddle.net/gaby/xmq8xhvp/
-2041501 0In Autofac you use Modules for this purpose. Groups of related components are encapsulated in a module, which is configured by the programmatic API.
Autofac's XML configuration has support for modules, so once you've decided to use one in an applicaiton, you can register the module (rather than all the components it contains) in the config file.
Modules support parameters that can be forwarded to the components inside, e.g. connection strings, URIs, etc.
The documentation here should get you started: http://code.google.com/p/autofac/wiki/StructuringWithModules
HTH
Nick
-35966987 0 Storing data to Flash in Wireless Sensor Networks on loosing connectionI have to implement an optimal solution to store values of sensor into NOR Flash with time stamps on loosing connection and send to the central server when connection comes back. A queue like implementation is needed. Will anyone please suggest an implementation Open source or proprietary, or any algorithms for same. It should have properties like wear leveling, write fail safe and erase fail safe.
It is a 256Mb Spansion NOR flash(S25FL256S). I need to store only less than 64bytes (including time stamp) every 60 seconds, if there is no connection. Page size of flash is 256 bytes and sector size is 256KB. Erase cycle endurance of flash is 100,000
-7908699 0The memory usage of a two dimensional array is slightly bigger, but this may result from bad code (?).
<!-- http://php.net/manual/en/function.memory-get-usage.php array1: 116408 (1D 1001 keys) (1x 100.000 keys: 11.724.512) array2: 116552 (2D, 1002 keys) (2x 50.000 keys: 11.724.768) total: +144 +256 --> <?php function genRandomString() { $length = 10; $characters = '0123456789abcdefghijklmnopqrstuvwxyz'; $string = ''; for ($p = 0; $p < $length; $p++) { $string .= $characters[mt_rand(0, strlen($characters))]; } return $string; } $i = 0; // ----- Larger 1D array ----- $mem_start = memory_get_usage(); echo "initial1: " . $mem_start . "<br />"; $arr = array(); for ($i = 1; $i <= 1000; $i++) { $arr[ genRandomString() ] = "Hello world!"; } echo "array1: " . (memory_get_usage() - $mem_start) . "<br />"; unset($arr); // ----- 2D array ----- $mem_start = memory_get_usage(); $arr2 = array(); echo "initial2: " . $mem_start . "<br />"; for ($i = 1; $i <= 500; $i++) { $arr2["key______1"][ genRandomString() ] = "Hello world!"; $arr2["key______2"][ genRandomString() ] = "Hello world!"; } echo "array2: " . (memory_get_usage() - $mem_start) . "<br />"; unset($arr2); unset($i); unset($mem_start) echo "final: " . memory_get_usage() . "<br />"; ?>
-40586241 0 This isn't an answer but it is too long for a comment: sorry.
There are three possibilities for creating variable bindings that seem to be common:
An example of (3) is Python. Languages which do this end up needing explicit scope-resolution operators (global and now nonlocal in Python) to deal with the stupid, lazy, pun they have done and are not worth discussing further: you need binding constructs which are distinct from assignment or you end up living in pain for ever.
Common Lisp is an example of (1), and C used to be: they are both (C was) examples of languages where all the bindings needed to be created at the start of a scope construct.
Within (1) there are languages which have some kind of block construct ({ ... } in C) which can be used for grouping and for scope, and ones which have a grouping construct and one or more separate scoping constructs: CL is in the latter family.
So in (old) C you would say
{ int i = 3; ... } While in CL you say
(let ((i 3)) ...) -- the scope construct here is let (and there are others of course).
Of course, CL, being a Lisp, can perfectly happily invent a construct which looks like C's blocks:
(defmacro scope (&body vars/body) (loop for (var? . body?) on vars/body while (and (listp var?) (<= 2 (length var?) 3) (eql (first var?) 'var) (symbolp (second var?))) collect (case (length var?) (2 (second var?)) (3 (rest var?))) into bindings finally (return `(let* ,bindings ,var? ,@body?)))) And now
(scope (var a) (var b 2) ...) is a construct in the language.
So really these two variants on (1) are more similar than they are different: it's just a matter of how you cut up the underlying constructs you want in the language: C conflated scope blocks and grouping, CL doesn't.
(2) is different however. Here you are allowed to intermingle binding constructs and other things within a scope construct. C is now like this, and so is JavaScript. CL is not like this natively (obviously, being a Lisp, it could become like this with some macrology, although that macrology would be a lot hairier than what I wrote above).
In such a language you really need a separate binding-creation construct, because it can't be part of the scoping construct. Languages like C already treat the binding-creation construct as separate, so for them it's just a matter of relaxing the rule which says bindings must all be created at the start of a scope construct.
Languages like this have a significant question to answer though: what is the scope of a binding? Does something like
{ ... int x = 3; ... } Really mean
{ ... { int x = 3; ... } } or does it mean
{ int x; ... x = 3; ... } The latter case is easier, but means that there's an awkward region where references to x are legal but its value may not be well-defined. C takes the former interpretation I think.
This is mostly fine for languages like C where the grouping construct is the same as the scoping construct. But it's not fine for languages like JavaScript where the grouping construct is not the scoping construct and, worse, where there is no scoping construct other than functions (or used not to be). And in fact languages like that can't really fix the problem, since there's no useful scoping construct. Well, of course, they fix it by growing a scoping construct.
Note that although CL is a (1) language there are Lisp-family languages which are (2) languages: in particular Racket is. In Racket (but not, I think, in Scheme) you can say
(define (foo) (define bar 1) ;; is baz bound here? (display bar) (define baz 3) (list bar baz)) And the answer is that yes, baz is bound there, but it's bound to an undefined object and you'll get an error (at run time, not compile time) if you try to use it. So this is a run-time error:
(define (foo) (define bar 1) (display baz) (define baz 3) (list bar baz))
while this
(define (foo) (define bar 1) (display baz) (let () (define baz 3) (list bar baz))) is a compile time error. (I am actually slightly confused about which constructs in Racket create scopes.)
-12726216 0 Saving a DIV as an ImageI have:
echo" <div id=IwantToSaveThisWholeDivAsAnImage)> <div id=OneOfMultipleDivs> <table>multiple tables rendered here </table> </div> </div>"; I have tried (one of many):
$html_code = " <html> <head> <title>Image</title> <style> body { font-family:verdana; font-size:11px; color:black } </style> </head> <body> my tables here </body> </html>"; $img = imagecreate("300", "600"); $c = imagecolorallocate($img, 0, 0, 0); $c2 = imagecolorallocate($img, 255, 255, 255); imageline($img,0,0,300,600,$c); imageline($img,300,0,0,600,$c2); $white = imagecolorallocate($img, 255, 255, 255); imagettftext($img, 9, 0, 1, 1, $white, "arial.tff", '$html_code'); header("Content-type: image/jpeg"); imagejpeg($img); I'm not allowed to use outside libaries. Read that it can be done with GD, but I have been unsuccessful thus far. Any ideas and help would be greatly appreciated! UB
-14221583 0Getting location from Android device go through this :
Get current location during app launch
Process Initiated from device : now you have coordinates now in you application so what you can do on launching of a web make an AsyncTask to hit the webservice passing these longitude and latitude and get the corresponding message as response.
Process Initiated from server: for that you need to implement a GCM push functionality in your application what server needs to do it will push a message to device and after getting the push do the same thing as mentioned in process initiated from device.
-16115641 0 Is an image that is display: none loaded by the browser?Are these images loaded by the browser:
<div style="display: none"> <img src="/path/to/image.jpg" alt=""> </div> or
<img src="/path/to/image.jpg" alt="" style="display: none;"> By "loaded by the browser" I mean, are these images loaded immediately by the browser so that they are available right away when the image is no longer displayed as none using css. Will it be taken from cache or loaded anew the moment it is no longer displayed as none?
-36894812 0other solution for your question.
var app = angular.module("testApp", []); app.controller('testCtrl', function($scope){ $scope.data = [{ "fleetcheckitemid": "1", "checkitemdesc": "Engine oil level", "answers": [{ "fleetcheckid": "1", "checkvaluedesc": "Ok" }, { "fleetcheckid": "2", "checkvaluedesc": "Low" }, { "fleetcheckid": "3", "checkvaluedesc": "Top-Up Required" }] }, { "fleetcheckitemid": "2", "checkitemdesc": "Water level", "answers": [{ "fleetcheckid": "1", "checkvaluedesc": "Ok" }, { "fleetcheckid": "2", "checkvaluedesc": "Low" }, { "fleetcheckid": "3", "checkvaluedesc": "Top-Up Required" }] }, { "fleetcheckitemid": "3", "checkitemdesc": "Brake fluid level", "answers": [{ "fleetcheckid": "1", "checkvaluedesc": "Ok" }, { "fleetcheckid": "2", "checkvaluedesc": "Low" }, { "fleetcheckid": "3", "checkvaluedesc": "Top-Up Required" }] }]; angular.forEach($scope.data,function(value,key){ console.log(value.fleetcheckitemid); console.log(value.checkitemdesc); angular.forEach(value.answers,function(v,k){ console.log(v.fleetcheckid); console.log(v.checkvaluedesc); }); }); }); <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="testApp" ng-controller="testCtrl"> </div> If you have the rsvp_event permission for the user you can RSVP them to any event they have permission to join (i.e public events) See here: https://developers.facebook.com/docs/reference/api/event/#attending
Sorry if my vb is wrong as im a c# guy!! but I hope this should give you a guidance. I do something similar in c#. Good luck
Protected Sub dvPictureInsert_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertEventArgs) Handles dvPictureInsert.ItemInserting Dim cancelInsert As Boolean = False Dim imageUpload As FileUpload = CType(dvPictureInsert.FindControl("imageUpload"), FileUpload) If Not imageUpload.HasFile Then cancelInsert = True Else If Not imageUpload.FileName.ToUpper().EndsWith(".JPG") Then cancelInsert = True 'Invalid image file! Else Dim image As System.Drawing.Image = System.Drawing.Image.FromStream(imageUpload.PostedFile.InputStream) If image.Width > 600 Or image.Height > 700 Then cancelInsert = True End If End If End If //etc
-19086518 0 Sorry. I got my answer for my own question.
Here is codes
[[self tableView] setSectionIndexColor:[UIColor redColor]]; [[self tableView] setSectionIndexBackgroundColor:[UIColor clearColor]];
-32276005 0 After several formatting errors and incorrect / missing inline table aliases...
SELECT * FROM ( SELECT TIME FROM table1 UNION ALL SELECT TIME FROM table2 ) B WHERE TIME = ( SELECT MAX(TIME) FROM ( SELECT TIME FROM table1 union all SELECT TIME FROM table2) a )
-17477899 0 Sylius Instalation - ProductBundle is Missing I'm new in sylius development and i'm getting trouble to install some sylius bundles. I want to build a small online store and i pretend to use SyliusProductBundle, SyliusCartBundle and the required SyliusResourcesBundle.
How can i add them to my project?
Just to test, i've downloaded and installed the sylius full stack and i've noticed that the ProductBundle isn't there. I've read the documentation of both ProductBundle and CartBundle. The ProductBundle was replaced?
So, i have 2 problems:
1 - Figure out what bundles should i use (i think Product and Cart but ProcuctBundle is aparently missing) 2 - How to install this standalone bundles via composer.
I'm using symfony 2.3.1
Can anyone help me? Thanks
-25610938 0The problem isn't that the plugin changes your structure (although it does add some ins elements, which I don't agree with), it's that the plugin doesn't fire a change event for the converted radio controls, and setting the checked property interactively doesn't appear to do so either.
Since the plugin author doesn't publish an API for this use case, it's hard to know whether this is by design or oversight, but the source code definitely doesn't fire the event when the slider is clicked:
this.bearer.find('.slider-level').click( function(){ var radioId = $(this).attr('data-radio'); slider.bearer.find('#' + radioId).prop('checked', true); slider.setSlider(); }); Your options, as I see them:
click event of the .slider-level class, as the API does. click event of your radio group, and catch click events on the bubble Here's a sample implementation of option 3. DEMO.
$(document).ready(function () { $(".radios").radiosToSlider(); }); var makeIsRadioGroupChecked = function(selector) { var $radioGroup = $(selector); return function isRadioGroupChecked() { return $radioGroup.find(':checked').length > 0; }; }; var isOptionsChecked = makeIsRadioGroupChecked('#optionsRadioGroup'); var isSizeChecked = makeIsRadioGroupChecked('#sizeRadioGroup'); var areAllGroupsChecked = function() { return isOptionsChecked() && isSizeChecked(); }; var alertIfAllGroupsChecked = function() { if (areAllGroupsChecked()) { alert("all answered"); } }; $('.radios').on('click', alertIfAllGroupsChecked);
-31538589 0 because print format is %u is unsigned int,but the c is a unsigned char. printf parse c point as a unsigned int point, program read undefined buffer.
-22440303 0 Webbrowser control in C# weird behaviorI'm finishing (QA testing) a web parser built in C# that is parsing specific data from a web site that is being load to a webbrowser control in a WFA (Windows Form Application) program.
The weird behavior is when I'm killing the internet connection... Actually the program is designed to navigate recursively in the site and each step its waiting for a WebBrowserDocumentCompletedEventHandler to be triggered. Beside that there is a Form timer set, and if the handler is not triggered in a specific interval then its reloading the entire procedure.
Everything is working good even if I manually avoid the handler from triggering - As I said the timer kicks in and restart the operation successfully and retrying another value successfully.
When shutting the internet connection manually while the procedure is running, I can see the page is getting the internet explorer message: "This page can't be displayed" (For some reason the DocumentComplete... is not triggered). Then immediately reconnecting the internet and waiting for the timer to kick in - As expected it fires the reload function but this time everything is going wild!! the functions are being fired not in the correct order and it seems like there is 100 threads that are running at the same time - a total chaos.
I know that its not easy to answer this question without experiencing that and seeing the code But if I copy the entire code it will be just too long using 5 different classes and I really can't see where is the problem... I'll try to simplify the question:
Thanks
-21841722 0You should be able to do the following with jQuery:
$('h1').html('<a href="#">' + $('h1').text() + '</a>'); or for multiple headers
$('h1').each(function() { $(this).html('<a href="#">' + $(this).text() + '</a>'); });
-9429413 0 Can one include separate files in htaccess for a list of redirects? My main htaccess file does a bunch of things for my site to function correctly. I have added redirects for pages that have moved. I don't have root access to the server and using .htaccess is my only option.
Is it possible to include separate files for the redirects in the .htaccess file so I can keep them separate and write programatically to the additional files that hold my redirects?
Basically I want to reference separate files from my .htaccess to manage rules dynamically and also neaten up one long .htaccess file with a few smaller files.
I also want to add redirect rules on the fly as things change on the site within my application.
-10273202 0Be sure you are using the same name (case-Sensitive) in Birds Detail View Controller -> Identity Inspector -> Class. "name" with the code in birdsDetailViewController.h: "@interface "name" : UITableViewControlle"
-29465163 0You'd want to post the data you've received over to a php script via an ajax call.
Here's just an example, but you should be able to work with it from there:
$(document).ready(function(){ $("#submit").click(function(){ var name = $("#name").val(); var email = $("#email").val(); var password = $("#password").val(); var contact = $("#contact").val(); // Returns successful data submission message when the entered information is stored in database. var dataString = 'name1='+ name + '&email1='+ email + '&password1='+ password + '&contact1='+ contact; if(name==''||email==''||password==''||contact=='') { alert("Please Fill All Fields"); } else { // AJAX Code To Submit Form. $.ajax({ type: "POST", url: "ajaxsubmit.php", data: dataString, cache: false, success: function(result){ alert(result); } }); } return false; }); });
-966224 0 If you're the vendor supporting a web application which your customer insists upon using with IE6 rather than an updated browser, I'd say try to offer them upgrade incentives (e.g. lower support contract fees, a one-time renewal discount, or some "enhanced" feature set which would magically be enabled once they upgrade their lowest common denominator browser-wise).
I'd agree with some of the previous sentiments mentioned about warning banners, they'd be annoying and useless.
If the company is so big and/or bureaucratic that they are a hard sell in terms of upgrading, it might take years for them to get "current". A hospital I once worked for was just finishing an upgrade to Windows NT 4 while XP had already been out a year.
Personally, if I had any influence over such a situation I would enclose with my annual invoice a very obvious raise in my support or dev fees substantially every year IE6 remains in use at the customer's site, while at the same time presenting them the attractively lower-priced option of upgrading their browser right alongside.
-26279698 0With this code
window.onscroll = function (event) { var amount = window.pageYOffset + "px"; document.getElementById("cover").style.left = amount; } You can achieve it.
Working Fiddle: Fiddle
-39845227 0Try this
var gus = '{{userrole}}';
-908639 0 Personally, I'd combine method two and three: Just create a generic XML document using reflection, say:
<object type="xxxx"> <property name="ttt" value="vvv"/> ... </object> and use an XSTL stylesheet to create the actual HTML from this.
-30040853 0 Swift - Getting address from coordinatesI have a local search that creates annotations for each search result. I'm trying to add an call out accessory to each of the annotations, and once that will be pressed, the Maps app will open and set directions on how to get to the certain location.
The problem that I am having is that in order for the call out accessory to work correctly, you have to get the address using place marks in the Address Book import. I've done plenty of searching and can't figure out how to set it up correctly where I can covert the annotation coordinates into a kABPersonAddressStreetKey so the Maps app can read it correctly. Below is my code for the search function, and the open Maps app function.
func performSearch() -> MKMapItem { matchingItems.removeAll() let request = MKLocalSearchRequest() request.naturalLanguageQuery = searchText.text request.region = mapView.region let search = MKLocalSearch(request: request) search.startWithCompletionHandler({(response: MKLocalSearchResponse!, error: NSError!) in if error != nil { println("Error occured in search: \(error.localizedDescription)") } else if response.mapItems.count == 0 { println("No matches found") } else { println("Matches found") for item in response.mapItems as! [MKMapItem] { println("Name = \(item.name)") println("Phone = \(item.phoneNumber)") self.matchingItems.append(item as MKMapItem) println("Matching items = \(self.matchingItems.count)") var annotation = MKPointAnnotation() var coordinates = annotation.coordinate var location = CLLocation(latitude: annotation.coordinate.latitude, longitude: annotation.coordinate.longitude) var street = // Insert code here for getting address from coordinates var addressDictionary = [String(kABPersonAddressStreetKey): street] var placemark = MKPlacemark(coordinate: coordinates, addressDictionary: addressDictionary) var mapItem = MKMapItem(placemark: placemark) return mapItem annotation.coordinate = item.placemark.coordinate annotation.title = item.name self.mapView.addAnnotation(annotation) } } }) } func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, calloutAccessoryControlTapped control: UIControl!) { let location = view.annotation as! FirstViewController let launchOptions = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving] location.performSearch().openInMapsWithLaunchOptions(launchOptions) } Any help would be greatly appreciated, thanks in advance.
-35952586 0 Sorting linked list by sorting the actual nodes and not just by swapping node valuesI want to sort my linked list so that the nodes are arranged in the sorted order. I have looked up several algorithms, but they all swap the data values and not the actual node itself. Does anyone know where I can find some code on how to swap the nodes themselves and not just the values?
-33877839 0 Why my jQuery function getJSON is not calling my function callback?I have this javascript code:
$(document).ready(function(){ $("#EstadoId").change(function(){ listaCidade($(this).val()); }); }); function listaCidade(uf) { $.getJSON("@Url.Action("ListaCidade")/" + uf, listaCidadeCallBack); } function listaCidadeCallBack() { alert('sucesso'); } Everything is working...getJSON is calling my action "ListaCidade" but it isnt calling my "listaCidadeCallBack".
The result of the Action is
public ActionResult ListaCidade(int id) { var cidades = from c in ctx.Cidades where c.Estado.ID == id select c; return Json(cidades); }
-15550431 0 There are many ways to solve it, one is by using a subquery which separately gets the one record for every district. Since you haven't mentioned your RDBMS that you are using, this will work on almost all RDBMS.
SELECT a.* FROM tableName a INNER JOIN ( SELECT district, MAX(longitude) max_val FROM tableName GROUP BY district ) b ON a.district = b.district AND a.longitude = max_val OUTPUT
╔════════════╦══════════╦═══════════╦══════════╗ ║ RESTAURANT ║ DISTRICT ║ LONGITUDE ║ LATITUDE ║ ╠════════════╬══════════╬═══════════╬══════════╣ ║ perseus ║ 1 ║ 80.879 ║ -56.00 ║ ║ artica ║ 2 ║ 67.708 ║ -69.89 ║ ║ petera ║ 3 ║ 89.00 ║ -78.89 ║ ╚════════════╩══════════╩═══════════╩══════════╝ UPDATE 1
WITH recordList AS ( SELECT restaurant, district, longitude, latitude, ROW_NUMBER() OVER (PARTITION BY district ORDER BY longitude DESC) rn FROM TableName ) SELECT restaurant, district, longitude, latitude FROM recordList WHERE rn = 1
-30656197 0 How to get Jackson to use a Google Guice Injector to create instances? We use Google Guice for DI (mostly with constructor injection) and Jackson for object serialization to/from JSON. As such we build our object graph through Guice Modules.
How do we provide/instruct Jackson to use our pre-built Guice Injector? Or it's own injector based on a Guice Module we provide? My preference is to provide it the injector because we already have means to control which module is used based on the environment/configuration we want to run in.
Here's a unit test:
public class Building { @JsonIgnore public final ElectricalProvider electricalProvider; public String name; @Inject Building(ElectricalProvider electricalProvider){ this.electricalProvider = electricalProvider; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public interface ElectricalProvider {} public class SolarElectricalProvider implements ElectricalProvider{} @Test public void testJacksonGuice() throws IOException { Injector injector = Guice.createInjector(new Module() { @Override public void configure(Binder binder) { binder.bind(ElectricalProvider.class).to(SolarElectricalProvider.class); } }); Building building1 = injector.getInstance(Building.class); building1.setName("test building"); ObjectMapper objectMapper = new ObjectMapper(); byte[] buildingJsonBytes = objectMapper.writeValueAsBytes(building1); Building building2 = objectMapper.readValue(buildingJsonBytes, Building.class); assertThat(building1, is(equalTo(building2))); assertThat(building2.electricalProvider, is(instanceOf(SolarElectricalProvider.class))); } That when run generates this exception com.fasterxml.jackson.databind.JsonMappingException, with this message: No suitable constructor found for type [simple type, class Building]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)
After a bit of googling, I came across the jackson-module-guice project but it doesn't appear to be what we need or doesn't provide as to how to accomplish what we need to do.
-39674698 0This is reason :
Grails is a mix of many frameworks, spring, hibernate etc. All the frameworks are included and you need them as they are the baseline of grails every grails application comes with many plugins by default (look into your BuildConfig.groovy): cache, asset, scaffolding etc. Every plugin has their own dependencies like classes, jars, js etc All of them add up.
Solution: a war and also a jar are just containers. Open them with your favorite unzip program and check.
You can remove that by using following command
grails war -nojars Note: It will build a war without WEB-INF/lib jars. But you have to provide them to your webserver before deployment.
reference: http://mrhaki.blogspot.in/2009/05/create-much-smaller-grails-war-file.html
OR
If you want remove the perticular jar files then you can use below config
Add to your BuildConfig.groovy:
grails.war.resources = { stagingDir -> delete(file:"${stagingDir}/WEB-INF/lib/whatever.jar") }
-31391581 0 How to bind multiple struct fields without getting "use moved value" error? I'm trying to code a generic list as an exercise - I know it's already supported by the syntax, I'm just trying to see if I can code a recursive data structure. As it turns out, I can't. I'm hitting a wall when I want to access more than one field of an owned struct value.
What I'm doing is basically this - I define a struct that will hold a list:
struct ListNode<T> { val: T, tail: List<T> } struct List<T>(Option<Box<ListNode<T>>>); Empty list is just represented by List(None).
Now, I want to be able to append to a list:
impl<T> List<T> { fn append(self, val: T) -> List<T> { match self { List(None) => List(Some(Box::new(ListNode { val: val, tail: List(None) }))), List(Some(node)) => List(Some(Box::new(ListNode { val: node.val, tail: node.tail.append(val) }))) } } } Ok, so that fails with an error "used of moved value: node" at node.tail with an explanation that it was moved at "node.val". This is understandable.
So, I look for ways to use more than one field of a struct and I find this: Avoiding partially moved values error when consuming a struct with multiple fields
Great, so I'll do that:
List(Some(node)) => { let ListNode { val: nval, tail: ntail } = *node; List(Some(Box::new(ListNode { val: nval, tail: ntail.append(val) }))) } Well, nope, still node is being moved at assignment ("error: use of moved value 'node'" at "tail: ntail"). Apparently this doesn't work like in the link anymore.
I've also tried using refs:
List(Some(node)) => { let ListNode { val: ref nval, tail: ref ntail } = *node; List(Some(Box::new(ListNode { val: *nval, tail: (*ntail).append(val) }))) } This time the deconstruction passes, but the creation of the new node fails with "error: cannot move out of borrowed content".
Am I missing something obvious here? If not, what is the proper way to access multiple fields of a struct that is not passed by reference?
Thanks in advance for any help!
EDIT: Oh, I should probably add that I'm using Rust 1.1 stable.
-5572785 0 html5 search input eventsWhat event is triggered when a user clicks the X in a search input field (in webkit browsers) to cancel the search or clear the text?
Information is available about restyling the button and other custom events, but not on using this button.
-2934140 0 How can I make named_scope in Rails return one value instead of an array?I want to write a named scope to get a record from its id.
For example, I have a model called Event, and I want to simulate Event.find(id) with use of named_scope for future flexibility.
I used this code in my model:
named_scope :from_id, lambda { |id| {:conditions => ['id= ?', id] } } and I call it from my controller like Event.from_id(id). But my problem is that it returns an array of Event objects instead of just one object.
Thus if I want to get event name, I have to write
event = Event.from_id(id) event[0].name while what I want is
event = Event.from_id(id) event.name Am I doing something wrong here?
-6089797 0Ok, again I reply to my own question, but this time with a positive remark. I think what I was doing wrong had something to do with the hidden - for me - implications of the Document-based architecture of the default Document Application template.
I have tried with a different approach, creating an application from scratch NOT flagging "Document-based Application" and providing it with:
and I have forced instantiation of the NSWindowController subclasses in the MyDocument code.
I have also put the IBActions for the MenuItems in the MyDocument and I have bound the MyDocument Object to the MenuItems in the MainMenu.xib.
This time I was able to do whatever, hiding/showing windows starting with one hidden one not, enabling menu items automatically at will.
Here follows the code, for any newbie like me who might have to fight with this in the future.
// MyDocument.h #import <Cocoa/Cocoa.h> #import "testWindowController.h" #import "test2WindowController.h" @interface MyDocument : NSDocument { testWindowController *test; test2WindowController *test2; } - (IBAction)showWindow1:(id)pId; - (IBAction)showWindow2:(id)pId; - (IBAction)hideWindow1:(id)pId; - (IBAction)hideWindow2:(id)pId; @end // MyDocument.m #import "MyDocument.h" #import "testWindowController.h" #import "test2WindowController.h" @implementation MyDocument - (id)init { self = [super init]; if (self) { // Initialization code here. NSLog(@"MyDocument init..."); [self makeWindowControllers]; } return self; } - (void)dealloc { [super dealloc]; } - (void)makeWindowControllers { test = [[testWindowController alloc] init]; test2 = [[test2WindowController alloc] init]; [self addWindowController:test]; [self addWindowController:test2]; // start hiding the first window [[test window] orderOut:self]; } - (IBAction)hideWindow1:(id)pId { NSLog(@"hideWindow1"); [[test window] orderOut:self]; } - (IBAction)showWindow1:(id)pId { NSLog(@"showWindow1"); [test showWindow:self]; [[test window] makeKeyAndOrderFront:nil]; // to show it } - (IBAction)hideWindow2:(id)pId { NSLog(@"hideWindow2"); [[test2 window] orderOut:self]; } - (IBAction)showWindow2:(id)pId { NSLog(@"showWindow2"); [test2 showWindow:self]; [[test2 window] makeKeyAndOrderFront:nil]; // to show it } -(BOOL)validateMenuItem:(NSMenuItem *)menuItem { NSLog(@"in validateMenuItem for item: %@", [menuItem title]); if ([[menuItem title] isEqualToString:@"Show Window"] && [[test window] isVisible]){ return NO; } if ([[menuItem title] isEqualToString:@"Hide Window"] && ![[test window] isVisible]){ return NO; } if ([[menuItem title] isEqualToString:@"Show Window2"] && [[test2 window] isVisible]){ return NO; } if ([[menuItem title] isEqualToString:@"Hide Window2"] && ![[test2 window] isVisible]){ return NO; } return [super validateMenuItem:menuItem]; }
-25995565 0 Custom form Validation Rails I am wondering if i have set up my method incorrectly as my validation attempt is being ignored halfway through the method. (i have provided a basic example, i want to get this working before adding more)
I have two variations of a form all belonging to the same object. The forms are differentiated by a column animal_type as you can see in my method
class Animal < ActiveRecord::Base before_save :animal_form_validation private def animal_form_validation if self.animal_type == 'Dog' ap('Im validating the dog Form') if self.name.length <= 0 errors.add(:name, "Name cannot be blank") end elsif self.animal_type == 'Cat' ap('Im validating the cat form') if self.name.length <= 0 errors.add(:name, "Name cannot be blank") end end end end whether i am submitting a cat or dog i get the correct message in the console (using awesome print), so the method is running and knows which form im submitting, but as for the next if statement it is being ignored.
So i have an error with my syntax? or am i calling the wrong validation check on the name field ?
Thanks
-21880001 0No, it's not possible to execute PHP code in Javascript.
What you'll need to do is make an ajax query to a php page. You can get more information about how to do that here: http://www.w3schools.com/php/php_ajax_xml.asp
And more info about XMLHttpRequest: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
-14433460 0You can use Enumerable.Except to get distinct items from lines3 which is not in lines2:
lines2.AddRange(lines3.Except(lines2)); If lines2 contains all items from lines3 then nothing will be added. BTW internally Except uses Set<string> to get distinct items from second sequence and to verify those items present in first sequence. So, it's pretty fast.
You can overload operator new, and operator delete for any specific user-defined type so that those operators use your allocator instead of the default heap allocator.
-27399598 0 Add optional OID in CMS/PKCS 7 signature in C# and Compact Framework 3.5By using CAPI functions (in C# and Compact Framework 3.5), I try to sign a XML and create an CMS/PKCS envelop like the following OpenSSL command do:
openssl smime -sign -in file.xml -out file.b64 -passin pass:test -binary -nodetach -inkey cert.priv.pem -signer cert.pub.pem By calling the functions "CryptMsgOpenToEncode" and "CryptMsgUpdate", I obtain a first signed file. Now I would add optional OID and others datas (more precisely the "SMIMECapabilities", and signing time).
How to do this?
-22280700 0If you use JSF 1.2 or higher you need change it like this:
<h:head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="cache-control" content="no-cache" /> <meta http-equiv="pragma" content="no-cache" /> <meta http-equiv="expires" content="0" /> </h:head> it can be part of template.xhtml
-1709430 0You better tell them what XML really means, 'cause that thing you posted there is far away from anything that has the right of being called XML...
In that case, go for the CSV, read in every row and strip out the spaces (e.g. _Row.Replace(" ", "");), save it in a new .XML and you should be good to go.
I tend to put them in a client context static class. This way they are easily accessible from anywhere in your application and you can initialize them (where needed) on application startup or user login.
-31356812 0 Method for randomly loading paired imagesI've created a webpage with many (over 100) paired flash cards with Question (image) flipping to Answer (image) when clicked. If possible I would like to be able to randomise the order in which the question/answer pairs load with each page load/refresh.
<div class="content4Column gap"> <div class="card-container"> <div class="card click" data-direction="left"> <div class="front"> <img src="Intermolecular/Q1.png" width="100%" height="100%" alt=""> </div> <div class="back"> <img src="Intermolecular/A1.png" width="100%" height="100%" alt=""> </div></div></div></div>
-12199151 0 List.js is a lightweight JavaScript library for adding sorting, searching and paging functionality to plain html lists and tables.
i use a seperate class for validation so it looks like
class UserValidation { protected static $id; protected static $rules = [ 'email' => 'required|email|unique:users,email,{{ self::$id }}', 'password' => 'required|alpha_dash|min:4', ]; public static function validate($input, $id) { self::$id = $id; return Validator::make($input, self::$rules); } } so imagine a user wants to update only his password ,so he updates it > submit but then he receive the error this email is already taken ,because laravel cant read {{ self::$id }} ,so how do i solve something like that.
http://www.mysite.com/<?php echo($var); ?> should do it ... If I understood you
-32041784 0Try to use this:
ContractResolver = new CustomContractResolver { IgnoreSerializableInterface = true, IgnoreSerializableAttribute = true };
-26257466 0 So finally got the system up and running, and for all the people facing similar problems, and without munch knowledge of unicorn or ngixn here are the steps:
First make sure both services are running (unicorn is the app server and ngixn is the http server), both services should be configured in /etc/init.d/.
Stop both services.
Check your policies in selinux, here is a good question on how to do it for the same error in PHP nginx error connect to php5-fpm.sock failed (13: Permission denied), the idea is to be sure selinux ins't interfering with the rad process of the socket (the socket is created by unicorn and readed by ngixn)
then you have to edit your config files unicorn.rb and nginx.conf, both should point to a folder different to tmp for the socket here is why http://serverfault.com/questions/463993/nginx-unix-domain-socket-error/464025#464025
So finally my configurations looks like this:
Part of nginx config file
upstream unicorn { server unix:/home/myuser/apps/myapp/shared/socket/unicorn.camicase.sock fail_timeout=0; } part of unicorn config file
listen "/home/deployer/apps/stickystreet/shared/socket/unicorn.camicase.sock" then start unicorn a ngixn, if you get a (13: Permission denied) while connecting to upstream error just do a sudo chmod 775 socket/ changing the socket for whatever folder you put your unicorn socket to be stored, the restart ngixn service.
-38025102 0 how to make ssis map columns based order instead of column namesI am working on a project where there are 700 columns in a remote server and our destination table have columns that starts with underscore for example if there is a "SchoolName" column in the remote server, on our destination table we would have "_SchoolName" or "_School_Name" column. We use to use DTS package to import data "which doesn't use column name to map, instead it uses the order of the column on the select statement to map the column in the destination table". Now we would like upgrading our DTS package to SSIS, but mapping 700 columns manually has been a nightmare. Is there any way we can map columns based on the column orders instead of column name?
I get the following error, when I would like to make a Build solution.
-26030711 0LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt
try this.
body { margin: 0; padding: 0; background: #EEE; font: 10px/13px'Lucida Sans', sans-serif; } .wrap { overflow: hidden; margin: 50px; } /*20 for 5 box , 25 for 4 box*/ .box { float: left; position: relative; width: 25%; padding-bottom: 25%; color: #FFF; } /*border width control*/ .boxInner { position: absolute; left: 30px; right: 30px; top: 30px; bottom: 30px; overflow: hidden; background: #66F; } .boxInner img { width: 100%; } .gallerycontainer { position: relative; /*Add a height attribute and set to largest image's height to prevent overlaying*/ } /*This hover is for small image*/ .thumbnail:hover img { border: 1px solid transparent; } /*This hide the image that is in the span*/ .thumbnail span { position: absolute; padding: 5px; visibility: hidden; color: black; text-decoration: none; } /*This is for the hidden images, to resize*/ .thumbnail span img { /*CSS for enlarged image*/ border-width: 0; width: 200%; /* you can use % */ height: auto; padding: 2px; } /*When mouse over, the hidden image apear*/ .thumbnail:hover span { position: fixed; visibility: visible; z-index: 200; zoom: 62%; bottom: 0; right: 0; } .thumbnail:hover span img { width: 100%; } <!DOCTYPE html> <html> <link href="overlay2.css" rel="stylesheet" type="text/css" /> <head> <title>Test</title> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="description" content="" /> <meta name="keywords" content="" /> </head> <body> <div class="wrap"> <div class="box"> <div class="boxInner"> <a class="thumbnail" href="#"> <img src="http://www.dwuser.com/education/content/creating-responsive-tiled-layout-with-pure-css/images/demo/7.jpg" /><span><img src="http://www.dwuser.com/education/content/creating-responsive-tiled-layout-with-pure-css/images/demo/7.jpg" /></span> </a> </div> </div> <div class="box"> <div class="boxInner"> <a class="thumbnail" href="#"> <img src="http://www.dwuser.com/education/content/creating-responsive-tiled-layout-with-pure-css/images/demo/6.jpg" /><span><img src="http://www.dwuser.com/education/content/creating-responsive-tiled-layout-with-pure-css/images/demo/6.jpg" /></span> </a> </div> </div> <div class="box"> <div class="boxInner"> <a class="thumbnail" href="#"> <img src="http://www.dwuser.com/education/content/creating-responsive-tiled-layout-with-pure-css/images/demo/1.jpg" /><span><img src="http://www.dwuser.com/education/content/creating-responsive-tiled-layout-with-pure-css/images/demo/1.jpg" /></span> </a> </div> </div> <div class="box"> <div class="boxInner"> <a class="thumbnail" href="#"> <img src="http://www.dwuser.com/education/content/creating-responsive-tiled-layout-with-pure-css/images/demo/2.jpg" /><span><img src="http://www.dwuser.com/education/content/creating-responsive-tiled-layout-with-pure-css/images/demo/2.jpg" /></span> </a> </div> </div> <div class="box"> <div class="boxInner"> <a class="thumbnail" href="#"> <img src="http://www.dwuser.com/education/content/creating-responsive-tiled-layout-with-pure-css/images/demo/3.jpg" /><span><img src="http://www.dwuser.com/education/content/creating-responsive-tiled-layout-with-pure-css/images/demo/3.jpg" /></span> </a> </div> </div> <div class="box"> <div class="boxInner"> <a class="thumbnail" href="#"> <img src="http://www.dwuser.com/education/content/creating-responsive-tiled-layout-with-pure-css/images/demo/4.jpg" /><span><img src="http://www.dwuser.com/education/content/creating-responsive-tiled-layout-with-pure-css/images/demo/4.jpg" /></span> </a> </div> </div> <div class="box"> <div class="boxInner"> <a class="thumbnail" href="#"> <img src="http://www.dwuser.com/education/content/creating-responsive-tiled-layout-with-pure-css/images/demo/8.jpg" /><span><img src="http://www.dwuser.com/education/content/creating-responsive-tiled-layout-with-pure-css/images/demo/8.jpg" /></span> </a> </div> </div> </div> </body> </html> I have created new facebook app for my application. Now this app is with api version 2.4. I was using below code for login with owin.
app.UseFacebookAuthentication(new FacebookAuthenticationOptions() { AppId = "xx", AppSecret = "xxx", Scope = { "email", "public_profile" } }); This code was working fine and returning me the email address with older facebook app with api version 2.3. But now with the api version2.4, it is not returning email. It is asking user for permission to share email bur not returning email in login info.
Is there any modification with api 2.4 which I am missing ?? Please suggest. Thanks in advance . .
-6101464 0You are trying to assign a const pointer to a non const pointer. If you make t a "const char*" in fun1() it will be fine.
-24488559 0$myArr3 = array_merge_recursive($myArr1, $myArr2); foreach($myArr3 as $key => $value){ if(!is_array($myArr3[$key])){ continue; } if($value[0] === $value[1]){ $myArr3[$key] = $value[0]; }else{ $myArr3[$key] = implode(' ', $value); } } // print_r($myArr3);
-34180763 0 In symfony, you only have to persist a new entity. If you update an existing entity found by your entity manager and then flush, your entity will be updated in database even if you didn't persist it.
Edit : you can detach an entity from the entity manager before flushing it using this line of code :
$em->detach($formModelEntity);
-37776557 1 Cannot print a specific number from a sublist within a list I want to be able to print the 3rd number with in a list of sublist. I am okay with interacting through the list and sublist, but unsure with how i can print the 3rd number of each sublist. for example [[1,2,3,4][1,2,3,4][,1,2,3,4][1,2,3,4]] i was to achieve 3,3,3,3
I have manage this so far, being able to print out all numbers with the sublists
def Contact(num):<br/> for i in range(len(num)):<br/> for j in range(len(num[i])):<br/> print(num[i][j]) Contact([[1,2,3,4][1,2,3,4][,1,2,3,4][1,2,3,4]])
-7091032 0 This question was on Common Lisp, but one particular answer referenced Picobit, which is essentially a Scheme for microcontrollers. It very well fits in my conditions, as the paper says it can work on as little as 7 kb of memory.
I've decided to fork Picobit and port it to ARM processors.
-3160946 0I highly recommend the Seam Framework from JBoss. It helps simplify JSF quite a bit, and also makes it very easy to integrate things like Hibernate or EJB3. Plus, it's quite pretty wide support across the major IDEs.
-21357659 0Currently, there's no triggers in mongo (but you can vote for the feature here -> https://jira.mongodb.org/browse/SERVER-124).
-35956868 0 Unable to install python-recsys moduleI am trying to install python-recsys module. But i get this error
Could not find a version that satisfies the requirement python-recsys (from versions: ) No matching distribution found for python-recsys
I am using Python 3.4 The code that i am using to install the module is: pip.exe install python-recsys
Based on the description of what you are doing, I don't understand why you think your query works.
The overlap query should look like this:
SELECT AssetID as UnAvailableAsset FROM agreementasset WHERE CheckOutDate <= @RentEndDate AND ExpectedReturnDate >= @RentStartDate; This type of query can be difficult to optimize (in most databases). You can start with an index on agreementasset(CheckOutDate, ExpectedReturnDate, AssetID).
there is a good example in here to calculate distance with PHP http://www.geodatasource.com/developers/php :
function distance($lat1, $lon1, $lat2, $lon2, $unit) { $theta = $lon1 - $lon2; $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); $dist = acos($dist); $dist = rad2deg($dist); $miles = $dist * 60 * 1.1515; $unit = strtoupper($unit); if ($unit == "K") { return ($miles * 1.609344); } else if ($unit == "N") { return ($miles * 0.8684); } else { return $miles; } }
-28593287 0 I had a very similar experience to @user1501382, but tweaked everything slightly in accordance with the documentation
1) cd c: //changes to C drive
2) mkdir data //creates directory data
3) cd data
4) mkdir db //creates directory db
5) cd db //changes directory so that you are in c:/data/db
6) run mongod -dbpath
7) close this terminal, open a new one and run mongod
I want to convert JSONObject to ContentValue. How can i do that without knowing what columns i have in JSONObject?
columns in JSONObject are the same as columns in SQLite database on the device and they are in the same order.
I can do it like this
ContentValues values = new ContentValues(); values.put(TASK_NAME, json.getString("name")); values.put(TASK_KEY_PROJECT, json.getString("project")); values.put(TASK_KEY_CATEGORY, json.getString("category")); values.put(TASK_KEY_TAG, json.getString("tag")); //TODO CATCH NO TAG EXCEPTION but i want to know better way thanks in advance
-1389183 0An other solution that may not appeal to some but is fast to implement and works well is to introduce a new property on the object for sorting purposes. Make the new property contain a sorting character as the first character (a number works well) and the actual sorting value as the rest of the characters. Implement some easy if-else statements to set the appropriate value of the sorting property.
When adding this column to the grid just make it hidden and sort on that column.
Possibly a less elegant solution than the one proposed by najmeddine, but it works.
-7826776 0i don't know how you would do it efficiently but if you need to get it done.
keywords = Keyword.objects.all() for keyword in keywords: print 'Total Articles: %d' % (Article.objects.filter(keywords=keyword).count())
-6488289 0 This works for removing a certain color from a bitmap. The main part is the use of AvoidXfermode. It should also work if trying to change one color to another color.
I should add that this answers the question title of removing a color from a bitmap. The specific question is probably better solved using PorterDuff Xfermode like the OP said.
// start with a Bitmap bmp // make a mutable copy and a canvas from this mutable bitmap Bitmap mb = bmp.copy(Bitmap.Config.ARGB_8888, true); Canvas c = new Canvas(mb); // get the int for the colour which needs to be removed Paint p = new Paint(); p.setARGB(255, 255, 0, 0); // ARGB for the color, in this case red int removeColor = p.getColor(); // store this color's int for later use // Next, set the alpha of the paint to transparent so the color can be removed. // This could also be non-transparent and be used to turn one color into another color p.setAlpha(0); // then, set the Xfermode of the pain to AvoidXfermode // removeColor is the color that will be replaced with the pain't color // 0 is the tolerance (in this case, only the color to be removed is targetted) // Mode.TARGET means pixels with color the same as removeColor are drawn on p.setXfermode(new AvoidXfermode(removeColor, 0, AvoidXfermode.Mode.TARGET)); // draw transparent on the "brown" pixels c.drawPaint(p); // mb should now have transparent pixels where they were red before
-15607681 0 Non-root user should not use ports below 1024. It is better to do port forwarding from 80 to 8080 and 443 (https default) to 8181.
Execute this as root:
iptables -A INPUT -p tcp --dport 80 -j ACCEPT iptables -t nat -A PREROUTING -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 8080 iptables -A INPUT -p tcp --dport 443 -j ACCEPT iptables -t nat -A PREROUTING -p tcp -m tcp --dport 443 -j REDIRECT --to-ports 8181 Need to make this permanent:
iptables-save -c > /etc/iptables.rules iptables-restore < /etc/iptables.rules and call during startup, vi /etc/network/if-pre-up.d/iptablesload
#!/bin/sh iptables-restore < /etc/iptables.rules exit 0
-5073188 0 How do I use LINQPad with third party plugins? All documentation I can find relevant to doing updates with Linqpad mentions a "SubmitChanges" function which should be global for C# code and/or expressions. Nonetheless it doesn't work; all I can get is:
The name 'SubmitChanges' does not exist in the current context
This is attempting to use LINQPad with Msoft CRM/Dynamics and the related plugin. Simple "Select" queries do work.
-24119922 0 JSP nested For LoopSo I have the following class
class User{ int id; int name; //constructor and getters and setters go here } set
Set<User> student = new LinkedHashSet<User>(); Set<User> teacher = new LinkedHashSet<User>(); Set<User> other = new LinkedHashSet<User>(); another set
Set<Set<User>> finalSet = new LinkedHashSet<Set<User>>(); this contains all the set above
how can i print all the value of finalSet in jsp using nested for loop
<c:forEach items="${finalSet}" var="each"> <c:forEach items="${finalSet.(what should go here??)}" var="each2"> ${each2.getId()); </c:forEach> </c:forEach> How to do this??
-23336183 0 How to read certain specified fields from text file in javascriptI am using text file data for my script. I am loading the text file and getting the data from it. The text file contains data as below.
'DoctorA': {name: "Pharmaceuticals", title: "Switzerland, 120000 employees"}, 'DoctorB': {name: "Consulting", title: "USA, 5500 employees"}, 'DoctorC': {name: "Diagnostics", title: "USA, 42000 employees"}, 'DoctorD': {name: "Fin Serv. & Wellness", title: "South Africa, employees"}, I load and use something like this to read the data from that text file.
data.speakers=names_val[0]; I have not fully specified my script. My problem is I am getting the entire text file when I load into data.speakers. Is there anyway to read only that title: fields or only that name: field
-2758587 0If the sample is representative of the page, the the form "myForm" doesn't exist when the script is evaluated. In addition to using document.getElementById (or document.forms.formName), you'll need to delay setting var myForm until after the form element is processed or, better yet, pass the form as an argument to the functions rather than using a global variable.
Try this.
$(window).on('scroll', function () { var v = $(window).scrollTop(); if (v > 200) { $('#id-of-div').css({"height": "75px","max-height":"75px"}); } else { $('#id-of-div').css({"height": "150px","max-height":"150px"}); } }); EDIT:
$(window).on('scroll', function () { var v = $(window).scrollTop(); if (v > 200) { $('#id-of-div').animate({"height": "75px","max-height":"75px"},500); } else { $('#id-of-div').animate({"height": "150px","max-height":"150px"},500); } });
-24769231 0 Your select is not doing what you think it does.
The most compact version in PostgreSQL would be something like this:
with data(first_name, last_name, uid) as ( values ( 'John', 'Doe', '3sldkjfksjd'), ( 'Jane', 'Doe', 'adslkejkdsjfds') ) insert into users (first_name, last_name, uid) select d.first_name, d.last_name, d.uid from data d where not exists (select 1 from users u2 where u2.uid = d.uid; Which is pretty much equivalent to:
insert into users (first_name, last_name, uid) select d.first_name, d.last_name, d.uid from ( select 'John' as first_name, 'Doe' as last_name, '3sldkjfksjd' as uid union all select 'Jane', 'Doe', 'adslkejkdsjfds' ) as d where not exists (select 1 from users u2 where u2.uid = d.uid;
-15495110 0 It looks as if you want to use Express and the express.compress middleware. That will figure out if a browser supports gzip and/or deflate, so you don't have to.
A simple setup could look like this:
var express = require('express'); var app = express(); app.use(express.compress()); app.get('/', function(req, res) { res.send({ app_id: 'A3000990' }); }); app.listen(3000); If your data is a JSON-string, you have to set the correct content-type header yourself:
res.setHeader('Content-Type', 'application/json'); res.send(data);
-18828322 0 Since you are using sh, and not bash, you should use a single equal = to do the string comparison, instead of the double equal ==. Also it is a good practice to double quote the variable in test statement (this error is not caused by incorrect quoting though).
The comparison should be:
if [ "$1" = "--daily" ] and
elif [ "$1" = "--monthly" ]
-32061920 0 Assuming your data will be ordered, like it is in your example, thus assuming the base will always appear before its children, this is what I came up with:
private static Collection<String> extractBases(String[] nodes) { Arrays.sort(nodes); // optional, to ensure order Deque<String> bases = new ArrayDeque<>(); bases.addFirst(nodes[0]); for (int i = 1; i < nodes.length; i++) { if (!nodes[i].contains(bases.peekFirst())) { // if it's not a child bases.addFirst(nodes[i]); } } return bases; } You can check a demo with your input here: http://ideone.com/sjEfvc
-4550461 0Most of the configuring/querying can be done via SNMP, so you don't have to have a SSH client/command parser built in you application. What's supported depends on router/ios version. You can check here: SNMP OID Browser. SNMP can sometimes be overwhelming, but in time it can be of great use to you. My first suggestion is to find a SNMP browser (eg. from solarwinds) so you can inspect what info you can get from the router. Then you can use NET-SNMP library to do the actual querying/configuring of the router, or if you are willing to pay you can try IP*Works.
-13242395 0Try to use regular expression, e.g.:
var count = Regex.Matches(input, @"\b\w+\b").Count();
-1170513 0 In the .cs file right click on the class name and click on "Find Usages".
This should find all designer files of other controls / pages that use that particular control.
-24519903 0 how to load first n rows from a scv file with phpexcel?I haven't seen an example on loading the first n rows from afile
So far I have:
$objPHPExcel = PHPExcel_IOFactory::load($file_name); $sheetData = $objPHPExcel->getActiveSheet()->toArray(NULL, FALSE, TRUE, FALSE); The reason I want to load only a few rows is that my file is large (10.000 entries) and im thinking that loading a few rows will be faster.
Any ideas?
-23746258 0Completely new answer as of given details. You are working with VBA so you can call WorksheetFunctions like
Dim someVariable someVariable = WorksheetFunction.Quotient(Worksheets("Sheet1").Cells(1, "A").Value, Worksheets("Sheet1").Cells(1, "B").Value) Debug.Print someVariable There is a quite good list of supported functions available on MSDN WorksheetFunction. Please choose your current Excel version on the linked page.
Furthermore I found another very important site concerning your problem that states that not all WorksheetFunctions are supported as Application. (see support.microsoft.com)
So I searched for workarounds and found a quite simple one on StackOverflow. But on the other hand - you really could make use of the VBA builtIn operator MOD
' created some variables, as I made some attempts on creating a good example Dim value1 value1 = Worksheets("Sheet1").Cells(1, "A").Value Dim value2 value2 = Worksheets("Sheet1").Cells(1, "B").Value someVariable = value1 Mod value2 Debug.Print someVariable ' of course you may use a single line statement too someVariable = Worksheets("Tabelle1").Cells(1, "A").Value Mod Worksheets("Tabelle1").Cells(1, "B").Value I think there are some pretty good links to have a deeper look into.
-3651525 0 Querying documents containing two tags with CouchDB?Consider the following documents in a CouchDB:
{ "name":"Foo1", "tags":["tag1", "tag2", "tag3"], "otherTags":["otherTag1", "otherTag2"] } { "name":"Foo2", "tags":["tag2", "tag3", "tag4"], "otherTags":["otherTag2", "otherTag3"] } { "name":"Foo3", "tags":["tag3", "tag4", "tag5"], "otherTags":["otherTag3", "otherTag4"] } I'd like to query all documents that contain ALL (not any!) tags given as the key.
For example, if I request using '["tag2", "tag3"]' I'd like to retrieve Foo1 and Foo2.
I'm currently doing this by querying by tag, first for "tag2", then for "tag3", creating the union manually afterwards.
This seems to be awfully inefficient and I assume that there must be a better way.
My second question - but they are quite related, I think - would be:
How would I query for all documents that contain "tag2" AND "tag3" AND "otherTag3"?
I hope a question like this hasn't been asked/answered before. I searched for it and didn't find one.
-37188175 0 Margins on flexbox items work in Chrome but nothing elseI have a flexbox with flex-direction column. The items inside the flexbox have margins set but the margins only appear in chrome. I tried setting a height to the container larger than the items and setting justify-content: space-around but that had no effect either.
I have looked around but can't seem to find any mention of this being a bug or browser support issue.
Here is the code I have. and here is a fiddle demonstrating the behavior. If you view the fiddle in Chrome you see the margins but in firefox no margins.
SCSS
.background { background-color: red; } .backgroundText { display: flex; flex-direction: column; a { padding-left: 3%; margin-top: 15%; font-size: 75px; &:nth-child(4) { margin-bottom: 15%; } } } HTML
<div class=container-fluid> <div class="background col-xs-12"> <div class="col-xs-3 col-xs-offset-9"> <div class="backgroundText"> <a href="#">Item</a> <a href="#">Item</a> <a href="#">Item</a> <a href="#">Item</a> </div> </div> </div> </div>
-39123272 0 var oBundle; defaultLocale = "en-EN"; var countryLocale = "de-FR"; oBundle= jQuery.sap.resources({url : "i18n/labels-en.properties", locale: defaultLocale}); //If need to use any other language have a condition to define accordingly. //oBundle= jQuery.sap.resources({url :"i18n/labels-fr.properties", locale: countryLocale }); And in your controls just below to setText
oBundle.getText("label.title");
-10598116 0 Zend Form Displays weird chars on non-english chars I use UTF-8 everywhere on the site, the data come back in UTF-8 too, it works everywhere on the page, except one case: the (zend) form value.
I have checked everything, the string is utf-8, the page encoding is utf-8, the result from the Api is utf8.
(Margar\u00e9t\u00e1\u00f3\u0171\u00fa\u0151\u00fc\u00f6)
This is what I see in the divs, as well as in the header too :
Margarétáóűúőüö This is what I got in the form:
Margarétáóűúőüö I have tried many things, utf8_encode , mb_convert_encoding , but nothing was happened.
I used a helper, the $name contains the 'Margarétáóűúőüö' value:
$form = $this->_helper->form('user-settings'); $form->addElement('text', 'name', array( 'label' => 'Name', 'value' => $name, 'required' => true, 'autocapitalize' => 'off', 'autocorrect' => 'off', ));
-2122987 0 Yes, the Exec function seems to be broken when it comes to terminal output.
I have been using a similar function function ConsumeStd(e) {WScript.StdOut.Write(e.StdOut.ReadAll());WScript.StdErr.Write(e.StdErr.ReadAll());} that I call in a loop similar to yours. Not sure if checking for EOF and reading line by line is better or worse.
I have one plugin on my Chrome Browser Extension and i want to send some parameter to this and run this plugin. So is that possible?
If yes so please guide me for the same.
I am using JAVA.
-12948314 0I didn't get you?? Y u need to implement threads in jsp..What you exactly want to do..Because the tomcat container itself maintains the threads for your concern jsp.. What u want is may be about the session tracking i guess..Sorry but didn,t get your question properly...???
-15428108 0I would do this using ddply from plyr package. For example:
require(plyr) res <- lapply(list.files(pattern='^[1-2].txt'),function(ff){ ## you read the file data <- read.table(ff, header=T, quote="\"") ## remove the outlier data <- data[data$RT>200,] data <- ddply(data,.(Condition),function(x) x[!abs(scale(x$RT)) > 3,]) ## compute the mean ddply(data,.(Condition,Reqresponse,Score),summarise,RT=mean(RT)) }) [[1]] Condition Reqresponse Score RT 1 X a 0 500 2 X a 1 750 3 X b 0 500 4 X b 1 500 5 Y a 0 400 6 Y a 1 640 7 Y b 1 1000 8 Z a 0 1000 9 Z a 1 1675 10 Z b 0 400 [[2]] Condition Reqresponse Score RT 1 X a 0 500 2 X a 1 750 3 X b 0 500 4 X b 1 500 5 Y a 0 400 6 Y a 1 640 7 Y b 1 1000 8 Z a 0 1000 9 Z a 1 1675 10 Z b 0 400
-40736223 0 You can reassign $this value by variable variable
$name = 'this'; $$name = 'stack'; echo $this; // this will result stack
-31561503 0 OneDrive Saver Api (Multiple Files Upload) var MyFiles = []; if (val == "Address") { MyFiles.push({ 'file': 'http://----/Content/File/Addresses.xlsx', 'fileName': 'Addresses.xlsx' }); } if (val == "DebitDetail") { MyFiles.push({ 'file': 'http://----/Content/File/DebitDetails.xlsx', 'fileName': 'DebitDetails.xlsx' }); } if (val == "AddressAssociated") { MyFiles.push({ 'file': 'http://----/Content/File/AddressAssociatedCompanies.xlsx', 'fileName': 'AddressAssociatedCompanies.xlsx' }); } if (val == "DebitDetailAssociated") { MyFiles.push({ 'file': 'http://----/Content/File/DebitDetailsAssociatedCompanies.xlsx', 'fileName': 'DebitDetailsAssociatedCompanies.xlsx' }); } var saverOptions = { file: myFiles, success: function () { // upload is complete }, progress: function (p) { // upload is progressing }, cancel: function () { // upload was cancelled }, error: function (e) { // an error occured } }; OneDrive.save(saverOptions); I have used the above code for DropBox and it works well because it takes an array of objects but i cant find solution for OneDrive.com! Below documentation only shows how to upload a single file using URL. but i want to upload multiple files.
The Format From The OneDrive Site
var saverOptions = { file: "inputFile", fileName: 'file.txt', success: function(){ // upload is complete }, progress: function(p) { // upload is progressing }, cancel: function(){ // upload was cancelled }, error: function(e) { // an error occured } } https://dev.onedrive.com/sdk/javascript-picker-saver.htm
-34325472 0 Angular define input of float valueHow would i define my input to be persistently be a float value and accept float values only ? below is my code but does not work as intended ?
<input type="number" step="0.01" placeholder="Amount" class="form-control" ng-model="choice.amount"/>
-32697700 0 This query would work
select t1.*,t2.pos from Table1 t1 left outer join Table2 t2 on t1.Date=t2.Date and t1.UserID=t2.UserID
-13699874 0 Add vertical-align:top; on your .item class
.item{ vertical-align:top; }
-22406605 0 The difference is in what default encoding is used. From MSDN, we can see that Set-Content defaults to ASCII encoding, which is readable by most programs (but may not work if you're not writing english). The > output redirection operator on the other hand works with Powershell's internal string representation, which is .Net System.String, which is UTF-16 (reference)
As a side-note, you can also use Out-File, which uses unicode encoding.
In your controller declare :
$scope.selectedCity = 'cityName'; // any name you want to initialize with
-11912381 0 ResourceEditor LWUIT NoClassDefFoundError: com/app/XMLMidlet: com/sun/lwuit/events/ActionListener I have developed Rss App LWUIT Project using ResourceEditor.
I opened the project in Netbeans IDE, I followed the link at developers Nokia site Generating the NetBeans project in the Resource Editor - Adding GUI resource file manually into your project.
While running my application, I am facing Uncaught exception
java/lang/NoClassDefFoundError: com/app/XMLMidlet: com/sun/lwuit/events/ActionListener Could I do any extra thing?
-37385987 0 GCM and swift can register and receive a success notification but no other push noteificiatonsUpdate: Ok so I redid all my certs and now I am getting this by testing the GCM at this site http://techzog.com/development/gcm-notification-test-tool-android/
URL: http://android.googleapis.com/gcm/send Headers: Array ( [0] => Authorization: key=AIzaSyBPTQGXlyImFWPda1s2LVUKIN98uMS0Bac [1] => Content-Type: application/json ) 1 Fields: Array ( [registration_ids] => Array ( [0] => fBspb1tyYDg:APA91bE0-pzjJrJodW2JuNvnEZSkUaw0rBjf0gkwu2Yi9GaS8WcrhZII2LnDcclwd4K5W51osjxfBCM7E76Ck7EDG4YHEESAesXZBgrSrHDQNAjGPv1VgOi-zkFi1biZSQzeaEbS3xch ) [data] => Array ( [message] => Koimute [] => ) ) 1 Result: Unauthorized Error 401 So this means that it is being basically stopped from getting to the phone I think.
UPDATE: Ok so I have been working at it and have tried to change the cert around and fool with the settings. now my console is printing out that I am connected to the GCM. But, still I do not receive any notification from the server at all. Here is what my console is printing
0028-05-24 12:21:32.829: GCM | GCM library version 1.1.4 0028-05-24 12:21:32.841: GCM | Invalid key in checkin plist: GMSInstanceIDDeviceDataVersion 2016-05-24 12:21:32.856 MyApp[560:] <GMR/INFO> App measurement v.2003000 started 2016-05-24 12:21:32.857 MuApp[560:] <GMR/INFO> To enable debug logging set the following application argument: -GMRDebugEnabled 0028-05-24 12:21:32.920: GCM | Invalid key in checkin plist: GMSInstanceIDDeviceDataVersion 2016-05-24 12:21:33.053 MyApp[560:106171] INFO: GoogleAnalytics 3.14 -[GAIReachabilityChecker reachabilityFlagsChanged:] (GAIReachabilityChecker.m:159): Reachability flags update: 0X000002 Registration Token: My token i get from GCM 2016-05-24 12:21:33.067 MyApp[560:] <GMR/INFO> App measurement enabled Connected to GCM 2016-05-24 12:21:33.937 MyApp[560:106213] INFO: GoogleAnalytics 3.14 -[GAIBatchingDispatcher hitsForDispatch] (GAIBatchingDispatcher.m:368): No pending hits. The GCM | Invalid key in checkin plist: GMSInstanceIDDeviceDataVersion error from what I gathered means that it is working and is fine. They said that they will fix this in a later release
OLD: So I have set up the GCM as well as a Google Analytics in my iOS project. The Analytics works perfect and all. Thats why I don't think its my Google service json that is the problem. I can successfully register to receive a token from the GCM server. But when I try to send a push notification nothing happens. I do receive a notification when it registers successfully so I think that my notification centre is working too. I follows the steps for creating the certificates as well. So I do not know where the problem is.: I am also using a third party APNs tester to rule out my server being the issues. I am using APN Tester. The APN tester returns this from doing a push notification:
gateway.sandbox.push.apple.com:2195 2016-05-23 07:56:02 +0000: Connected to server gateway.sandbox.push.apple.com 2016-05-23 07:56:02 +0000: Set SSL connection 2016-05-23 07:56:02 +0000: Set peer domain name gateway.sandbox.push.apple.com 2016-05-23 07:56:02 +0000: Keychain Opened 2016-05-23 07:56:02 +0000: Certificate data for Apple Development IOS Push Services: com.mywebpage.jp.MyClient initialized successfully 2016-05-23 07:56:02 +0000: Sec Identity created 2016-05-23 07:56:02 +0000: Client certificate created 2016-05-23 07:56:03 +0000: Connected 2016-05-23 07:56:03 +0000: Token: <0000000c 00000003 00001bff ff1b0000 00001bff ff1b0000 00001bff ff1b0000 00001bff ff1b0000 00001bff 00000e82 000000ef 0000003a 3a000000 0000003a 3a000000 0000003a 3a000000> 2016-05-23 07:56:03 +0000: Written 92 bytes sending data to gateway.sandbox.push.apple.com:2195 2016-05-23 07:56:03 +0000: Disconnected from server gateway.sandbox.push.apple.com:2195 This is my AppDeligate file
import UIKit import Foundation @UIApplicationMain //add this for GCM //, GGLInstanceIDDelegate, GCMReceiverDelegate class AppDelegate: UIResponder, UIApplicationDelegate, GGLInstanceIDDelegate, GCMReceiverDelegate{ let loginInformation = NSUserDefaults.standardUserDefaults() var window: UIWindow?; //MARK: Varaibles for GCM var connectedToGCM = false var subscribedToTopic = false var gcmSenderID: String? var registrationToken: String? var registrationOptions = [String: AnyObject]() let registrationKey = "onRegistrationCompleted" let messageKey = "onMessageReceived" let subscriptionTopic = "/topics/global" func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. APIManager.sharedInstance.setAuthorization(Config.API_USERNAME, password: Config.API_PASSWORD) // [START_EXCLUDE] // Configure the Google context: parses the GoogleService-Info.plist, and initializes // the services that have entries in the file var configureError:NSError? GGLContext.sharedInstance().configureWithError(&configureError) assert(configureError == nil, "Error configuring Google services: \(configureError)") gcmSenderID = GGLContext.sharedInstance().configuration.gcmSenderID // [END_EXCLUDE] // Register for remote notifications let settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil) application.registerUserNotificationSettings(settings) application.registerForRemoteNotifications() // [END register_for_remote_notifications] // [START start_gcm_service] let gcmConfig = GCMConfig.defaultConfig() gcmConfig.receiverDelegate = self GCMService.sharedInstance().startWithConfig(gcmConfig) // [END start_gcm_service] //Google Analyitics functions // [START tracker_swift] // Configure tracker from GoogleService-Info.plist. //var configureGAError:NSError? GGLContext.sharedInstance().configureWithError(&configureError) assert(configureError == nil, "Error configuring Google services: \(configureError)") // Optional: configure GAI options. let gai = GAI.sharedInstance() gai.trackUncaughtExceptions = true // report uncaught exceptions gai.logger.logLevel = GAILogLevel.Verbose // remove before app release // [END tracker_swift] return true } func applicationDidEnterBackground(application: UIApplication) { GCMService.sharedInstance().disconnect() // [START_EXCLUDE] self.connectedToGCM = false // [END_EXCLUDE] } func applicationDidBecomeActive(application: UIApplication) { // Connect to the GCM server to receive non-APNS notifications GCMService.sharedInstance().connectWithHandler({(error:NSError?) -> Void in if let error = error { print("Could not connect to GCM: \(error.localizedDescription)") } else { self.connectedToGCM = true print("Connected to GCM") } }) } // [START receive_apns_token] func application( application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData ) { // [END receive_apns_token] // [START get_gcm_reg_token] // Create a config and set a delegate that implements the GGLInstaceIDDelegate protocol. let instanceIDConfig = GGLInstanceIDConfig.defaultConfig() instanceIDConfig.delegate = self // Start the GGLInstanceID shared instance with that config and request a registration // token to enable reception of notifications GGLInstanceID.sharedInstance().startWithConfig(instanceIDConfig) registrationOptions = [kGGLInstanceIDRegisterAPNSOption:deviceToken, kGGLInstanceIDAPNSServerTypeSandboxOption:true] GGLInstanceID.sharedInstance().tokenWithAuthorizedEntity(gcmSenderID, scope: kGGLInstanceIDScopeGCM, options: registrationOptions, handler: registrationHandler) // [END get_gcm_reg_token] } // [START ack_message_reception] func application( application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { print("Notification received: \(userInfo)") // This works only if the app started the GCM service GCMService.sharedInstance().appDidReceiveMessage(userInfo); // Handle the received message // [START_EXCLUDE] NSNotificationCenter.defaultCenter().postNotificationName(messageKey, object: nil, userInfo: userInfo) // [END_EXCLUDE] } func application( application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler handler: (UIBackgroundFetchResult) -> Void) { print("Notification received: \(userInfo)") // This works only if the app started the GCM service GCMService.sharedInstance().appDidReceiveMessage(userInfo); // Handle the received message // Invoke the completion handler passing the appropriate UIBackgroundFetchResult value // [START_EXCLUDE] NSNotificationCenter.defaultCenter().postNotificationName(messageKey, object: nil, userInfo: userInfo) handler(UIBackgroundFetchResult.NoData); // [END_EXCLUDE] } // [END ack_message_reception] func registrationHandler(registrationToken: String!, error: NSError!) { if (registrationToken != nil) { self.registrationToken = registrationToken print("Registration Token: \(registrationToken)") //store the registation token for use in the postData function in the login page self.loginInformation.setObject(self.registrationToken, forKey: "GCMToken") self.loginInformation.synchronize() let userInfo = ["registrationToken": registrationToken] NSNotificationCenter.defaultCenter().postNotificationName( self.registrationKey, object: nil, userInfo: userInfo) } else { print("Registration to GCM failed with error: \(error.localizedDescription)") let userInfo = ["error": error.localizedDescription] NSNotificationCenter.defaultCenter().postNotificationName( self.registrationKey, object: nil, userInfo: userInfo) } } // [START on_token_refresh] func onTokenRefresh() { // A rotation of the registration tokens is happening, so the app needs to request a new token. print("The GCM registration token needs to be changed.") GGLInstanceID.sharedInstance().tokenWithAuthorizedEntity(gcmSenderID, scope: kGGLInstanceIDScopeGCM, options: registrationOptions, handler: registrationHandler) } // [END on_token_refresh] // [START upstream_callbacks] func willSendDataMessageWithID(messageID: String!, error: NSError!) { if (error != nil) { // Failed to send the message. } else { // Will send message, you can save the messageID to track the message } } // [START receive_apns_token_error] func application( application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError ) { print("Registration for remote notification failed with error: \(error.localizedDescription)") // [END receive_apns_token_error] let userInfo = ["error": error.localizedDescription] NSNotificationCenter.defaultCenter().postNotificationName( registrationKey, object: nil, userInfo: userInfo) } func didSendDataMessageWithID(messageID: String!) { // Did successfully send message identified by messageID } // [END upstream_callbacks] func didDeleteMessagesOnServer() { // Some messages sent to this device were deleted on the GCM server before reception, likely // because the TTL expired. The client should notify the app server of this, so that the app // server can resend those messages. } //MRAK: End of GCM Function func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } } And this is my testing page where it receives the notification of a successful registration:
class PlayGroundController: UIViewController{ @IBOutlet weak var registeringLabel: UILabel! @IBOutlet weak var registrationProgressing: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PlayGroundController.updateRegistrationStatus(_:)), name: appDelegate.registrationKey, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PlayGroundController.showReceivedMessage(_:)), name: appDelegate.messageKey, object: nil) registrationProgressing.hidesWhenStopped = true registrationProgressing.startAnimating() } func updateRegistrationStatus(notification: NSNotification) { registrationProgressing.stopAnimating() if let info = notification.userInfo as? Dictionary<String,String> { if let error = info["error"] { registeringLabel.text = "Error registering!" showAlert("Error registering with GCM", message: error) } else if let _ = info["registrationToken"] { registeringLabel.text = "Registered!" let message = "Check the xcode debug console for the registration token that you " + " can use with the demo server to send notifications to your device" showAlert("Registration Successful!", message: message) } } else { print("Software failure. Guru meditation.") } } func showReceivedMessage(notification: NSNotification) { if let info = notification.userInfo as? Dictionary<String,AnyObject> { if let aps = info["aps"] as? Dictionary<String, String> { showAlert("Message received", message: aps["alert"]!) } } else { print("Software failure. Guru meditation.") } } func showAlert(title:String, message:String) { //Set up for the title color let attributedString = NSAttributedString(string: title, attributes: [ NSFontAttributeName : UIFont.systemFontOfSize(15), //your font here, NSForegroundColorAttributeName : UIColor.whiteColor() ]) //Set up for the Message Color let attributedString2 = NSAttributedString(string: message, attributes: [ NSFontAttributeName : UIFont.systemFontOfSize(15), //your font here, NSForegroundColorAttributeName : UIColor.whiteColor() ]) let alert = UIAlertController(title: title,message: message, preferredStyle: .Alert) alert.setValue(attributedString, forKey: "attributedTitle") alert.setValue(attributedString2, forKey: "attributedMessage") //alert.view.tintColor = UIColor.whiteColor() let dismissAction = UIAlertAction(title: "Dismiss", style: .Destructive, handler: nil) alert.addAction(dismissAction) self.presentViewController(alert, animated: true, completion: nil) //set the color of the Alert //let subview = alert.view.subviews.first! as UIView //let alertContentView = subview.subviews.first! as UIView //alertContentView.backgroundColor = UIColor.blackColor() let subview :UIView = alert.view.subviews.last! as UIView let alertContentView = subview.subviews.last! as UIView alertContentView.backgroundColor = UIColor.blackColor() //alertContentView.backgroundColor = UIColor.greenColor() //Changes is to a grey color :( /* alertContentView.backgroundColor = UIColor( red: 0, green: 0, blue: 0, alpha: 1.0) //Also another Grey Color Not batman black */ //alertContentView.backgroundColor = UIColor.blueColor() //turns into a purple } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) }
-13725370 0 If you need to analyse C# code at runtime, take a look at Roslyn.
-36131248 0 tfs unable to browse projectsI'm using Visual Studio Team Services (was TFS Online) server {MyProject}.visualstudio.com. I'm able to connect to the server, map the project, even receive a review request, but I can't see my team projects under DefaultCollection. Currently when I'm opening the Source Control Explorer I'm only seeing {MyProject}.visualstudio.com\DefaultCollection underlying projects are missing, but my user is in project team members list.
What I missed, what I should do else to be able to browse my projects, get and work with them?
Note: My account was not a microsoft account. I received an email to join the visual studio after tfs administrator added my email as the project team member. I follow to the link and I create a new account during VS sign up using that email and then successfully signed in.
Thanks a lot
-36022303 0 Error when publishing from VS 2015 - The components for communicating with FTP servers are not installedI'm using Visual Studio 2015 Enterprise with Update 1. I have a single solution, with a single ASP.NET web application project. I publish it by right-clicking on the project node, and clicking "Publish". I've setup a publish profile for FTP. Credentials work/tested/etc. Server connectivity is good.
However, when publish from Visual Studio 2015, it says "The components for communicating with FTP servers are not installed."
Things I've tried: - Validating FTP server name and credentials. - Clean/Rebuild - Restarting Visual Studio. - Kicking it (hard).
Things I did not try: - Restarting PC. - Repairing Visual Studio. - Sacrificing a goat.
I do NOT have Xamarin installed, but I do have Tools for Apache Cordova. I do NOT have VS 2013 (or any prior version) of VS installed.
-15772958 0 How can I copy dependencies from the local repository to some specific location?I want copy all the dependencies from the local repository to some specific location without have to specify which dependencies should be copied, I just want that copy all the dependencies that I declared in the pom in specific folder.
-9780306 0You shouldn't need to destroy and create the annotation every time. Once it has been created, just update the anchorPoint. Removing and adding the annotation is probably related to the constant redraw.
Here's my solution to make it a little more generic:
private static final String[] magnitudes = new String[] {"", "K", "M"}; public static String shortenNumber(final Integer num) { if (num == null || num == 0) return "0"; float res = num; int i = 0; for (; i < magnitudes.length; i++) { final float sm = res / 1000; if (sm < 1) break; res = sm; } // don't use fractions if we don't have to return ( (res % (int) res < 0.1) ? String.format("%d", (int)res) : String.format("%.1f", res) ) + magnitudes[i]; }
-24883358 0 How to Add custom markers to a google directions map at the start only of multiple journeys Firstly let me say I am not a Java or even web developer. I have pieced together this code via the web and am almost at the finish point - but cannot get over the line.
I am mapping journeys for a trucking firm, and want to use a custom marker at the start of each journey, with no marker at the end of the journey. The attached code does all I need for mapping the journey but I can't get the markers to render on the page. What am I missing?
var directionsService = new google.maps.DirectionsService(); var num, map, data; var requestArray = [], renderArray = []; // A JSON Array containing some people/routes and the destinations/stops var jsonArray = { "Journey1": ["-38.076600, 176.722100", "-38.279641, 175.897505"], "Journey2": ["-38.279641, 175.897505", "-38.058217, 175.783939"], "Journey3": ["-38.058217, 175.783939", "-37.964919, 175.478964"], "Journey4": ["-37.964919, 175.478964", "-38.323678, 175.152163"], "Journey5": ["-38.323678, 175.152163", "-38.274879, 175.894551"], "Journey6": ["-38.274879, 175.894551", "-38.095284, 176.076530"], "Journey7": ["-38.095284, 176.076530", "-38.075316, 176.716276"], "Journey8": ["-38.075316, 176.716276", "-38.076600, 176.722100"] } // 16 Standard Colours for navigation polylines var colourArray = ['Maroon', 'Green', 'Olive', 'DarkBlue', 'Violet', 'Teal', 'Gray', 'Silver']; var Labelarray = [ 'Kawerau Depot, Ex: CHH Kawerau - Cogen Plant Kinleith - Hogfuel - CHH KINLEITH', 'Cogen Plant Kinleith - TD Haulage Pinedale - Empty', 'TD Haulage Pinedale - Gascoigne Farms Cambridge - Post Peeling - Untreated - GASCOIGNE FARMS LTD', 'Gascoigne Farms Cambridge - Tregoweth Te Kuiti - Empty', 'Tregoweth Te Kuiti - CHH Kinleith - Chip - FLL NETLOGIX LTD', 'CHH Kinleith - Mamaku Sawmill Mamaku - Empty', 'Mamaku Sawmill Mamaku - CHH Kawerau - Chip - FLL NETLOGIX LTD', 'CHH Kawerau - Kawerau Depot - Empty']; // Let's make an array of requests which will become individual polylines on the map. function generateRequests() { requestArray = []; for (var route in jsonArray) { // This now deals with one of the people / routes // Somewhere to store the wayoints var waypts = []; // 'start' and 'finish' will be the routes origin and destination var start, finish // lastpoint is used to ensure that duplicate waypoints are stripped var lastpoint data = jsonArray[route] limit = data.length for (var waypoint = 0; waypoint < limit; waypoint++) { if (data[waypoint] === lastpoint) { // Duplicate of of the last waypoint - don't bother // continue; } // Prepare the lastpoint for the next loop lastpoint = data[waypoint] // Add this to waypoint to the array for making the request waypts.push({ location: data[waypoint], stopover: true }); } // Grab the first waypoint for the 'start' location start = (waypts.shift()).location; // Grab the last waypoint for use as a 'finish' location finish = waypts.pop(); if (finish === undefined) { // Unless there was no finish location for some reason? finish = start; } else { finish = finish.location; } // Let's create the Google Maps request object var request = { origin: start, destination: finish, waypoints: waypts, travelMode: google.maps.TravelMode.DRIVING }; // and save it in our requestArray requestArray.push({ "route": route, "request": request }); } processRequests(); } function processRequests() { // Counter to track request submission and process one at a time; var i = 0; // Determines if we will use an image for the icon 1 = true, 0 = false var UseImage = 1; var j = 0; var x = 0; // Used to submit the request 'i' function submitRequest() { directionsService.route(requestArray[i].request, directionResults); } // Used as callback for the above request for current 'i' function directionResults(result, status) { if (status == google.maps.DirectionsStatus.OK) { j++; //j = i + 1 // Create a unique DirectionsRenderer 'i' renderArray[i] = new google.maps.DirectionsRenderer({ suppressMarkers: true }); renderArray[i].setMap(map); renderArray[i].setOptions({ preserveViewport: true, suppressInfoWindows: true, polylineOptions: { strokeWeight: 3, strokeOpacity: 0.8, strokeColor: colourArray[i] } }); //************************************** // this is the code I am trying to add in so that I get a marker only at the start position of the line. // Shapes define the clickable region of the icon. var shape = { coords: [1, 1, 1, 20, 18, 20, 18, 1], type: 'poly' }; // Add markers to the map var image = { url: "Marker Green " + j + ".png", // This marker is 27 pixels wide by 40 pixels tall. size: new google.maps.Size(27, 40), // The origin for this image is 0,0. origin: new google.maps.Point(0, 0), // The anchor for this image is the base of the icon at 14, 39. anchor: new google.maps.Point(14, 39) }; var marker = new google.maps.Marker({ position: new google.maps.LatLng(requestArray[i].request.origin), map: map, icon: image, shape: shape, title: Labelarray[i] + ' - ' + requestArray[i].request.origin, zIndex: i }); //************************************** //end of code I am trying to get to work } // Use this new renderer with the result renderArray[i].setDirections(result); // and start the next request nextRequest(); } function nextRequest() { // Increase the counter i++; // Make sure we are still waiting for a request if (i >= requestArray.length) { // No more to do return; } // Submit another request submitRequest(); } // This request is just to kick start the whole process submitRequest(); } // Called Onload function init() { // Some basic map setup (from the API docs) //Map centre var mapOptions = { center: new google.maps.LatLng(-38.143567, 175.965254), zoom: 9, mapTypeControl: true, streetViewControl: true, zoomControl: true, panControl: true, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); // Start the request making generateRequests() } // Get the ball rolling and trigger our init() on 'load' google.maps.event.addDomListener(window, 'load', init);
-21071686 0 Spring 404 error I am trying to run spring application, but i am getting the 404 error. Can anyone please help? I take this code from mkyong site. The example he given is working but i tried to do everything from scratch it is not working.
package com.mkyong.common.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping("/welcome") public class HelloController { @RequestMapping(method = RequestMethod.GET) public String printWelcome(ModelMap model) { model.addAttribute("message", "Spring 3 MVC Hello World"); return "hello"; } } hello.jsp <html> <body> <h1>Message : ${message}</h1> </body> </html> mvc-dispatcher-servlet.xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.mkyong.common.controller" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/pages/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans> web.xml <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>Spring Web MVC Application</display-name> <servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
-21665315 0 I believe there is no way to make it compile. You will have to use reflection to make the call.
Actually. You could cheat if you contain it within a class:
public class Container<T> { public Container(T value) { Value = value; } public T Value { get; private set; } } public void Bar<T>(T item) { this.Foo<Container<T>>(new Container<T>(item)); } but this adds one layer you need to call-through and makes the types less clear.
-13996618 0Here:
function isNull() { var isChecked = false; var radiobutton = document.getElementsByName('radiobtn'); for (var i=0; i < radiobutton.length; i++) { if (radiobutton[i].checked) { isChecked = true; } } if ( !isChecked ) { alert("Make a selection."); return false; } } I don't know how your form tag looks, but here is what you need to prevent the form from submitting if no radio fields are checked:
<form action="" method="post" onSubmit="return isNull();">
-7247541 0 How to findAll in mongoosejs? My code is like that:
SiteModel.find( {}, function(docs) { next(null, { data:docs}); } ); but it never returns anything... but if I specify something in the {} then there is one record. so, how to findall?
-12006124 0You should look in the default_master.properties file (in my case it's in the same directory as js-export) and change the database properties according to your setup.
Then js-export and js-import should work.
-21975826 0 Split a string with using preg_split()I have a sting that is in this format.
<span class="amount">$25</span>–<span class="amount">$100</span> What I need to do is split that into two strings. The string will remain in the same format but the prices will change. I tried using str_split() but because the price changes I wouldn't be able to always know how many characters to split the string at.
What I am trying to get is something like this.
String 1
<span class="amount">$25</span>– String 2
<span class="amount">$100</span> It seems the best option I have found is to use preg_split() but I don't know anything about regex so I'm not sure how to format the expression. There may also be a better way to handle this and I just don't know of it.
Could someone please help me format the regex, or let me know of a better way to split that string.
Thanks to @rm-vanda for helping me figure out that I don't need to use preg_split for this. I was able to split the string using explode(). The issue I was having was because the '-' was encoded weird and therefore not returning correctly.
-37048308 0-27446413 0 SVG path animation issueReturns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
I'm new to CSS animations and I'm struggling to get this animation working.
I've been following this CSS Tricks post.
Currently I don't understand why there are three separate starting point in the animation.
I would like to start from one point, follow the path all the way(doesn't matter which direction) and close the animation at the starting point.
Is that possible? If it is, can anyone tell what's wrong in what I've tried so far?
Any help appreciated, thanks.
This is the code in the demo (I've cut some svg code out):
HTML
<svg xmlns="http://www.w3.org/2000/svg" width="3.27778in" height="3.27778in" viewBox="0 0 236 236"> <path class="path" fill="none" stroke="black" stroke-width="2" d="M 236.00,0.00 C 236.00,0.00 236.00,236.00 236.00,236.00 236.00,236.00 0.00,236.00 0.00,236.00 0.00,236.00 0.00,0.00 0.00,0.00 0.00,0.00 236.00,0.00 236.00,0.00 Z M 74.00,34.00 ......... C 212.00,194.00 213.00,195.00 213.00,195.00 213.00,195.00 213.00,194.00 213.00,194.00 213.00,194.00 212.00,194.00 212.00,194.00 Z" /> </svg> CSS
.path { stroke-dasharray: 1000; stroke-dashoffset: 1000; animation: dash 10s linear infinite; } @keyframes dash { from { stroke-dashoffset: 1000; } to { stroke-dashoffset: 0; } }
-4787678 0 According to the documentation of Boost shared_ptr, the shared_ptr constructor is marked explicit, meaning that there's no implicit conversion from T*s to shared_ptr<T>. Consequently, when you're trying to insert the iterator range defining your old container into the new container, the compiler complains because there's no way of implicitly converting from the raw pointers of the old containers into the shared_ptrs of the new container. You can fix this by either using a back_inserter and transform, or by just doing the iteration by hand to wrap each pointer and insert it one at a time.
It turns out that there's a good reason that you don't want this conversion to work implicitly. Consider:
void DoSomething(shared_ptr<T> ptr) { /* ... */ } T* ptr = new T(); DoSomething(ptr); If the implicit conversion were allowed here, then the call to DoSomething would be legal. However, this would cause a new shared_ptr to start referencing the resource held by ptr. This is problematic, because when this shared_ptr goes out of scope when DoSomething returns, it will see that it's the only shared_ptr to the resource and will deallocate it. In other words, calling DoSomething with a raw pointer would implicitly delete the pointer!
I have run on terminal to install easy-captcha for my app.
npm install easy-captcha --save and error appeared:
gyp ERR! build error gyp ERR! stack Error: `make` failed with exit code: 2 gyp ERR! stack at ChildProcess.onExit (/home/haihv94/Applications/nodejs/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:269:23) gyp ERR! stack at ChildProcess.emit (events.js:110:17) gyp ERR! stack at Process.ChildProcess._handle.onexit (child_process.js:1074:12) gyp ERR! System Linux 3.19.0-25-generic gyp ERR! command "node" "/home/haihv94/Applications/nodejs/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild" gyp ERR! cwd /home/haihv94/NDM/ndm.org/node_modules/easy-captcha gyp ERR! node -v v0.12.7 gyp ERR! node-gyp -v v2.0.1 gyp ERR! not ok npm ERR! Linux 3.19.0-25-generic npm ERR! argv "/home/haihv94/Applications/nodejs/bin/node" "/home/haihv94/Applications/nodejs/bin/npm" "install" "easy-captcha" "--save" npm ERR! node v0.12.7 npm ERR! npm v2.11.3 npm ERR! code ELIFECYCLE npm ERR! easy-captcha@0.1.5 install: `node-gyp rebuild` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the easy-captcha@0.1.5 install script 'node-gyp rebuild'. npm ERR! This is most likely a problem with the easy-captcha package, npm ERR! not with npm itself. npm ERR! Tell the author that this fails on your system: npm ERR! node-gyp rebuild npm ERR! You can get their info via: npm ERR! npm owner ls easy-captcha npm ERR! There is likely additional logging output above. npm ERR! Please include the following file with any support request: npm ERR! /home/haihv94/NDM/ndm.org/npm-debug.log I've tried installing another npm to using captcha (s.a recaptcha, node-captcha) but same error! How can I solve this problem? thanks all!
-20521383 0 Updating MySQL database with values from dynamically generated textboxes in different divsI'll try my best to explain my problem here, forgive me if I use the wrong terms occasionally, I'm still pretty much a beginner, and quite terrible at explaining.
My goal is to use Jquery to dynamically add textboxes, and then use C# to update the values in those textboxes into a mysql database.
The database consists of four columns, UserID(PK), Date(PK), Subject(PK) and Hours. The goal is to be able to fill in the amount of hours you've worked on a subject on certain day of the current week.
So far, I'm able to add a new textbox whenever I press the button for the day I want to update the data for. The problem I'm running into is that I have no idea how to build the mysql query in such a way that it correctly associates the entered values with the day they're entered for.
My code so far:
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script> <script type="text/javascript"> </script> <title></title> </head> <body> <form id="form1" runat="server"> <div id="dag1" runat="server"> <input class="btnAdd" type="button" value="Monday" onclick="AddTextBox($(this).parent().attr('id'));" /> </div> <div id="dag2" runat="server"> <input class="btnAdd" type="button" value="Tuesday" onclick="AddTextBox($(this).parent().attr('id'));" /> </div> <div id="dag3" runat="server"> <input class="btnAdd" type="button" value="Wednesday" onclick="AddTextBox($(this).parent().attr('id'));" /> </div> <div id="dag4" runat="server"> <input class="btnAdd" type="button" value="Thursday" onclick="AddTextBox($(this).parent().attr('id'));" /> </div> <div id="dag5" runat="server"> <input class="btnAdd" type="button" value="Friday" onclick="AddTextBox($(this).parent().attr('id'));" /> </div> <br /> <br /> <div id="TextBoxContainer"> <script type="text/javascript"> function AddTextBox(day) { var value = "" var div = document.createElement('DIV'); div.innerHTML = '<input name = "Subject" type="text" value = "' + value + '" /><input name = "Hours" type="text" value = "' + value + '" />'; document.getElementById(day).appendChild(div); } </script> </div> <br /> <asp:Button ID="btnPost" runat="server" Text="Post" OnClick="Post" /> <asp:Label ID="labeltest" Text="" runat="server" /> </form> </body> </html> And my codebehind:
protected string Values; protected void Post(object sender, EventArgs e) { string[] textboxValues = Request.Form.GetValues("Subject"); string[] textboxValues2 = Request.Form.GetValues("Hours"); MySqlConnection conn; MySqlCommand comm; string myConnectionString = "server=localhost;uid=root;database=caroussel"; using (conn = new MySqlConnection()) { try { int veld = 0; foreach (string val in textboxValues) { string value2 = textboxValues2[veld]; veld++; using (comm = new MySqlCommand("update uren set Subject=@Subject, Hours=@Hours WHERE Date=??? AND UserID=1, conn)) ; comm.Parameters.Add("@Subject", MySqlDbType.VarChar, 45); comm.Parameters["@Subject"].Value = val; comm.Parameters.Add("@Hours", MySqlDbType.Int16); comm.Parameters["@Hours"].Value = value2; comm.Parameters.Add("@UserID", MySqlDbType.Int16); comm.Parameters["@UserID"].Value = 1; comm.Parameters.Add("@Date", MySqlDbType.VarChar, 45); comm.Parameters["@Date"].Value = ????; { conn.ConnectionString = myConnectionString; conn.Open(); comm.ExecuteNonQuery(); conn.Close(); } } } finally { conn.Close(); } } } If there's anything missing, or clarification is required, or I simply forgot something, please do tell, I'm rather stuck at the moment, and I haven't been able to find something that would help me so far.
-22807565 0 Servlet file upload ismultipartcontent returns falseI am trying to upload a selected file from the local file system to a folder within the application. Here technology used is jsp, servlet.
On clicking the Press button of Example.jsp, the control passes to the Request servlet. But the checking that if the request is multi part returns false. so "Sorry this Servlet only handles file upload request" is printed in the console.
Example.jsp
<form action="Request" method="Post" name = "invoices" target="_self"> <div class="invoicetable"> <table> <colgroup> <col class="first" span="1"> <col class="rest" span="1"> </colgroup> <tr> <td>Start date:</td> <td><input type = "text" name = "start_date" id="datepicker" size = "6" maxlength="10"/></td> </tr> <tr> <td>End date:</td> <td><input type = "text" name = "end_date" id="datepicker2" size = "6" maxlength="10"/></td> </tr> <tr> <form action="Request" enctype="multipart/form-data" method="post" name = "upload"> <table> <tr> <td>Input File:</td> <td><input type = "file" name ="datafile" size="30" maxlength="200"/></td> </tr> </table> <div> <input type ="submit" name="invoice" value="Press"/> to upload the file! <input type="hidden" name = "type" value="upload"> </div> </form> </tr> <tr> <td>Regular</td> <td> <input type = "radio" name ="input_type" value="regular"/> </td> </tr> <tr> <td>Manual</td> <td> <input type = "radio" name ="input_type" value="manual" checked/> </td> </tr> <tr> <td>Final</td> <td> <input type = "radio" name ="input_type" value="final"/> </td> </tr> </table> </div> <div style="margin-left: 20px"> <input type ="submit" name="invoice" value="Submit" class="button"/> <input type="hidden" name = "type" value="invoice"> </div> </form> Request - doPost method
jsp_request = request.getParameter("type"); if (jsp_request.equalsIgnoreCase("upload")) { String file_location = request.getParameter("datafile"); ServletFileUpload uploader = null; //Checking if the request is multipart if(ServletFileUpload.isMultipartContent(request)){ try { String upload_location_holder = request.getServletContext().getRealPath(""); upload_location_holder = upload_location_holder.substring(0,upload_location_holder.indexOf(".")) + upload_location_holder.substring(upload_location_holder.lastIndexOf("/")+1); //excel file goes into the input files folder String excel_name = upload_location_holder + "/WebContent/input_files/" + file_location; File file = new File(excel_name); DiskFileItemFactory fileFactory=new DiskFileItemFactory(); fileFactory.setRepository(file); uploader = new ServletFileUpload(fileFactory); List<FileItem> fileItemsList = uploader.parseRequest(request); Iterator<FileItem> fileItemsIterator = fileItemsList.iterator(); while (fileItemsIterator.hasNext()) { FileItem item = (FileItem) fileItemsIterator.next(); if (!item.isFormField()) { String fileName = item.getName(); String root = getServletContext().getRealPath("/"); File path = new File(root + "/uploads"); if (!path.exists()) { boolean status = path.mkdirs(); } File uploadedFile = new File(path + "/" + fileName); System.out.println(uploadedFile.getAbsolutePath()); item.write(uploadedFile); } } //File uploaded successfully request.setAttribute("message", "File Uploaded Successfully"); } catch (Exception ex) { // request.setAttribute("message", "File Upload Failed due to " + ex); ex.printStackTrace(); } }else{ System.out.println("Sorry this Servlet only handles file upload request"); } } I tried googling for a possible solution. but didnot land with any answer. Any help appreciated.
-40103236 0The Equals method and the IEquatable<T> interface could be used to know if two objects are equal but they won't allow you to know the differences between the objects.
I'm having trouble wrapping my head around how to interface with C/C++ libraries, both static (.lib/.a) and dynamic (.dll/.so), in D. From what I understand, it's possible to tell the DMD compiler to link with .lib files, and that you can convert .dll files to .lib with the implib tool that Digital Mars provides. In addition, I've come across this page, which implies being able to call functions in .dlls by converting C header files to D interface files. Are both of these methods equivalent? Would these same methods work for Unix library files? Also, how would one reference functions, enums, etc from these libraries, and how would one tell their D compiler to link with these libs (I'm using VisualD, specifically)? If anyone could provide some examples of referencing .lib, .dll, .a, and .so files from D code, I'd be most grateful.
-40636558 0Sorry cordova application works at your device. It does not operate at your network switch/router. There is yet no way that your device could ask your router if it has working internet access and the router could acknowledge that yes i have or not. What you could do at your device only to detect network access.
The only other thing you can do is send an http request to something like google which is almost never down, in device ready event or when required, if it responds with ready state then your internet is ok and otherwise not.
A function to test this address to check if the device has access to internet would look like this :
function testInternet(win,fail){ $.get("https://people.googleapis.com/v1/people/me/connections").done(win).fail(fail); } Or , function testInternet(win,fail){ $.ajax({ url:"https://people.googleapis.com/v1/people/me/connections", timeout:5000, //timeout to 5s type: "GET", cache: false }).done(win).fail(fail); } ajax request response back 401 (Unauthorized) which means we have internet access but we are Unauthorized for that google api. here is the google api
-17852249 0 svn2git: Cannot setup tracking informationThe plugin does not detect if the user has access to the Internet, but only if the user is on a network. Since your phone is on a WiFi network even though the WiFi network doesn't have access to the Internet, the plugin is performing as designed.
I am trying to migrate a SVN project to git with thel help of svn2git. When executing the command it exits with the following error:
Running command: git branch --track "0.0.9" "remotes/svn/0.0.9" fatal: Cannot setup tracking information; starting point 'remotes/svn/0.0.9' is not a branch. Started it with:
svn2git http://<host>/<project> I can't find any solution for it and it seems not many users has the same problem.
What can I do to solve this problem?
-8352772 0primarykey fields ( of any data-type ) are not included in the list returned by allFileds method of the Mapper.
You can prepend the field separately if you want
something like
var myMapperPrimaryKey=DummyMapper.primaryKeyField var fieldList=DummyMapper.allFields.toBuffer[BaseField] fieldList.prepend(myMapperPrimaryKey) // Now fieldList is having the primaryKey along with other fields.
-34601654 0 I am assuming the following format:
word definitionkey : definitionvalue [definitionkey : definitionvalue …] None of those elements may contain a space and they are always delimited by a single space.
The following code should work:
awk '{ for (i=2; i<=NF; i+=3) print $1, $i, $(i+1), $(i+2) }' file Explanation (this is the same code but with comments and more spaces):
awk ' # match any line { # iterate over each "key : value" for (i=2; i<=NF; i+=3) print $1, $i, $(i+1), $(i+2) # prints each "word key : value" } ' file awk has some tricks that you may not be familiar with. It works on a line-by-line basis. Each stanza has an optional conditional before it (awk 'NF >=4 {…}' would make sense here since we'll have an error given fewer than four fields). NF is the number of fields and a dollar sign ($) indicates we want the value of the given field, so $1 is the value of the first field, $NF is the value of the last field, and $(i+1) is the value of the third field (assuming i=2). print will default to using spaces between its arguments and adds a line break at the end (otherwise, we'd need printf "%s %s %s %s\n", $1, $i, $(i+1), $(i+2), which is a bit harder to read).
I have two tables. One is hall which is having following schema. 
One hall can have many events.I want halls which are available between two dates.For example halls between 2016-09-10 and enddate = 2016-09-15. I want all the halls which are not booked for the whole range of dates i.e 10,11,12,13,14,15.
-38275927 0Make the dictionary value(s) compiled re that can match your string:
import re productline = '8.H.5' pattern = re.compile(r'tata.xnl.\d\.\d-dev.1.0') pl_component_dict = {'8.H.5': pattern} component_branch = "tata.xnl.1.0-dev.1.0" if pl_component_dict[productline].match(component_branch): print "PASS" else: print "ERROR:Gerrit on incorrect component"
-35114477 0 There is no workaround.
Using non-top level imports will not work with native ES6 implementations. Babel allows it because it transpiles to CommonJS require, but it is technically not allowed in ES6.
eslint issue and according espree issue
-1861282 0 .net, UserControls, and application start timeWe have a medium sized application that depends on several usercontrols, namely:
A tablelayout panel, with 2x5 grid of usercontrols, with 3+ levels of inheritance. A big issue we're running into with our application has proven to be startup time (both cold\warm), one of the big big hangups we're getting is initializing this usercontrol grid.
From our timing reports, this form comes in at about 0.75 seconds for initialization, and cutting this down would be a big deal.
My question is: What the heck can I do to speed this up? Whenever I run timing checks on similar-complexity InitializeComponents (all windows, .net controls), the result is magnitudes less (<10 milleseconds) sometimes.
edit) I'm wondering if things like marking my final classes sealed or something similar would help.
edit2) I've looked deeper into the timing of initializecomponent, and for my current machine, The main container adds 10 components to it (at 10ms a piece). Each of those components adds 3 components (at 10ms a piece). 10x10 + 30x10 = 700ms. Unless I can increase the speed at which items get added to their containers, I think I'm SOL.
-22589182 0 Set 'nice' value to concrete processes, by defaultI would like to set specific "nice" values to several processes in a laptop. For example, I would like the window manager to run at -10, and keep the default at 0.
I know that "renice" can change the niceness of a processes, but this is a-posteriori, and I do not want to "renice" my window manager process every time that I open the computer. Similarly, "limits.conf" allows to specify default niceness for specific users or groups, but not (as far as I know) specific processes.
So my question is whether there is a way to define niceness for concrete processes, without having to change the default for the user and without having to renice the process once it runs.
-11622734 0 make tooltip display on click and add a modal to itstrangely, I find it difficult to bind jquery's onclick event handler to this fiddle. I don't even know what I'm doing wrong. The html is as follows:-
<ul> <li><a id="tooltip_1" href="#" class="tooltip" >Trigger1</a><li> <li><a id="tooltip_2" href="#" class="tooltip" >Trigger2</a><li> <li><a id="tooltip_3" href="#" class="tooltip" >Trigger3</a><li> </ul> <div style="display: none;"> <div id="data_tooltip_1"> data_tooltip_1: You can hover over and interacte with me </div> <div id="data_tooltip_2"> data_tooltip_2: You can hover over and interacte with me </div> <div id="data_tooltip_3"> data_tooltip_3: You can hover over and interacte with me </div> </div> styled this way:-
li { padding: 20px 0px 0px 20px; } with a jquery like this:-
$(document).ready(function() { $('.tooltip[id^="tooltip_"]').each (function(){ $(this).qtip({ content: $('#data_' + $(this).attr('id')), show: { }, hide: { fixed: true, delay: 180 } }); }); }); you check out the fiddle page I created:- http://jsfiddle.net/UyZnb/339/.
Again, how do I implement a jquery modal-like appearance to it so the tooltip becomes the focus?
-21687674 0The problem is that when you set a 100% height value it take the longitud from the parent container. If the conatiner is the body tag it ajustment to the size of the content it self that could be very samll. You need to set up the size to a specifycally size you can use the window size for example.
-20197287 0You are using JSON.Stringify; it should be JSON.stringify. Did you check your console for errors? Simply spitting the JSON out isn't too user-friendly, though. Is that what you want?
You're going to have to iterate over each individual skill and then insert that into the table in a format that you see fit (perhaps you can use an un-ordered list):
var $table = jQuery("table"); $table.append(jQuery("tr") .append( jQuery("th").text("First Name")) .append( jQuery("th").text("LastName")) ... //and so on ) for(var i = 0; i < data.length; i++) { var $tr = jQuery("tr"); $tr.append( jQuery("td").text(data[i].firstname}) ).append( jQuery("td").text(data[i].lastname) )... var skills = data[i].skills; var $ul = jQuery("ul"); for(var j = 0; j < skills.length; j++) { var skill = skills[j]; $ul.append(jQuery("li").text(skill.name)); } $tr.append(jQuery("td").append($ul)); }
-2008363 0 This should be very easy. Valid function names can only consist of alphanumerics, parenthesis, and possibly parameter values within the parens (i don't know enough javascript to know whether parameters are defined in the function call) and must start with a letter, correct? Therefore to validate that a string is a valid function name. Therefore this should work:
[a-xA-z]+[a-zA-z0-9_]\*(\\(.*?\\))\*
-24397530 0 The developer doesn't own the tabBar, the framework does. It will fight you to make sure that the tabBar stays the same height. If you want to work around this, you can make your own toolbar and add autlayout constraints to its height to force it to stay whatever height you'd like.
-12099227 0 When I put a record in the test database in rails, for how long does it persist?If, as part of an RSpec or Cucumber test in my Rails application, I create a model and store it in the test database, how long will the record remain there for?
I'm pretty sure that the records are cleared at the end (or beginning?) of every test cycle, because they don't seem to interfere with successive runs of my test suite, but do records persist between different cucumber features and scenarios, or between different RSpec tests?
-1857247 0 How do you write to an xml file in win32 C++?I would like to write a simple xml file using xmllite in win32 c++. the file will be saved over every time the user saves. How do I do this? I'd rather not include any new libraries for this...
I have a load of UserControl objects (ascx files) in their own little project. I then reference this project in two projects: The REST API (which is a class library project) and the main website.
I'm sure this would be easy in the website, simply use Controls.Add in any Panel or ASP.NET control would work.
However, what about the API? Is there any way I can render the HTML of this control, simply by knowing the type of the control? The RenderControl method doesn't write any HTML to the writer as the control's life cycle hasn't even started.
Please bare in mind that I don't have the controls in the web project, so I don't have a virtual path to the ascx file. So the LoadControl method won't work here.
All the controls actually derive from the same base control. Is there anything I can do from within this base class that will allow me to load the control from a completely new instance?
-6651380 0$textFields = $("input[type=text]"); Then you can test them individually using filter
$textFields.filter('[name=email]');
-1117686 0 I would do something like this. I'm thinking the problem could be the order of the rules, that say, the first rule will try to load the image/js/css since isn't looking if the file exists.
try this:
Options -Indexes RewriteEngine on Options +FollowSymLinks RewriteCond %{HTTP_HOST} !^www\.website\.com$ [NC] RewriteRule .* https://www.website.com/$1 [L,R=301] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ myfolder/index.php?q=$1 [L,QSA] RewriteRule ^$ myfolder/index.php [L]
-5510978 0 In Hudson, how do I get the current build's git commit sha? We are using Hudson with git. We have a build/test server which compiles our project and then a QA server to which we need to deploy.
We want to get the current built git commit sha and use it to pull the appropriate commit for deployment on our QA server.
Unfortunately it seems that the hudon git plugin does not set the git commit sha in the environment variables (as the svn plugin does in SVN_REVISION for example). How do we get around this?
Pointer/ examples will be helpful as I am a hudson noob.
Thanks
-30883783 0there's no such built-in functionality unless you utilize nested datasets that is. you should either implement some specific remote method wrapping all required modifications or enhance midas with extra means (see for example "KT Data Components" lib to get the idea how this could be implemented)
-34257839 0 Use $mdDialog stright from controllerTrying to use the $mdDialog when login fails; currently I have injected $mdDialog and where my response fails I have added the following code:
$mdDialog Code:
$mdDialog.show( $mdDialog.alert() .title('Username / password is incorrect') .textContent(response.message) .ok('Got it!')); Any Idea what am I doing wrong ?
My error
$mdDialog.alert(...).title(...).textContent is not a function My controller (I don't think its necessary but just encase ):
(function () { 'use strict'; angular .module('app') .controller('authController', authController); authController.$inject = ['$scope','$state','AuthService','$mdDialog']; function authController($scope,$state,AuthService,$mdDialog) { $scope.login = login; $scope.user = {email: 'user', pass: 'pass'}; function login(){ this.dataLoading = true; AuthService.Login(this.user.email, this.user.pass, function (response) { console.log(response); if (response.success) { $state.go("dashboard"); } else { $mdDialog.show( $mdDialog.alert().title('Username / password is incorrect').textContent(response.message) .ok('Got it!')); } }); } }; })();
-25107717 0 I just encountered this issue in CE v1.9.0.1. My admin module was getting all processes as a collection and looping through each one calling reindexEverything(). I based the code on the adminhtml process controller which was working fine, but my code wasn't working at all.
I finally figured out the issue was that I had previously set the reindex mode to manual (to speed up my product import routine) as follows:
$processes = Mage::getSingleton('index/indexer')->getProcessesCollection(); $processes->walk('setMode', array(Mage_Index_Model_Process::MODE_MANUAL)); // run product import $processes = Mage::getSingleton('index/indexer')->getProcessesCollection(); foreach($processes as $p) { if($p->getIndexer()->isVisible()) { $p->reindexEverything(); //echo $p->getIndexer()->getName() . ' reindexed<br>'; } } $processes = Mage::getSingleton('index/indexer')->getProcessesCollection(); $processes->walk('setMode', array(Mage_Index_Model_Process::MODE_REAL_TIME)); SOLUTION: set mode back to MODE_REAL_TIME before reindexing everything:
$processes = Mage::getSingleton('index/indexer')->getProcessesCollection(); $processes->walk('setMode', array(Mage_Index_Model_Process::MODE_MANUAL)); // run product import $processes = Mage::getSingleton('index/indexer')->getProcessesCollection(); $processes->walk('setMode', array(Mage_Index_Model_Process::MODE_REAL_TIME)); $processes = Mage::getSingleton('index/indexer')->getProcessesCollection(); foreach($processes as $p) { if($p->getIndexer()->isVisible()) { $p->reindexEverything(); //echo $p->getIndexer()->getName() . ' reindexed<br>'; } } Note: these are snips from a few different methods hence the repeated assignment of $processes etc..
It seemed reindexEverything() wasn't doing anything when the processes index mode was set to MODE_MANUAL. Setting mode back to MODE_REAL_TIME and then calling reindexEverything worked fine.
I hope this helps someone as I had a few frustrated hours figuring this one out!
Thanks
-23249089 0 Sum of a field with respect to another fieldI have a table of employees Salary named as empSalary.

I want to calculate sum of salaries issued by each department. What comes to my mind is
Select sum(Salary) from empSalary where deptId = (Select deptId from empSalary) This statement gives me 5100 which is the sum of Salary where deptId = 1. How is this possible using only sql query? Sorry for the question title as i was unable to find words.
-37369628 0PHP cannot find the index referer in the variable $_GET, you should first test if the index exist, Try this:
PHP
<input id="refer" placeholder="<?php echo $txt['not_oblige']; ?>" type="text" name="referer" value="<?php echo (isset($_GET['referer'])) ? $_GET['referer'] : '' ; ?>" class="form-control" />
-4820593 0 How can I use .Net system.drawing.drawstring to write right-to-left string (project is a dll)? Hi I need to create a bitmap file from an string, currently I'm using
Bitmap b = new Bitmap(106, 21); Font f = new Font("Tahoma",5 ); StringFormat sf = new StringFormat(); int faLCID = new System.Globalization.CultureInfo("fa-IR").LCID; sf.SetDigitSubstitution(faLCID, StringDigitSubstitute.National); Brush brush = Brushes.Black; Point pos = new Point(2, 2); Graphics c = Graphics.FromImage(b); c.FillRectangle(Brushes.White, 0, 0, m_width, m_length); c.DrawString(stringText, f, brush, pos,sf); it works but the problem is it is writing left to right. How can I make DrawString() to write right-to-left? thanx
-536695 0you including your own code. how safe is it?
-8023571 0 What's wrong with this QuickSort program?I've written a QuickSort algorithm based off pseudo-code that I had been given. I've been running through the outputs for about 4 hours now and I can't seem to find exactly why my algorithm starts to derail. This sort of collection logic is something I struggle with.
Anyway, whenever I run my program there's 3 possible results:
Given my results it leads me to believe that something has to do with the index variable I'm using. However, I can' figure out why or what's wrong with it.
Here's ALL of my code that I use for my QuickSort algorithm:
public void QuickSort(IList<int> list, int l, int r) { if (l>=r) return; int index = Partition(list, l, r); Console.WriteLine("index: " + index); QuickSort(list, l, (index-1)); QuickSort(list, (index+1), r); } public int Partition(IList<int> list, int l, int r) { int pivot = list[l]; int i = l; int j = r + 1; do { do { i++; } while(i < list.Count && list[i] < pivot); do { j--; } while(j > 0 && list[j] >= pivot); Swap(list, i, j); } while(i<j); Swap(list, i ,j); Swap(list, j, l); return j; } public void Swap(IList<int> list, int i, int j) { //Console.WriteLine("Swapping [i] " + list[i] + " with [j] " + list[j]); //PrintList(list, i, j, false); int temp = list[i]; list[i] = list[j]; list[j] = temp; //PrintList(list, j, i, true); } PrintList is simply used to test my outputs.
Here is a sample input/output:
INPUT: [18,43,5,73,59,64,6,17,56,63]
OUTPUT: [5,6,18,17,43,59,56,63,64,73]
-24658299 0 How to optimize a subset of JavaScript files created as RequireJS modulesI have single-page web application that uses RequireJS to organize and structure JavaScript code. Inside the app, I have some JS files that I want to optimize using r.js because they belong to an API that will be consumed by my customers. So, I just want to optimize those files and keep the rest of the code as it is now.
This is my application structure:
All the JavaScript code is located under the app and scripts folders. As I mentioned before, all those files are defined as RequireJS modules. This is how the main.js looks now:
require.config({ baseUrl: 'scripts', paths: { base: 'myAPI/base', proxy: 'myAPI/proxyObject', localization: 'myAPI/localization', app: '../app', } }); require(['myAPI/app'], function (app) { //app.init.... } ); As you can see, in the paths configuration I'm defining some aliases that point to myAPI (the folder I want to optimize).
This is how I reference RequireJS from the index.htm file:
<script data-main="app/main" src="scripts/require.js"></script> This is the build file I created for r.js (scripts/build.js):
({ baseUrl: '.', out: 'build/myAPI.js', name: 'myAPI/app', include: ['some modules'], excludeShallow: ['some modules defined in the app folder'], mainConfigFile: '../app/main.js', optimize: 'uglify2', optimizeCss: 'none' }) The optimized file is generated, but I have some challenges trying to use it:
Could you please help me with some suggestions or feedback for this situation?
Thanks!!
-6610877 0as far as I can see you have a custom comparator (why does that keep a reference to the sorter? looks fishy) not a custom RowSorter.
The intended way to change sorting is to invoke toggleSortOrder(column) on RowSorter. For more fine-grained control you can need access to the DefaultRowSorter, f.i. its setSortKeys method.
-31301870 0This info on the changelog is more related to the fact that before the maximum number of concurrent sockets node could handle was set to 5 (it was changeable of course) but now it is set to Infinity by default.
This has nothing to do with the capacity of connexions an application can handle, that will be limited by the network's characteristics, the OS specifications, the available resources on the server, etc.
In short, you are looking at something (the blog post) that has nothing to do with your question.
-9945049 0 Tablet landscape specific with media queriesI have a 'responsive' website but there are some links I only want on 'pc browsers' only and not on 'tablet landscape' becasue they link off to flash objects.
So far this is what I have done but it't not a 100% fix as some android tablets such as 'Lenovo think pad' which have a bigger screen.
I am using media queries to make my site responsive and this is what I'm currently using...
@media only screen and (max-device-width : 1024px) and (orientation:landscape) { header.Site { nav.Site > ul > li { line-height: 2 ; } div.BidSessionCountdown, a.LiveOnline { display: none; } } } Is there any CSS fixes you can think of?
Thank you in advance Tash :D
-7809186 0You need this syntax:
depth := Default(Nullable<Double>);
-5598476 1 Django filter for converting the number of seconds into a readable form I have model:
class Track(models.Model): artist = models.CharField(max_length=100) title = models.CharField(max_length=100) length = models.PositiveSmallIntegerField() where length is the duration of track in seconds
I have template:
{% for track in tracks %} {{track.artist}} - {{track.title}} {{track.length}} {% endfor %} How can I convert a length in the readable form, ie 320 seconds should be displayed as 5:20, 3770 as 1:02:50?
Forgive sorry for bad english.
-11912623 0In order to submit POST data, the data must be sent to the server. A hyperlink alone cannot do this - however with a bit of JS magic, you can easily accomplish this.
If you're using something like jQuery, you can capture the click event - gather data from the link based on the click event, and submit to the server via $.post/$.ajax.
HTML:
<a href="javascript:void(0);" class="age-less-then-five">age<5</a> Javascript:
$('a.classname').click(function(){ var that = $(this), value = that.text().trim(); //you can optionally store a value in the classname, or ID which is what I would do.. in this scenario.. I think XD $.post('yoururl.com/phpscript.php',{postName: value}, function(data){ //load whatever data you want, or redirect to list.html now that you've gathered desired data } }); To clarify the above answer, var that = $(this); refers to the link that's been clicked on. So you could grab the class name from the anchor by: that.attr('class') // which would equal age-less-then-five or simply do as above, and grab the text inbetween the anchor tags by using .text(). We trim here, this really isn't the best way to do this.. but it is one way to do it. When I'm using a link to perform any sort of post to the server, I'll typically use an ID if it holds a unique value, or class name.
-28285970 0You are missing the .call() when you're trying to make an array copy from the HTMLCollection. Instead of this:
var x = document.getElementsByTagName("th"); var plop = Array.prototype.slice(x); You can do this:
var x = document.getElementsByTagName("th"); var plop = Array.prototype.slice.call(x); console.log(plop); Note: you don't need to make an array copy just to iterate over it. You can iterate an HTMLCollection directly:
var items = document.getElementsByTagName("th"); for (var i = 0; i < items.length; i++) { console.log(items[i]); }
-27769205 0 Swift Dictionary of Arrays I am making an app that has different game modes, and each game mode has a few scores. I am trying to store all the scores in a dictionary of arrays, where the dictionary's key is a game's id (a String), and the associated array has the list of scores for that game mode. But when I try to initialize the arrays' values to random values, Swift breaks, giving me the error below. This chunk of code will break in a playground. What am I doing wrong?
let modes = ["mode1", "mode2", "mode3"] var dict = Dictionary<String, [Int]>() for mode in modes { dict[mode] = Array<Int>() for j in 1...5 { dict[mode]?.append(j) let array:[Int] = dict[mode]! let value:Int = array[j] //breaks here } } ERROR:
Execution was interrupted, reason: EXC_BAD_INSTRUCTION(code=EXC_I386_INVOP, subcode=0x0).
-14315005 0 Here is what I would do: I would write a static function for formatting your dates (either using my own class or extending Kohana Date class). I would use this function in your view directly:
<?php echo SomeClass::date_format($result->time_start, $result->time_finished) ?> Why in the view? Because the function is used for formatting, it doesn't actually return different data set.
-21984914 0You can use the view's controller property to access the controller. Using this property, you can access it in the didInsertElement handler like this.
var controller = this.get('controller');
-33158914 0 case-esac; syntax error: newline unexpected (expecting ")") I'm getting crazy for an easy case but can't find what I missing. they told me the next error:
name.sh: 21: name.sh: syntax error: newline unexpected (expecting ")") my code is that one (the error is the line of the case):
#!/bin/bash while true do clear echo "________________________________________________________" echo "1) Encontraren el disco ficheros que contengan un patrón" echo "2) Tamaño de un directorio y su contenido" echo "3) Exit" echo "________________________________________________________" echo -e "\n" echo -e "Introduce una opción (1/2/3): \c" read answer case "$answer" in 1) ls ;; 2) cal ;; 3) exit ;; esac echo -e "pressiona enter per continuar \n" read input done
-38012171 0 sodawillow provided a valid answer. Howevery, you can simplify this using -notin:
if ($SER -notin 'Y', 'N') { Write-Host "ERROR: Wrong value for services restart" -ForegroundColor Red }
-9832772 0 Calling strtotime("4pm") will give you the time for today at 4pm. If it's already past 4pm, you can just add 60*60*24 to the given timestamp
// Example blatantly copied from AndrewR, but it uses strtotime $nextfourpm = strtotime("4pm"); if ($nextfourpm < time()) { $nextfourpm += 60*60*24; }
-39272813 0 If you run jhipster project with default elasticsearch configuration then be sure that your elasticsearh server version is 1.7 because jhipster java project works with this version(in production profile)
In development profile there was such a problem which I couldn't solve yet
-18006262 0I'm assuming that the version of mongo listed in phpinfo is 1.2 -- MongoClient class wasn't out until v1.3
if so, you need to update mongodb to the newer version.
https://bugs.launchpad.net/ubuntu/+source/php-mongo/+bug/1096587
-14655974 0my $newvar = $text =~ m/ quick (.*) dog /; is an assignment in scalar context, and assigns either 1 or undef.
You want to make this assignment in list context
my ($newvar) = $text =~ m/ quick (.*) dog /; which assigns the captured groups from the regular expression.
The difference between scalar and list contexts is one of the trickiest things to get used to in Perl.
Note that captured groups from regular expressions in Perl also get assigned to the special variables $1, $2, ... . So you also could just have said
print "$1\n";
-37973299 0 Strings in python are declared using double or single quotes, therefore the variable data contains a string. You can check the type of a variable directly in python:
data = "000000000000000117c80378b8da0e33559b5997f2ad55e2f7d18ec1975b9717" type(data) which outputs
str meaning that the variable is a string. When you call the function decode('hex') on a string you obtain another string:
data.decode('hex') '\x00\x00\x00\x00\x00\x00\x00\x01\x17\xc8\x03x\xb8\xda\x0e3U\x9bY\x97\xf2\xadU\xe2\xf7\xd1\x8e\xc1\x97[\x97\x17' Every character in your original string is interpreted as an hexadecimal number, and every pairs of hexadecimal numbers - e.s. "17" - is converted into an hexadecimal character using the escape sequence \x - becoming "\x17".
When you write "\x41" you are basically telling python to interpret 41 as a single ASCII character whose hexadecimal representation is 41.
The ASCII table contains the hexadecimal, decimal and octal values associated to the ascii characters.
If you try for example
"48454C4C4F".decode('hex') you obtain the string "HELLO"
Lastly when you use [::-1] on a string you reverse it:
"48454C4C4F".decode('hex')[::-1] produces the string "OLLEH"
You can find more about the escape characters reading the python documentation.
-24471126 0 How to track if location services is enabled or not enabled? titaniumI am able to turn it off.
code:
//get current Location // Titanium.Geolocation.accuracy = Titanium.Geolocation.ACCURACY_BEST; Titanium.Geolocation.distanceFilter = .25; var overlays = require('overlays'); //check if gps is enabled exports.checkGPS = function(windowCur) { Ti.Geolocation.accuracy = Titanium.Geolocation.ACCURACY_BEST; // make the API call var wrapperW = overlays.wrapperOverlay(windowCur); Ti.Geolocation.getCurrentPosition(function(e) { // do this stuff when you have a position, OR an error if (e.error) { Ti.API.error('geo - current position' + e.error); //put overlay on overlays.GPSError(windowCur); return; }else{ //alert(JSON.stringify(windowCur)); wrapperW.hide(); } }); }; This works fine at getting whether the user has turned on or off their location services. An overlay is put on the screen informing the user they need to turn it on, if they have turned it off.
However the problem is after the user has set it, and then goes into settings -> location services and enabled it, I am unable to take the overlay off as I have know way off tracking in real time if it has been turned on or off.
Does anyone know how this can be achieved, cheers.
UPDATE:
This did the trick
var wrapperW = null; Titanium.Geolocation.addEventListener('location', function(e) { if (e.error) { //put overlay on wrapperW = overlays.GPSError($.win); } else { //keep updating Ti.API.info(e.coords); if (wrapperW != null) { wrapperW.hide(); } } });
-14494070 0 How to resolve java.net.SocketException Permission Denied error? I have already included the Internet Permissions in the andoird manifest page, still the error seems to persist. I am also recieveing an unknown host excption in the similar code. Kindly guide me through! Ty! :)
package name.id; import android.app.Activity; import android.content.DialogInterface.OnClickListener; import android.os.Bundle; import org.ksoap2.*; import org.ksoap2.serialization.*; import org.ksoap2.transport.*; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class FirstPage extends Activity implements android.view.View.OnClickListener { /** Called when the activity is first created. */ TextView tv; Button bu; EditText et; private static final String SOAP_ACTION="http://lthed.com/GetFullNamefromUserID"; private static final String METHOD_NAME="GetFullNamefromUserID"; private static final String NAMESPACE="http://lthed.com"; private static final String URL="http://vpwdvws09/services/DirectoryService.asmx"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); et=(EditText) findViewById(R.id.editText1); tv=(TextView) findViewById(R.id.textView2); bu=(Button) findViewById(R.id.button1); bu.setOnClickListener((android.view.View.OnClickListener) this); tv.setText(""); } public void onClick(View v) { // creating the soap request and all its paramaters SoapObject request= new SoapObject(NAMESPACE, METHOD_NAME); //request.addProperty("ID","89385815");// hardcoding some random value //we can also take in a value in a var and pass it there //set soap envelope,set to dotnet and set output SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); soapEnvelope.dotNet=true; soapEnvelope.setOutputSoapObject(request); HttpTransportSE obj = new HttpTransportSE(URL); //to make call to server try { obj.call(SOAP_ACTION,soapEnvelope);// in out parameter SoapPrimitive resultString=(SoapPrimitive)soapEnvelope.getResponse(); //soapObject or soapString tv.setText("Status : " + resultString); } catch(Exception e) { tv.setText("Error : " + e.toString()); //e.printStackTrace(); } } }
-11797898 0 The AOT can be found in the development workspace. To open the development workspace, use Ctrl + Shift + W. To open the AOT, use Ctrl + D.
-5125210 0Let me start with this: I don't think a Python script is the best tool for the job. If you want to do enterprise-level management of updates (e.g., for all machines on a network), then you should seriously consider using the existing MS tools.
With that said, here is how you might go about this:
Have a look at the windows-update tag on ServerFault, one of StackOverflow's sister sites: http://serverfault.com/questions/tagged/windows-update . A lot of the questions seem to cover command-line control of the update process. Keep in mind that the command line tools vary significantly between e.g. Windows XP on the one hand and Vista/7 on the other. With some luck, you should be able to use windows built-in commands rather than going to the windows update website programmatically.
Assuming you find the command-line incantations that you need: Use the subprocess module to call to the shell and execute those commands programmatically. Because you're using python, you may need to spend quite a bit of time parsing the command outputs to figure out how your shell calls are doing.
Hope that helps. I realize this is a rather high-level answer, but as it stands, the question is not very specific about what exactly you want to accomplish and why you're using python to do it.
-27747889 0As per your error messages:
01-03 00:25:57.443 2371-2387/com.example.androidhive E/JSON Parser﹕ Error parsing data org.json.JSONException: Value <br><table of type java.lang.String cannot be converted to JSONObject
<br><table is NOT JSON. E.g. your fetched data is html, not json. Since it's not JSON, the json parser barfs, and here we are...
I'd like to add a fadeout to the tabs on my page here, if someone could help with the javascript side?
Here's the html:
<ul class="tabs clearfix"> <li class="aboutustab active" style="border-left:1px solid #ccc;"><div class="up"></div>About</li> <li class="maptab"><div class="up"></div>Map</li> <li class="featurestab"><div class="up"></div>Features</li> <li class="voucherstab"><div class="up"></div>Offers</li> </ul> And the here's the javascript:
$(window).load(function(){ $('.tab:not(.aboutus)').hide(); $('.tabs li').click(function(){ var thisAd = $(this).parent().parent(); $(thisAd).children('.tab').hide(); $(thisAd).children('.'+$(this).attr('class').replace('tab','')).show(); $('.tabs li').removeClass('active'); $(this).addClass('active'); }); if(window.location.hash) { if (window.location.hash == "#map") { $(".Advert").children('.tab').hide(); $(".Advert").children('.map').show(); $('.tabs li').removeClass('active'); $('.maptab').addClass('active'); } if (window.location.hash == "#voucher") { $(".Advert").children('.tab').hide(); $(".Advert").children('.vouchers').show(); } } }); I have the bootstrap.js plugin from here and would like to use that, if anyone was familiar with that it'd be ideal.
Here's how I would like it to work.
Update: This is what I have now, but the fade effect is different for each tab almost - I like the transition back to the About Us tab which isn't as "heavy" as the transition of the others. The offers tab is leaving remnants of the 'Features' tab content too.
$(window).load(function(){ $('.tab:not(.aboutus)').fadeOut(); $('.tabs li').click(function(){ var thisAd = $(this).parent().parent(); $(thisAd).children('.tab').fadeOut(); $(thisAd).children('.'+$(this).attr('class').replace('tab','')).fadeIn(); $('.tabs li').removeClass('active'); $(this).addClass('active'); }); newContent.hide(); currentContent.fadeOut(750, function() { newContent.fadeIn(500); currentContent.removeClass('current-content'); newContent.addClass('current-content'); }); if(window.location.hash) { if (window.location.hash == "#map") { $(".Advert").children('.tab').fadeOut(750); $(".Advert").children('.map').fadeIn(500); $('.tabs li').removeClass('active'); $('.maptab').addClass('active'); } if (window.location.hash == "#voucher") { $(".Advert").children('.tab').fadeOut(750); $(".Advert").children('.vouchers').fadeIn(500); } } });
-31193716 0 UITabBarController - transition from one tab's navigation stack to a view controller of another tab's navigation stack Novice iOS developer here. I am making a simple tabbed chat application in Swift using a UITabBarController. For simplicity, let's assume the application only has two tabs, "Contacts" and "Chats". Each of the two tabs has a navigation controller.
The "Chats" navigation stack begins with a UITableViewController called "ChatsTableViewController" which lists the user's chats. When the user selects a chat, the app segues to a MessagesViewController which displays the messages for the selected chat.
The "Contacts" navigation stack includes a UITableViewController which lists the user's contacts. Upon selecting a contact, another view controller is presented modally, asking the user whether they would like to begin a chat with the selected contact, and giving them the option to cancel. If the user chooses to begin a chat, I would like to transition from this modal view controller to the MessagesViewController of the "Chats" tab, passing the information necessary to display the chat (which I have at the ready in the modal view controller).
When the MessagesViewController loads, regardless of whether we get to it by selecting a chat from the "Chats" tab or by creating a new chat from the "Contacts" tab, it should have a navigation bar at the top with a "Back" button that takes the user to the ChatsTableViewController.
I have done a good deal of searching, but have not found any solutions that fit what I need. Any suggestions would be greatly appreciated! Here is a summary of what I am looking for.
EDIT: I've found that you can easily switch tabs programmatically using self.tabBarController?.selectedIndex = index_of_tab_to_switch_to, however, this takes me to the first view of the tab and I am still unsure of how I can pass data. Any thoughts on how I can proceed?
The answer to this is to use intermediate layouts.
[self.collectionView setCollectionViewLayout: layoutForStepOne animated:YES completion:^(BOOL finished) { [self.collectionView setCollectionViewLayout: layoutForStepTwo animated:YES completion:^(BOOL finished) { [self.collectionView setCollectionViewLayout: layoutForStepThree animated:YES]; }]; }];
-29865487 0 Drawing to the background I'm creating a website that lets the user draw to the background with a color he chooses. I also want to let the user to change the background color with a hex color picker tool.
The latter is easy but how can I let the user draw to the background? Is it possible to use canvas as the background?
Should I create the whole background entire of small divs which color I would change when the user is drawing?
-1255891 0Maybe it won't be a full answer to your question, but here's what I've been able to find so far : there is some kind of a partial answer in the book "Extending and Embedding PHP", written by Sara Golemon (amazon ; some parts are also available on google books).
The relevant part (a note at the top of page 56) is :
Ever wonder why some extensions are configured using
--enable-extnameand some are configured using--with-extename? Functionnaly, there is no difference between the two. In practice, however,--enableis meant for features that can be turned on witout requiring any third-party libraries.--with, by contrast, is meant for features that do have such prerequisites.
So, not a single word about performance (I guess, if there is a difference, it is only a matter of "loading one more file" vs "loading one bigger file") ; but there is a technical reason behind this possibility.
I guess this is done so PHP itself doesn't require an additionnal external library because of some extension ; using the right option allows for users to enable or disable the extension themselves, depending on whether or not they already have that external library.
-4471371 0This has nothing to do with calling revalidate as recommended by another and likely has all to do with calling a method on the wrong object. In your showEmployeesActionPerformed method you create a new Company object, one that is not visualized. The key is to call this method on the proper reference, on the visualized GUI. You do this by passing a reference to the visualized GUI object into the class that is wanting to call methods on it. This can be done via a setCompany method:
setCompany(Company company) { this.company = company); } or via a constructor parameter.
-33745943 0You can not to use prepare result without check.
It able to return false if any error occured.
if ($resolve = $data_base->prepare("INSERT INTO links VALUES('',?,?)")) { $resolve->bind_param("ss",$link, $short); // Problematic frame $resolve->execute(); } else { // You can get error message here printf("Error: %s.<br/>\n", $resolve->error); // assumed this is mysqli $resolve->close(); } May be you get sql syntax error, about your insert query should be like this:
INSERT INTO links (long_url, title) VALUES (?, ?);
-10545891 0 It appears that you are using this database migration solely for populating the data.
Database migrations are meant for changing the database schema, not for populating the database (though you can add some logic to populate the database after the change; for example, if you add a column - role to users table, you can add some custom logic to populate the newly added field for existing entries in users table). Refer to rails api - migrations for details.
If you forgot add the code to populate the database in your previous database migration, you can undo the previous migration and apply it again using:
rake db:rollback ... Edit the previous migration ..Add the code to populate rake db:migrate If you just want to populate the database, you should seed the database instead. Watch this railscast for more information.
EDIT: To seed the database:
Create a file called db/seeds.rb
Add the record creation code like this:
['Sampath', 'Suresh'].each do |name| User.create(role: 'admin', username: name) end Then,
rake db:seed This will read the seeds.rb and populate the database.
-34245177 0What you are looking for is called
Structural Search/Replace.It is not very well documented but it is Extremely Powerful once you grok it completely.
There are a few examples in the
Existing Templatesthat you can probably modify and learn from, the following will do what you are asking for now.
Go to the Menu: Edit -> Find -> Replace Structurally and use the following Search Template.
System.out.println($EXPRESSION$); Check Case Sensitive and make File Type = Java Source
Set the Scope of the search to Project Files for everything.
If you want to just remove it all you can just make sure the Replace Template field is blank.
You could comment them all out with a Replace Template of //System.out.println($EXPRESSION$); or /* System.out.println($EXPRESSION$); */
Use the
Structural Search/Replaceto addprivate static final Logger L = LoggingFactory($Class$.class);to all the classes with theSystem.out.println()statements.
Then replace all the System.out.println($EXPRESSION$); with L.info($EXPRESSION$);
You can even do things sophisticated things like the following:
This is just an example idea, the body of the catch needs to only have the the System.out.println($EXPRESSION$) a more sophisticated block to grab other expressions and keep them would be an exercise for the reader.
try { $TryStatement$; } catch($ExceptionType$ $ExceptionRef$) { System.out.println($EXPRESSION$); } with
try { $TryStatement$; } catch($ExceptionType$ $ExceptionRef$) { L.error($EXPRESSION$); } -30654711 0Always use a
Loggerinstead ofSystem.out.println()in everything. Even inscratchclasses used for experimenting, they eventually end up in production code at some point!
In the original view controller add a IBAction that you want to handle the call back.
In IB Control Drag from the cell to the Exit icon at the top of the view. On release you will see a a pop up menu with the name of available IBAction methods. Choose your IBAction method.
I don't remember wether if you add a sender variable to the IBAction, you can retrieve info from it.
-11566824 0this is a problem with the lastest versions of Firefox and not your code. I have half a dozen sites that are not properly rendering css in firefox at this time. they were all fine not more than a week ago and no change to the code or codebase was made. the styles still work in other browsers.
Firefox is having issues on thier current release of the browser and I am sure they are all aware of it, but really, if it does not get fixed soon, they will loose even more market share. which would be a shame really.
-2210564 0There is no way that this can happen. More often we think that there is bug in the language when we are sure that, we haven't done any thing wrong. But there is always some thing silly in the code. You must check the code again.
-21565167 0You must show not metadata but materials array, blender exporter doesn't save texture by default if it missed in materials then try 2-2 from this tutorial.
-34738403 0cherlietfl is right.
The problem is that you break the reference to the messages array since you assign a new array to messages inside your get function. But concat is doing this as well.
Try this:
Restangular.all('/api/messages/').getList({'_id': userId}).then(function(docs){ messages.splice(0, messages.length); // clear the array messages.push.apply(messages, docs); //add the new content });
-19451800 0 SVN resolve tree conflict in merge I have an SVN merge tree conflict that i can't figure out how to resolve and i'm hoping you guys(girls) can help out.
Here's the situation: i created a branch A from trunk to do some development. Then i created a branch B, from branch A. Both branches are evolving concurrently.
At some point i cherry-picked some revisions from branch B into trunk to get some features developed in branch B.
Now, i synced branch A with trunk:
~/branch_a$ svn merge ^/trunk ~/branch_a$ svn commit No problems here. Next step is to sync B with A:
~/branch_b$ svn merge ^/trunk Here i get some tree conflicts, in files/dirs that already existed in trunk before the merge but were changed in the cherry-picks i did earlier (don't know if it has anything to do with it, i'm just mentioning it):
C some_dir/other_dir/some_file.php > local add, incoming add upon merge C some_other_dir/some_sub_dir > local add, incoming add upon merge Essentially i want the versions of the files that are coming in from the merge and discard the current version. What's the best way to solve this?
Thanks in advance!
-2079615 0 Seeking good practice advice: multisite in DrupalI'm using multisite to host my client sites.
During development stage, I use subdomain to host the staging site, e.g. client1.mydomain.com.
And here's how it look under the SITES folder:
/sites/client1.mydomain.com When the site is completed and ready to go live, I created another folder for the actual domain, e.g. client1.com. Hence:
/sites/client1.com Next, I created symlinks under client1.com for FILES and SETTINGS.PHP that points to the subdomain
i.e.
/sites/client1.com/settings.php --> /sites/client1.mydomain.com/settings.php /sites/client1.com/files --> /sites/client1.mydomain.com/files Finally, to prevent Google from indexing both the subdomain and actual domain, I created the rule in .htaccess to rewrite client1.mydomain.com to client1.com, therefore, should anyone try to access the subdomain, he will be redirected to the actual domain.
This above arrangement works perfectly fine. But I somehow feel there is a better way to achieve the above in much simplified manner. Please feel free to share your views and all advice is much appreciated.
-33525605 0This type of player is connected via Media Transfer Protocol (MTP) Looks like you need PyMTP Good luck.
-32068097 0This does not explain why your method stops so soon, but you need to take care of it or you will have an even stranger problem with the result data being completely garbled.
From the APi doc of DataInputStream.read():
Reads some number of bytes from the contained input stream and stores them into the buffer array b. The number of bytes actually read is returned as an integer.
You need to use that return value and call the write() method that takes and offset and length.
-22904893 0You can not declare objects at runtime they way you art trying. You can store the week days in array / List<T> starting Monday at index 0 and Sunday at index 6, You can give id of element with the string name you want.
List<TextBox> weekList = new List<TextBox>(); weekList.Add(new TextBox()); weekList[0].ID = "txt" + ViewState["temp"].ToString();
-21200703 0 try this, use-
Intent intent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI); then, in your onAcitivityResult:
Uri contact = data.getData(); ContentResolver cr = getContentResolver(); Cursor c = managedQuery(contact, null, null, null, null); // c.moveToFirst(); while(c.moveToNext()){ String id = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID)); String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); if (Integer.parseInt(c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) { Cursor pCur = cr.query(Phone.CONTENT_URI,null,Phone.CONTACT_ID +" = ?", new String[]{id}, null); while(pCur.moveToNext()){ String phone = pCur.getString(pCur.getColumnIndex(Phone.NUMBER)); textview.setText(name+" Added " + phone); } } } You can also check this link for more help- How to call Android contacts list?
-12645201 0When the page is done loading, intercept the links :
Dim olink As HtmlElement Dim olinks As HtmlElementCollection = WB1.Document.Links For Each olink In olinks olink.AttachEventHandler("onclick", AddressOf LinkClicked) Next Then add a function :
Private Sub LinkClicked(ByVal sender As Object, ByVal e As EventArgs) If txtAddress.Enabled = True Then Dim link As HtmlElement = WB1.Document.ActiveElement Dim url As String = link.GetAttribute("href") MsgBox("Link Clicked: " & link.InnerText & vbCrLf & "Destination: " & url) WB1.Navigate(url, False) End If End Sub
-11429875 0 Here is an example which works well:
C:\Program Files\WinRAR>rar a -hpabc h:\abc.rar c:\pdf So you can follow the example in your codes.
p.StartInfo.Arguments = String.Format("a -hp{0} {1} {2}", your password, Destination, SourceFile); p.Start();
-119346 0 It's just personal preference really, and has to do with the layout of your python modules.
Let's say you have a module called erikutils. There are two ways that it can be a module, either you have a file called erikutils.py on your sys.path or you have a directory called erikutils on your sys.path with an empty __init__.py file inside it. Then let's say you have a bunch of modules called fileutils, procutils, parseutils and you want those to be sub-modules under erikutils. So you make some .py files called fileutils.py, procutils.py, and parseutils.py:
erikutils __init__.py fileutils.py procutils.py parseutils.py Maybe you have a few functions that just don't belong in the fileutils, procutils, or parseutils modules. And let's say you don't feel like creating a new module called miscutils. AND, you'd like to be able to call the function like so:
erikutils.foo() erikutils.bar() rather than doing
erikutils.miscutils.foo() erikutils.miscutils.bar() So because the erikutils module is a directory, not a file, we have to define it's functions inside the __init__.py file.
In django, the best example I can think of is django.db.models.fields. ALL the django *Field classes are defined in the __init__.py file in the django/db/models/fields directory. I guess they did this because they didn't want to cram everything into a hypothetical django/db/models/fields.py model, so they split it out into a few submodules (related.py, files.py, for example) and they stuck the made *Field definitions in the fields module itself (hence, __init__.py).
For someone directed here from google :
If your JRE crashes after you run the java tutorials then most probably you have the python Bindings installed as well (cv2.so) . You will have to re-make OpenCV without those bindings
cmake -DBUILD_SHARED_LIBS=OFF -D BUILD_NEW_PYTHON_SUPPORT=NO
That solved the problem for me.
-14439127 0Save them as UTC time and then convert them to local time when loading to the UI.
-6803195 0For those who installed direct from the official installer, just adding the host to the command works with no path changes:
psql -h localhost -U postgres
-24045905 0 To do that you need a third table which contains EmployeeID and ProjectID. Mark both IDs as primary key. You have to do a double join if you want to select them though but it's the best way to handle it.
-416124 0While it is not free (but $39), FireDaemon has worked so well for me I have to recommend it. It will run your batch file but has loads of additional and very useful functionality such as scheduling, service up monitoring, GUI or XML based install of services, dependencies, environmental variables and log management.
I started out using FireDaemon to launch JBoss application servers (run.bat) but shortly after realized that the richness of the FireDaemon configuration abilities allowed me to ditch the batch file and recreate the intent of its commands in the FireDaemon service definition.
There's also a SUPER FireDaemon called Trinity which you might want to look at if you have a large number of Windows servers on which to manage this service (or technically, any service).
-28890234 0 Ant ReplaceRegExp task changing a line it shouldn'tI was updating an xml file with a version/build number. It was working just fine but then a developer put in some new lines of code and for some reason one of those lines gets changed. Here is my regex:
`<replaceregexp file="${basedir}Monitors\Invos\Trunk\InvosWPF\InvosSettings.xml" match="<ConfigurationVersion value=\"[0-9.]* " replace="<ConfigurationVersion value=\"${ver_bldnum}" byline="false"/>` Its messing with ChannelLabel2 value. Before the regex: <ChannelLabels> <ChannelLabel0 value="L"/> <ChannelLabel1 value="R"/> <ChannelLabel2 value="Sâ‚"/> <ChannelLabel3 value="Sâ‚‚"/> </ChannelLabels>
After the regex: <ChannelLabels> <ChannelLabel0 value="L"/> <ChannelLabel1 value="R"/> <ChannelLabel2 value="Sâ‚?"/> <ChannelLabel3 value="Sâ‚‚"/> </ChannelLabels>
Its inserting a ? for some reason. The only line I want it to change is:
`<ConfigurationVersion value="1.0.0.92" />` Thanks for any help or suggestions.
-14874445 0 Is the Monolithic God object in Javascript a performance concern?I have recently joined a webapp project which maintains, as a matter of standard, one single globally-available (ie, itself a property of window) object which contains, as properties or recursive sub-properties, all the functions and variables necessary to run the application — including stateful indicators for all the widgets, initialization aliases, generic DOM manipulation methods — everything. I would try to illustrate with simplified pseudo-code, but that defeats the point of my concern, which is that this thing is cyclopean. Basically nothing is encapsulated: everything single granular component can be read or modified from anywhere.
In my recent work I've been the senior or only Javascript developer so I've been able to write in a style that uses functions, often immediately invoked / self-executing, for scoping discreet code blocks and keeping granular primitives as variables within those scopes. Using this pattern, everything is locked to its execution scope by default, and occasionally a few judiciously chosen getter/setter functions will be returned in cases where an API needs to be exposed.
Refactoring the code to functional parity from style A to style B is a gargantuan task, so I can't make any meaningful practical test for my assertion, but is the Monolithic God object anti-pattern a known performance monster compared to the scoped functional style? I would argue for B for the sake of legibility, code safety, and separation of concerns... But I imagine keeping everything in memory all the time, crawling though lookup chains etc would make it either an inherently performance-intensive exercise to access anything, or at least make garbage collection a very difficult task.
-27723933 0 Opcache + Memcached Togethermy environment
ubuntu 14.04 , php 5.5 , nginx 1.76
i am using both opcache and xcache concurrently
PHP 5.5.19-1+deb.sury.org~trusty+1 (cli) (built: Nov 19 2014 19:33:43) Copyright (c) 1997-2014 The PHP Group Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies can i use both opcache and memchached together .. i dont know whether this allowed or not ?
suggestions invited ? ?
-511899 0Check to see how fragmented your indexes are. At my company we have a nightly import process that trashes our indexes and over time it can have a profound impact on data access speeds. For example we had a SQL procedure that took 2 hours to run one day after de-fragmenting the indexes it took 3 minutes. we use SQL Server 2005 ill look for a script that can check this on MySQL.
Update: Check out this link: http://dev.mysql.com/doc/refman/5.0/en/innodb-file-defragmenting.html
-10030375 0If the date_promised field is of a DATETIME type you can use -
SELECT date_promised, DATE_FORMAT(date_promised, '%m/%d/%Y') AS date_promised2 FROM erp_workorder AS t1 WHERE id_primary = 73135; If the date_promised field contains a unix timestamp you can use -
SELECT date_promised, DATE_FORMAT(FROM_UNIXTIME(date_promised), '%m/%d/%Y') AS date_promised2 FROM erp_workorder AS t1 WHERE id_primary = 73135;
-21814004 0 If you want to send an SMS, in about 5 lines of code, you should look into Twilio. Incredibly easy to get started, only pay for what you use, nicely document rest api and best of all its is a proven/mature technology.
-32480591 0In Python 3.5, the async for syntax is introduced. However, asynchronous iterator function syntax is still absent (i.e. yield is prohibited in async functions). Here's a workaround:
import asyncio import inspect class escape(object): def __init__(self, value): self.value = value class _asynciter(object): def __init__(self, iterator): self.itr = iterator async def __aiter__(self): return self async def __anext__(self): try: yielded = next(self.itr) while inspect.isawaitable(yielded): try: result = await yielded except Exception as e: yielded = self.itr.throw(e) else: yielded = self.itr.send(result) else: if isinstance(yielded, escape): return yielded.value else: return yielded except StopIteration: raise StopAsyncIteration def asynciter(f): return lambda *arg, **kwarg: _asynciter(f(*arg, **kwarg)) Then your code could be written as:
@asynciter def countdown(n): while n > 0: yield from asyncio.sleep(1) #or: #yield asyncio.sleep(1) n = n - 1 yield n async def do_work(): async for n in countdown(5): print(n) asyncio.get_event_loop().run_until_complete(do_work()) To learn about the new syntax, and how this code works, see PEP 492
-39621578 1 Match multiple times a group in a stringi'am trying to use regular expression. I have this string that has to be matched
influences = {{hlist |[[Plato]] |[[Aristotle]] |[[Socrates]] |[[David Hume]] |[[Adam Smith]] |[[Cicero]] |[[John Locke]]}} {{hlist |[[Saint Augustine]] |[[Saint Thomas Aquinas]] |[[Saint Thomas More]] |[[Richard Hooker]] |[[Edward Coke]]}} {{hlist |[[Thomas Hobbes]] |[[Rene Descartes]] |[[Montesquieu]] |[[Joshua Reynolds]] |[[Sir William Blackstone|William Blackstone]]}} {{hlist |[[Niccolo Machiavelli]] |[[Dante Alighieri]] |[[Samuel Johnson]] |[[Voltaire]] |[[Jean Jacques Rousseau]] |[[Jeremy Bentham]]}} I would like to extract from the text the following templates:
{{hlist .... }} Instead, the following text has not to be matched:
main_interests = {{hlist |[[Music]] |[[Art]] |[[Theatre]] |[[Literature]]}} I wrote this regex but it doesn't work
(?:^\|\s*)?(?:influences)\s*?=\s*?(?:(?:\s*\{\{hlist)\s*\|([\d\w\s\-()*—&;\[\]|#%.<>·:/",\'!{}=•?’ á~ü°œéö$àèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇߨøÅ寿œ]*?)(?=\n))+ I'm using python.
-4377999 0 Mapping vs compositionIf I have two classes with a one-to-one relationship, when's a good time to use mapping.
class A { ... } class B { ... } class C { Map<A,B> a2b; } And when's a good time to use composition?
class A { B myB; } class B { ... } Would the answer change if the relationship was one-to-many and many-to-many?
-6984033 0 Trying to print multiple result set .But list returns only objectThis my query which i am trying get result from multiple table.
SQLQuery query = session.createSQLQuery("select t.id as ID, t.companyname as COMPANYNAME, e.fullname as FULLNAME, e.empid as EMPID, ca.dateallocated as DATEALLOCATED from bw_tempclientdetails t, bw_employee_details e, bw_clientallocation ca where e.empid=ca.empid and ca.companyname=t.companyname "); But query.list returns only object in which i am unable to convert to string representation. Any solution?
-35289597 0 Excel 2010 Cell Validation - Grouped ListIs it possible (without the use of user forms, or form controls) to have a grouped validation list in-cell, where the group title cannot be selected. So for example:
Fruit
Apple
Banana
Veg
Potato
Carrot
I feel like I've been searching for an absolute age now, and I'm getting no where fast. The reason I cannot use form controls as that there are 8 sheets, each with a few thousand rows (possible) and each entry must have this selection. I have done this before with dependant lists across multiple columns but I'd like to trim everything down.
Any ideas? I don't want a clear cut solution if one exists, just a nudge in the right direction. Any help appreciated.
-29221582 0 laravel 4.2 liebig package work on localhost but fail in server cron job commandi want to fire some function to get news about football from rss i used laravel4.2 https://github.com/liebig/cron as that
Event::listen('cron.collectJobs', function() { Cron::add('football', '* * * * *', function() { //the controller of function $news=new News_feedController(); $news->football(); return 'success'; }); }); $report = Cron::run(); it work correctly when i use cmd
php artisan cron:run
in my computer but when use the server cron job command
- /usr/bin/php /home/public_html/interestoo.com/artisan cron:run
i don't find any change in
cron_job
table but find data in
cron_manager
table and the cron job function did not work i'm sure that the path
/home/sfathy/public_html/interestoo.com/
in command is true and does not find any reason for that problem any help please.
-28691842 0Try this :
DateTime SelectedDate = MyDatePicker.Date.Date;
-21290403 0 WebSockets and HTTPS load balancers I cannot find authoritative information about how WSS interacts with HTTPS proxies and load balancers.
I have a load balancer that handles the SSL (SSL off-loading), and two web servers that contains my web applications and handle the requests in plain HTTP. Therefore, the customers issue HTTPS requests, but my web servers get HTTP requests, since the load balancer takes care of the SSL certificates handling.
I am developing now an application that will expose WebSockets and SSL is required. But I have no clear idea about what will happen when the load balancer gets a secure HTTPS handshake for WSS.
Will it just relay the request as normal handshake to the web server? WebSockets use a "Upgrade:WebSocket" HTTP header that is only valid for the first hop (as there is also "Connection:Upgrade", will this be a problem?
Cheers.
-24173779 0I think the third sql statement should be:
INSERT INTO [project_manager] (project_id, manager_id) SELECT project_id, @ID FROM [projects] WHERE project_name = @Name
-1821748 0Probably the simplest way to do that is to find out exactly what imagefile jQuery is using for the icons, and then modify that image file (or create your own) and drop it into place.
-15511511 0 How to use on the same content box 2 columns of vertical tabs?How can I create a new column which is identical to the first column, and have it display one column to the right?
I want the new column to have the same properties as the first column because I want to add more things to this tabs and only on 1 column they are ugly.
Here is what I have tried: http://jsfiddle.net/26zQS/6/
<div class="verticalslider" id="textExample"> <ul class="verticalslider_tabs"> <li><a href="#">Catedra de Limba si Literatura Romana</a></li> <li><a href="#">Catedra de Matematica</a></li> <li><a href="#">Catedra de Informatica</a></li> <li><a href="#">Limba engleza</a></li> <li><a href="#">Limba Germana</a></li> </ul> <ul class="verticalslider_contents"> <li> <h2>Catedra de Limba si Literatura Romana</h2></br> <p id="profesor"> Popa Alina </br> Nadia Pascu</br> </p> </li> <li> <h2>Catedra de Matematica</h2></br> <p id="profesor"> Ciubotariu Boer-Vlad </br> Diaconu Ilie</br> Gorcea Violin </br> </p> </li> <li> <h2>informatica</h2> <p id="profesor"> Wainblat Gabriela</br> Nistor Ancuta</br> </li> <li> <h2>Limba Engleza</h2> <p id="profesor"> Wainblat Gabriela</br> Nistor Ancuta</br> </li> <li> <h2>Germana</h2> <p id="profesor"> Wainblat Gabriela</br> Nistor Ancuta</br> </li> </ul> </div>
-1266807 0 I've come across this myself before. Adobe's documentation on Traversing XML structures isn't exactly clear on the point.
Their documentation states that if there is more than one element with a particular name you have to use array index notation to access it:
var testXML:XML = <base> <book>foo</book> <book>bar</book> </base> var firstBook:XML = testXML.book[0]; Then it goes on to say that if there is only one element with a particular name then you can omit the array index notation:
var testXML:XML = <base> <book>foo</book> </base> var firstBook:XML = testXML.book; This means that when you try and force coercion to an Array type it doesn't work since it sees the single element as an XMLNode and not an XMLList.
If you are lucky you can just check the number of children on your <my_claims> node and decide if you want to warp the single element in an ArrayCollection or if you can use the automatic coercion to work for multiple elements.
Quoting from RegEx match open tags except XHTML self-contained tags :
You can't parse [X]HTML with regex. Because HTML can't be parsed by regex. Regex is not a tool that can be used to correctly parse HTML. [...] Regular expressions are a tool that is insufficiently sophisticated to understand the constructs employed by HTML. HTML is not a regular language and hence cannot be parsed by regular expressions. Regex queries are not equipped to break down HTML into its meaningful parts.
The conclusion I case was the same as the author:
Have you tried using an[sic] XML parser instead?
Which is what you can do!
Try this:
var fragment = document.createDocumentFragment(); var elem = document.createElement('div'); fragment.appendChild(elem); elem.innerHTML = '<svg viewBox="0 0 120 120" version="1.1" xmlns="http://www.w3.org/2000/svg"><circle cx="60" cy="60" r="50"/></svg>'; alert(elem.getElementsByTagName('circle')[0].getAttribute('cx')); It should alert 60.
Javascript provides all the tools to mess with this. Just pretend that the string is HTML and you should be fine!
Note: that code is just an example! Addapting it to work properly is easily done in 5 minutes or less.
-31804966 0 Running NodeJs http-server forever with PM2My question is about running HTTP-server in combination with PM2.
The problem i face is that:
So i tried the following (note the double dash which should pass the parameters to the HTTP-server script:
/node_modules/http-server/lib$ pm2 start http-server.js -- /home/unixuser/websiteroot -p8686 But it doesn't work.
I also tried:
http-server /home/unixuser/websiteroot -p8686 Which does work, but doesn't have the great support of pm2 ?
Any suggestions would be great, thanks!
-1308103 0There's already a browser-based system that uses keys to secure data transfer. It's called SSL.
-41023266 0 Is there an OData dependency graph somewhere?I'm following this guide to migrate an app I developed to an open framework. I get to the part where I'm supposed to install all the OData references. Specifically these:
Install-Package Angularjs Install-Package Microsoft.OData.Client Install-Package Microsoft.OData.Core Install-Package Microsoft.OData.Edm Install-Package Microsoft.Spatial Install-Package Microsoft.AspNet.OData Install-Package Microsoft.AspNet.WebApi.WebHost And these are the errors I get:
Unable to resolve dependencies. 'Microsoft.OData.Core 7.0.0' is not compatible with 'Microsoft.OData.Client 6.15.0 constraint: Microsoft.OData.Core (= 6.15.0)'. Unable to find a version of 'Microsoft.OData.Core' that is compatible with 'Microsoft.OData.Client 6.15.0 constraint: Microsoft.OData.Core (= 6.15.0)'. Unable to find a version of 'Microsoft.OData.Core' that is compatible with 'Microsoft.OData.Client 6.15.0 constraint: Microsoft.OData.Core (= 6.15.0)'. Unable to find a version of 'Microsoft.OData.Edm' that is compatible with 'Microsoft.OData.Core 6.15.0 constraint: Microsoft.OData.Edm (= 6.15.0)'. I started running my app over and over until it throws an exception and then adding a bingindRedirect to my Web.config to target the currently installed versions. But this doesn't seem right and will add a lot of maintenance later on. I know how to install old versions and nightly versions. But I have no idea which versions to install. Is there some place that tells me which versions work together correctly?
According to NuGet, I have version 6.15.0 of each installed. So why am I getting errors?
-3841110 0It's probably worth just testing if the following works:
SqlConnection con = new SqlConnection("Data Source=server;Initial Catalog=Invoicing;Persist Security Info=True;ID=id;Password=pw"); To me it looks like your connection string is probably not right - there's no user provided. I use the following connection string: "Data Source=ServerNameHere;Initial Catalog=DBNameHere;User ID=XXXX;Password=XXXX"
-26174400 0 RegEx - Extract Domain Name from multiple sub-domainsI'm trying to write a Java RegEx that will extract the domain name from a list of domains, sub-domains, and multi sub-domains.
There are too many domains to maintain with the RegEx I have written, and there is a lot more out there. https://publicsuffix.org/list/effective_tld_names.dat
What is a better way to capture the domain name? The goal is to remove the subdomain, extract the domain name so I can resolve or ping it.
This is the RegEx I have come up with
(\w*.(?:\.co|\.org|\.net|\.int|\.edu|\.gov|\.mil|\.arpa|\.tv|\.aero|\.asia).*) Here is a sample list I am testing against.
comnettest.google.com doubleclick.net googleapis.com imrworldwide.com bom.gov.au www.bom.gov.au googleapis.com www.google.com www.twiiter.com dynamic.t2.tiles.virtualearth.net domain.com 1-A.domain.com 1-A.2-B.domain.com 1-A.2-B.3-C.domain.com mt0.google.com twitch.tv stream.twitch.tv streamcom.com.au network.google.com
-14361227 0 This will do the trick:
if($_SERVER['REMOTE_ADDR'] === '127.0.0.1') { // do something } Be careful you don't rely on X_FORWARDED_FOR as this header can be easily (and accidentally) spoofed.
The correct way to do this would be to set an environmental variable in your server configuration and then check that. This will also allow you to toggle states between a local environment, staging and production.
-26578516 0You can use SASS or less for this. you have some variables and switch value on switching theme.
-38536136 0 Unique methods for use through the class rather than an objectSo, I'm beginning to learn Java and I think it's an awesome programming language, however I've come across the static keyword which, to my understanding, makes sure a given method or member variable is accessible through the class (e.g. MyClass.main()) rather than solely through the object (MyObject.main()). My question is, is it possible to make certain methods only accessible through the class and not through the object, so that MyClass.main() would work, however MyObject.main() would not? Whilst I'm not trying to achieve anything with this, I'd just like to know out of curiosity.
In my research I couldn't find this question being asked anywhere else, but if it is elsewhere I'd love to be pointed to it!
Forgive me if it's simple, however I've been thinking on this for a while and getting nowhere.
Thanks!
-23189974 0Your production environment has the short_open_tag setting disabled. For full compatibility its recommended that you do not turn it on and instance use the full php tag <?php instead of <?
Does this work?
def json = request.JSON try { def context = json.optJSONObject("context") userService.updateContext(context) }catch(e) { log.error json.toString() }
-22184715 0 There are two (or more) problems. The first: you are using typedef when you are trying to declare an array of structs. Don't. Instead of
typedef struct Symbles symbles_arr[MAX_SYMBOLS_ENTRIES_EXTERNALS]; use
struct Symbles symbles_arr[MAX_SYMBOLS_ENTRIES_EXTERNALS]; Notice that you now have the structure (not a pointer to the structure) - so when you want to access an element you need . not -> Thus:
symbles_arr[symbol_counter]->symbolName=*toCheck; needs to become
strcpy(symbles_arr[symbol_counter].symbolName, *toCheck); because you allocated space for the symbol name in the structure, and you can't just take that pointer and point it somewhere else.
Finally - you don't need to malloc space for toCheck since strtok actually returns a pointer to the original string (it doesn't make a copy). The side effect of this is that your input string (the one passed to strtok) becomes mangled in the process - after you're done using it, it has a lot of '\0' added.
There may be other problems, but this should get you on your way...
-28257088 0One way to go about it is to create a view with your basic logic:
CREATE VIEW myview AS SELECT * FROM mytable WHERE column_b = 'X' AND column_c = 'Y' Now, this logic can be reused:
SELECT * FROM myview WHERE column_a NOT IN (SELECT column_k FROM myview)
-30943140 0 By using add, you are effectively getting a calendar instance that is 2015 years, 6 months, 20 days, and 19 hours later than now. Instead use the constructor:
Calendar cal = new GregorianCalendar(2015, 5, 20, 19, 0); and do not call add.
Alternatively, you can use set instead of add:
cal.set(Calendar.YEAR, 2015); cal.set(Calendar.MONTH, 5); // 0-based cal.set(Calendar.DAY_OF_MONTH, 20); cal.set(Calendar.HOUR, 19); cal.set(Calendar.MINUTE, 0);
-33234754 0 Like adeneo said: dataType: 'array' is invalid and probably jquery will trigger the .fail() instead of .done().
https://api.jquery.com/deferred.fail/
-28912282 0 Trying to write "<<<" in kshI am having trouble with the code below:
IFS=: read c1 c2 c3 c4 rest <<< "$line" Don't get me wrong this code works good but it doesn't seem to be used for ksh. I basically need to write the same code without the "<<<". There is not much info on the "<<<" online. If anybody has any ideas it would be much appreciated.
EDIT:
Ok code is as follows for the entire portion of programming:
m|M) #Create Modify Message clear echo " Modify Record " echo -en '\n' echo -en '\n' while true do echo "What is the last name of the person you would like to modify:" read last_name if line=$(grep -i "^${last_name}:" "$2") then oldIFS=$IFS IFS=: set -- $line IFS=$oldIFS c1=$1 c2=$2 c3=$3 c4=$4 shift; shift; shift; shift rest="$*" echo -e "Last Name: $1\nFirst Name: $2\nState: $4" while true do echo "What would you like to change the state to?:" read state if echo $state | egrep -q '^[A-Z]{2}$' then echo "State: $state" echo "This is a valid input" break else echo "Not a valid input:" fi done echo -e "Last Name: $c1\nFirst Name: $c2\nState: $state" echo "State value changed" break else echo "ERROR: $last_name is not in database" echo "Would you like to search again (y/n):" read modify_choice case $modify_choice in [Nn]) break;; esac fi done ;; Ok so everything works except for the
echo -e "Last Name: $c1\nFirst Name: $c2\nState: $state" It will just show:
Last Name:
First Name:
State:
So I can see it is not adding it to my echo correctly.
FINAL EDIT
CODE:
#Case statement for modifying an entry m|M) #Create Modify Message clear echo " Modify Record " echo -en '\n' echo -en '\n' while true do echo "What is the last name of the person you would like to modify:" read last_name if line=$(grep -i "^${last_name}:" "$2") then echo "$line" | while IFS=: read c1 c2 c3 c4 rest; do echo -e "Last Name: $c1\nFirst Name: $c2\nState: $c4" last=$c1 first=$c2 done while true do echo "What would you like to change the state to?:" read state if echo $state | egrep -q '^[A-Z]{2}$' then echo "State: $state" echo "This is a valid input" break else echo "Not a valid input:" fi done echo -e "Last Name: $last\nFirst Name: $first\nState: $state" echo "State value changed" break else echo "ERROR: $last_name is not in database" echo "Would you like to search again (y/n):" read modify_choice case $modify_choice in [Nn]) break;; esac fi done ;;
-2355399 0 Creating a "skeleton" of an existing database I have a huge database in production environment which I need to take a copy off, but the problem is that the data is over 100Gb's and downloading a backup off it is out of the question. I need to get a "skeleton" image of the database. What I mean by "skeleton" is, I need to get the database outline so that I can recreate the database locally by running SQL scripts.
Is there a quick and easy way to retrieve the SQL for recreating the database structure and tables?
Or will I have to write something in order to do this programmatically?
-11653985 0An IMHO improved way based upon ZZ Coder's solution is to use a ResponseInterceptor to simply track the last redirect location. That way you don't lose information e.g. after an hashtag. Without the response interceptor you lose the hashtag. Example: http://j.mp/OxbI23
private static HttpClient createHttpClient() throws NoSuchAlgorithmException, KeyManagementException { SSLContext sslContext = SSLContext.getInstance("SSL"); TrustManager[] trustAllCerts = new TrustManager[] { new TrustAllTrustManager() }; sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); SSLSocketFactory sslSocketFactory = new SSLSocketFactory(sslContext); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("https", 443, sslSocketFactory)); schemeRegistry.register(new Scheme("http", 80, new PlainSocketFactory())); HttpParams params = new BasicHttpParams(); ClientConnectionManager cm = new org.apache.http.impl.conn.SingleClientConnManager(schemeRegistry); // some pages require a user agent AbstractHttpClient httpClient = new DefaultHttpClient(cm, params); HttpProtocolParams.setUserAgent(httpClient.getParams(), "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:13.0) Gecko/20100101 Firefox/13.0.1"); httpClient.setRedirectStrategy(new RedirectStrategy()); httpClient.addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(HttpResponse response, HttpContext context) throws HttpException, IOException { if (response.containsHeader("Location")) { Header[] locations = response.getHeaders("Location"); if (locations.length > 0) context.setAttribute(LAST_REDIRECT_URL, locations[0].getValue()); } } }); return httpClient; } private String getUrlAfterRedirects(HttpContext context) { String lastRedirectUrl = (String) context.getAttribute(LAST_REDIRECT_URL); if (lastRedirectUrl != null) return lastRedirectUrl; else { HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); String currentUrl = (currentReq.getURI().isAbsolute()) ? currentReq.getURI().toString() : (currentHost.toURI() + currentReq.getURI()); return currentUrl; } } public static final String LAST_REDIRECT_URL = "last_redirect_url"; use it just like ZZ Coder's solution:
HttpResponse response = httpClient.execute(httpGet, context); String url = getUrlAfterRedirects(context);
-9175243 0 Force, I must tell you that an Android Service do not require root access instead some actions(i.e. Access, Read, Write system resources) requires Root Permissions. Every Android Service provided in Android SDK can be run without ROOT ACCESS.
You can make the actions to execute with root permissions with the help of shell commands.
I have created an abstract class to help you with that
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import android.util.Log; public abstract class RootAccess { private static final String TAG = "RootAccess"; protected abstract ArrayList<String> runCommandsWithRootAccess(); //Check for Root Access public static boolean hasRootAccess() { boolean rootBoolean = false; Process suProcess; try { suProcess = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(suProcess.getOutputStream()); DataInputStream is = new DataInputStream(suProcess.getInputStream()); if (os != null && is != null) { // Getting current user's UID to check for Root Access os.writeBytes("id\n"); os.flush(); String outputSTR = is.readLine(); boolean exitSu = false; if (outputSTR == null) { rootBoolean = false; exitSu = false; Log.d(TAG, "Can't get Root Access or Root Access deneid by user"); } else if (outputSTR.contains("uid=0")) { //If is contains uid=0, It means Root Access is granted rootBoolean = true; exitSu = true; Log.d(TAG, "Root Access Granted"); } else { rootBoolean = false; exitSu = true; Log.d(TAG, "Root Access Rejected: " + is.readLine()); } if (exitSu) { os.writeBytes("exit\n"); os.flush(); } } } catch (Exception e) { rootBoolean = false; Log.d(TAG, "Root access rejected [" + e.getClass().getName() + "] : " + e.getMessage()); } return rootBoolean; } //Execute commands with ROOT Permission public final boolean execute() { boolean rootBoolean = false; try { ArrayList<String> commands = runCommandsWithRootAccess(); if ( commands != null && commands.size() > 0) { Process suProcess = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(suProcess.getOutputStream()); // Execute commands with ROOT Permission for (String currentCommand : commands) { os.writeBytes(currentCommand + "\n"); os.flush(); } os.writeBytes("exit\n"); os.flush(); try { int suProcessRetval = suProcess.waitFor(); if ( suProcessRetval != 255) { // Root Access granted rootBoolean = true; } else { // Root Access denied rootBoolean = false; } } catch (Exception ex) { Log.e(TAG, "Error executing Root Action", ex); } } } catch (IOException ex) { Log.w(TAG, "Can't get Root Access", ex); } catch (SecurityException ex) { Log.w(TAG, "Can't get Root Access", ex); } catch (Exception ex) { Log.w(TAG, "Error executing operation", ex); } return rootBoolean; } } Extend your class with RootAccess or create an instance of RootAccess class and Override runCommandsWithRootAccess() method.
-3370656 0 C++ Boost multi-index type identificationIn boost multi-index, can I verify whether a particular index type is ordered/not through meta programming? There are the ordered indexes, hash indexes, sequence indexes etc. Can I find them out through meta programming?
Suppose there is a index like:
int main() { typedef multi_index_container<double> double_set; return 0; } I want to know whether the double_set index is ordered or hashed or sequenced. Of course in this case, it is ordered.
-1815095 0do all JVMs optimize the usage of Strings in a way such that when the same string is used several times, it will always be the same physical instance?
I doubt that very much. In the same class file, when definined like:
String s1 = "Yes"; String s2 = "Yes"; you'll probably have s1 == s1.
But if you have like:
String x = loadTextFromFile(); // file contains es StringBuilder b = new StringBuilder(); s2 = b.append("Y").append(x).toString(); // s2 = "Yes" I don't think the runtime is going to check and compare all the loaded strings to the return value of them builder.
So, always compare objects with equals(). That's good advice anyway since every good equals starts with:
if (this == o) { return true; }
-30480178 0 innerText auto truncating long text inside a DOM element I am trying to access the content inside a td element through the JavaScript innerText property (inside an excel VBA macro). It works perfectly for all cases except for this one case where the text inside the td element is very long (greater than 85982 characters).
Upon inspection of the text extracted by innerText, I found that innerText seems to be truncating the text after a certain length. Note that this doesn't happen for other cases where the text size is small.
Also, it seems that Mozilla's textContent property has a similar problem as well. I tried accessing the truncated part of the text using the developer console in Firefox for the aforementioned DOM element, but it seems that text isn't there in the extracted content (but the not truncated text is there - just like with innerText).
Does anyone know how to bypass this restriction? Is there some internal limit on these functions?
Here's my VBA code that has this problem:
MyInnerText = objElement.ChildNodes(3).innerText Here's an equivalent code run in the Firefox console which has the same problem:
var t = document.getElementsByName("chapter11")[0].parentNode.children[3].textContent; t.match("some text that is in the part being truncated."); For Firefox, this problem seems to go away if I inspect the element, and click "Show all 3396" nodes. After those nodes are visible, the textContent does not truncate the text anymore.
Please do note that I want to be able to extract the text from inside a VBA script using the Internet Explorer object.
-33642859 0-eq is similar to == operator which will compare the address for Objects not values. You must use Array or other collection utilities to compare two Objects.
-17656342 0Would something like this work?
SELECT max(a.field_date_and_time_value2) as last_time , b.uid FROM field_data_field_date_and_time a INNER JOIN node b ON /* this piece might be wrong. what is the relationship between the first table and the second one? */ b.nid = '".$node->nid."' where a.field_date_and_time_value2 > '".$today."' AND b.uid = $node->nid
-20382511 0 This one works fine:
; 0_9.asm ; assemble with "nasm -f bin -o 0_9.com 0_9.asm" org 0x100 ; .com files always start 256 bytes into the segment mov cx, 9 ; counter mov dl, "0" ; 0 top: push dx push cx mov ah, 2 int 21h mov dl, "_" ; display underscore mov ah, 2 int 21h pop cx pop dx inc dl loop top mov dl, "9" ; display 9 mov ah, 2 int 21h mov ah, 4ch ; "terminate program" sub-function mov al,00h int 21h
-1552913 0 You say it works if you use the full path to tclsh84.exe. So, a solution might be to find out that full path and use it in your call to proc_open.
If you know your tclsh84.exe is in the directory in which your PHP script is, you could use something based on dirname and __FILE__ ; a bit like this, I suppose :
$dir = dirname(__FILE__); var_dump($dir); // directory in which the current PHP script is in $path = $dir . DIRECTORY_SEPARATOR . 'tclsh84.exe'; var_dump($path); Considering the PHP script I am using is /home/squale/developpement/tests/temp/temp.php, I would get :
string '/home/squale/developpement/tests/temp' (length=37) string '/home/squale/developpement/tests/temp/tclsh84.exe' (length=49) And, if needed, you can use '..' to go up in the directories tree, and, then use directories names to go down.
Another solution might be to make sure that the program you are trying to execute is in your PATH environment variables -- but if it's a program that's used only by your application, it doesn't make much sense to modify your PATH, I guess...
How can I get all content between pipes and return a space where it comes across two pipes next to each other?
An example string and desired output is:
|test1| test2|test3 || test 4 | Result1: "test1" Result2: "test2" Result3: "test3" Result4: " " Result5: "test4" The closest I've got so far is:
/[^\|]+)/ which will get all data between pipes but does not detect ||./\|([^\|]*)/ which will get all data between pipes and detect || but have an extra whitespace result at the end.For MySQL and SQLite,ejabberd provides a way to store messages in a very simple way.
-13340679 0 Time Range Selection in C#How can I know current time(not date) is between JobStart & Job End Time
var JobStartTime = new DateTime(2012,1,1,9,0,0,DateTimeKind.Local); //09:00AM var JobEndTime = new DateTime(2012,1,1,18,0,0,DateTimeKind.Local); //06:00PM var CurrentTime = DateTime.Now;
-24409698 1 Django view function not being called Ths is the function in question. The problem is that it does not seem to do be called. User can download any files on the server, regardless of whether pk matches request.user.id or not.
def permit(request, pk): # First I sanitize system_path from request, then... if int(request.user.id) == int(pk) and int(request.user.id) >= 1: sendfile(request, system_path) else: return render_to_response('forbidden.html') return HttpResponseRedirect('/notendur/list') As you can see, it takes pk and compares it to request.user.id, and serves the file if that is the case.
Then the relevant bits of urls.py
urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), #upload urls (r'^notendur/', include('notendur.urls')), #This needs to be changed to welcome.html (r'^$', RedirectView.as_view(url='/notendur/list/')), # Just for ease of use. #security url(r'^media/uploads/(?P<pk>[^/]+)', 'notendur.views.permit'), url(r'^media', 'notendur.views.permit'), ) This error sort of came out of the blue. I hadn't edited anything pertaining to this as far as I am aware.
I know the function is not being called because I commented out the sendfile() and put render_to_response('forbidden.html') instead. Did not have any effect; user could still download file unexamined.
a while ago i was using htaccess to display some files, and recently i started that project again and found i had somehow deleted the "go up a level" button back then.
Can anyone tell me what the code line in htaccess looks like to get this button back? Should be relatively simple but i just cant find it... heres what i got.
Options +Indexes # DIRECTORY CUSTOMIZATION <IfModule mod_autoindex.c> IndexOptions IgnoreCase FancyIndexing FoldersFirst NameWidth=* DescriptionWidth=* SuppressHTMLPreamble # SET DISPLAY ORDER IndexOrderDefault Descending Name # SPECIFY HEADER FILE HeaderName /partials/header.html # SPECIFY FOOTER FILE ReadmeName /partials/footer.html # IGNORE THESE FILES, hide them in directory IndexIgnore .. IndexIgnore header.html footer.html icons # IGNORE THESE FILES IndexIgnore header.html footer.html favicon.ico .htaccess .ftpquota .DS_Store icons *.log *,v *,t .??* *~ *# # DEFAULT ICON DefaultIcon /icons/generic.gif AddIcon /icons/dir.gif ^^DIRECTORY^^ AddIcon /icons/pdf.gif .txt .pdf AddIcon /icons/back.png .. </IfModule> Options -Indexes
-14118750 0 If you'd use only id's the selection would be faster, but you would also have to do more selections than if you would use classes. Provided that the css is clean. Problem with basing style on id's in general is that you forgo all reuse of that style.
The best way to go is to link style to classes. That gives you adequate speed and keeps the css file smaller. Smaller files are much more important for performance in most sites than faster execution on the client. Typical clients will render a complex page in microseconds, once they have all the resources that is.
The css you point out is using a sprite, which could very well be generated with compass or something similar. It's important to see the original code too before making harsh judgements about the quality.
-6835427 0If you do not mind additional statements (while loop) the following will work in c99
#define NBITS_32(n,out_len) 0; while (n && !(0x80000000 >> out_len & n)) out_len++; out_len = n ? abs(out_len - 32) : n uint8_t len1 = NBITS_32(0x0F000000, len1); uint8_t len2 = NBITS_32(0x00008000, len2); uint8_t len3 = NBITS_32(0xFFFFFFFF, len3); uint8_t len4 = NBITS_32(0x00000001, len4); printf("%u\n%u\n%u\n%u\n", len1, len2, len3, len4); Output:
-28157759 028
16
32
1
In order to Updateupdate the data on the database your SqlDataAdapter need to have its InsertCommand, UpdateCommand, DeleteCommand properties set.
So, try the below code:
ds.Tables[0].Rows.Add(newRow); SqlCommandBuilder commandBuilder = new SqlCommandBuilder(adp); adp.DeleteCommand = commandBuilder.GetDeleteCommand(true); adp.UpdateCommand = commandBuilder.GetUpdateCommand(true); adp.InsertCommand = commandBuilder.GetInsertCommand(true); adp.Update(ds.Tables[0]); //connection.UpdateDatabase(ds); connection.Close(); Edit: The Update method takes the name of a DataSet and a table. The DataSet for us is ds, which is the one we passed in to our UpdateDatabase method when we set it up. After a dot, you type the name of a table in your dataset.
-6720268 0I wrote a server side script that shows the output of headers from both examples and APIKEY was set identically in both cases. There were some differences in HTTP_ACCEPT / HTTP_ACCEPT_ENCODING and WWW::Mechanize adds some additional headers:
'downgrade-1.0' => '1' 'force-response-1.0' => '1' 'nokeepalive' => '1' So I would suggest the problem is somewhere else.
-17496867 0Many ways to persist these days...
localStorage()If this intro could be annoying for repeat users and the site has a login, I'd persist it server side. You don't want the user being hit with it when they use a different browser or computer to access your site.
If not, use localStorage().
You can't use paths like that in the extends tag. But you don't need to - assuming your TEMPLATE_DIRS setting is root/pages, you just do extends "base.html".
Try this:
virtual public IEnumerable<string> GetSelectedIds(){ if (_kids == null){ yield return null; yield break; } foreach (var current in _kids.Nodes) yield return current; }
-40011046 0 Whitespace is important; you need to separate the == operator from its arguments, and you need to separate the brackets from the condition.
if [[ "$1" == "sell" ]]
-10244637 0 If you want to keep record of all queries that are executed, you can enable either the General Query Log or the Slow Query Log and set the threshold to 0 seconds (any query that takes more than 0 seconds will be logged).
Another option is the Binary log. However, binary log does not keep record of queries like SELECT or SHOW that do not modify data.
Note that these logs get pretty big pretty fast in a server with traffic. And that both might contain passwords so they have to be protected from unauthorized eyes.
-6047463 0Because the triple design doesn't prevent you from using a closure, while the alternative approach prevents you from not using closures. Sometimes the external-state design is the simpler approach.
For instance, say that you're using a for loop to iterate which pages to display in the response to a RESTful query. With external-state-based loops, you can write a function that iterates pages based on a table representing the state-representational parameters of the query (which you construct from the URL once and reuse for several other functions). With triples, you can iterate with just those values without being forced to wrap it (and every other function like it) in a closure constructor.
ctype_digit( (string) $score); preg_match('#^\d+$#', $score); In b4 @EmilioGort
boolean false int 0
-21938921 0 How to manipulate the output to a ItemsSource? With this Previous Question i was able too manage to show the output. I've reading alot of posts here on stackoverflow, but cant find the right solution for the next:
How to manipulate the output too ItemsSource, because:
{"order_id":"12345678","itemList":["235724","203224","222224","222324","230021"],"amount":["65","50","10","25","42"]} The number 235724 is also used within a IMG url and need to become like "235724 X 65" for a selectable listbox.
Solution was:
ObservableCollection<CreateItem> pitems = new ObservableCollection<CreateItem>(); for (int i = 0; i < rootObject.itemList.Count; i++) { var itemsku = rootObject.itemList[i]; var amount = rootObject.amount[i]; pitems.Add(new CreateItem() { pTitle = itemsku + " X " + amount , pImage = new BitmapImage(new Uri(string.Format("http://image.mgam79.nl/indb/{0}.jpg", itemsku)))}); } MyListBox.ItemsSource = pitems; public class CreateItem { public string pTitle { get; set; } public ImageSource pImage { get; set; } }
-25179324 0 change
strcat(ipstr,&ipch); to
strncat(ipstr, &ipch, 1); this will force appending only one byte from ipch. strcat() will continue appending some bytes, since there's no null termination character after the char you are appending. as others said, strcat might find somewhere in memory \0 and then terminate, but if not, it can result in segfault.
from manpage:
char *strncat(char *dest, const char *src, size_t n); The strncat() function is similar to strcat(), except that
I feel your process(mosquitto) have hit the maximum number of open file descriptors limit. Check your max open files by ulimit -n. Then increase the limit to max number of connections expected by you. E.g. For 10k connection it would be ulimit -n 10000
A note on ulimit(1). It is only set for the current terminal and for persistent changes you will need to edit config files as per your Linux flavor( /etc/security/limits.conf + /etc/pam.d/common-session* on Ubuntu ).
-20237644 0Creating snapshots in VHD works by putting an overlay over the existing VHD image, so that any change get written into the overlay file instead of overwriting existing data. For reading the top-most data is returned: either the data from the overlay if that sector/cluster was already over-written, or from the original VHD file if it was not-yet over-written.
The vhd-util command creates such an overlay-VHD-file, which uses the existing VHD image as its so-called "backing-file". It is important to remember, that the backing-file must never be changed while snapshots still using this backing-file exist. Otherwise the data would change in all those snapshots as well (unless the data was overwritten there already.)
The process of using backing files can be repeated multiple times, which leads to a chain of VHD files. Only the top-most file should ever be written to, all other files should be handled as immutable.
Reverting back to a snapshot is as easy as deleting the current top-most overlay file and creating a new empty overlay file again, which again expose the data from the backing file containing the snapshot. This is done by using the same command again as above mentioned. This preserves your current snapshot and allows you to repeat that process multiple times. (renaming the file would be more like "revert back to and delete last snapshot".)
Warning: before re-creating the snapshot file, make sure that no other snapshots exists, which uses this (intermediate) VHD file as its backing file. Otherwise you would not only loose this snapshot, but all other snapshots depending on this one.
-13614770 0I simply created Drupal nodes programmatically. Turned out to be easiest.
-20082646 0There might be a way to do this with less duplication, but the following should work, anyway. First, find out which columns we need to shift, and then replace those columns by the shifted versions.
to_shift = pd.isnull(df2.iloc[-1]) df2.loc[:,to_shift] = df2.loc[:,to_shift].shift(1) Get the last row:
>>> df2.iloc[-1] one 5 two NaN three NaN Name: i, dtype: float64 See where there's missing data:
>>> pd.isnull(df2.iloc[-1]) one False two True three True Name: i, dtype: bool >>> to_shift = pd.isnull(df2.iloc[-1]) Select that portion of the frame:
>>> df2.loc[:, to_shift] two three a -0.447225 0.240786 b NaN NaN c 1.736224 0.191835 d NaN NaN e -0.310505 2.121659 f 2.542979 -0.772117 g NaN NaN h -0.350395 0.825386 i NaN NaN Shift it:
>>> df2.loc[:, to_shift].shift(1) two three a NaN NaN b -0.447225 0.240786 c NaN NaN d 1.736224 0.191835 e NaN NaN f -0.310505 2.121659 g 2.542979 -0.772117 h NaN NaN i -0.350395 0.825386 And fill the frame with the shifted data:
>>> df2.loc[:, to_shift] = df2.loc[:, to_shift].shift(1) >>> df2 one two three a -0.691010 NaN NaN b NaN -0.447225 0.240786 c 0.570639 NaN NaN d NaN 1.736224 0.191835 e 2.509598 NaN NaN f -2.053269 -0.310505 2.121659 g NaN 2.542979 -0.772117 h 1.812492 NaN NaN i 5.000000 -0.350395 0.825386
-27093061 0 android calender events handling library Is there any open source library to add/remove/update calendar events in android devices? (android 2.3.x and above)
I am looking at adding events "silently", meaning injecting them into the users calendar
-28726660 0$('#sort_by').on('change', function(){ $.ajax({ type: "GET", url: "/items", data: { sort: $('option:selected', this).val() }, dataType : "script" }).done(function(data) { console.log(data); }); });
-28079643 0 Rails 4 Bootstrap partial styling I've been having trouble integrating bootstrap-sass into any of my Rails 4 projects. So far i'm only getting partial rendering of the bootstrap assets. I've resorted to using using the railstutorial.org in my search for bootstrap functionality. I'm using the ch5 (listing 5.4) source code yielding the following results:
The classes btn-lg, btn-primary, and navbar-right classes are working. The page yields buttons and a partially structured navbar with the links to the right. However, the navbar classes for the most part are not working. The navbar has no 'inverse' styling, the entire div is washed out with no text styling whatsoever.
I've been using 'rake assets:precompile' and restarting the server after every update to the assets pipeline.
Gemfile contains the following above the 'jquery-rails' gem
gem 'rails', '4.2.0' gem 'bootstrap-sass', '~> 3.3.3' gem 'sass-rails', '>= 3.2' custom.css.scss
@import "bootstrap-sprockets"; @import "bootstrap" application.html.erb
<!DOCTYPE html> <html> <head> <title><%= full_title(yield(:title)) %></title> <%= stylesheet_link_tag "application", :media => "all" %> <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %> <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %> <%= csrf_meta_tags %> <!--[if lt IE 9]> <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/r29/html5.min.js"> </script> <![endif]--> </head> <body> <div class="navbar navbar-fixed-top navbar-inverse"> <div class="container"> <%= link_to "sample app", '#', id: "logo" %> <nav> <ul class="nav navbar-nav navbar-right"> <li><%= link_to "Home", '#' %></li> <li><%= link_to "Help", '#' %></li> <li><%= link_to "Log in", '#' %></li> </ul> </nav> </div> </div> <div class="container"> <%= yield %> </div> </body> </html> Buttons in home.hrml.erb
<% provide(:title, "Home") %> <div class="center jumbotron"> <h1>Welcome to the Sample App</h1> <h2> This is the home page for the <a href="http://www.railstutorial.org/">Ruby on Rails Tutorial</a> sample application. </h2> <%= link_to "Sign up now!", '#', class: "btn btn-lg btn-primary" %> </div> <%= link_to image_tag("rails.png", alt: "Rails logo"), 'http://rubyonrails.org/' %> I found the solution, use replaceFilters outside from object (after declaration).
myns.test.util = { myOne: function(m) { return m; }, myTwo: function(m) { return m; }, processAllFunction: function(m) { for(var i=0; i<this.replaceFilters.length; i++) { if(typeof(this.replaceFilters[i])==='function') { m= this.replaceFilters[i](m); } } console.log(this.replaceFilters); return m; } }; myns.test.util.replaceFilters = [this.myOne, this.myTwo]; with this method, I don't have problem with this.
This is what I would like to achieve.

Although when using this code.
<paper-input-decorator floatingLabel label="Name *"> <core-icon icon="account-circle"></core-icon> <input type="name"> </paper-input-decorator> I end up with this,

I've noticed that in the code on their website (which can be seen here) they have just given the form soem padding on the left and then given the icon an absolute position. Is this the only way to do that set up?
Thank you.
-30758937 0TL;DR - In the code snippet shown above, there is no memory leak.
Do I need to use malloc instead of hardcoded size of array?
I think, you got confused by the possible underuse of char buffer[10000]; and char error_msg[10000];. These arrays are not allocated dynamically. Even the arrays are not used to their fullest capacities, there is no memory leak here.
Also, as Mr. @Vlad metioned rightly about another much possible issue in your case, actual_error_msg being a global, if the trimwhitespace() function does not have a return value which is having a global scope, (i.e., stays valid after the a() has finished execution), it may possibly lead to undefined behaviour.
To avoid that, make sure, trimwhitespace() function is either returning (assuming return type is char *)
static array. (bad practice, but will work)To elaborate, from the Wikipedia article about "memory leak"
In computer science, a "memory leak" is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in such a way that memory which is no longer needed is not released. ...
and
.. Typically, a memory leak occurs because dynamically allocated memory has become unreachable. ...
When memory is being allocated by your compiler, there is no scope of memory leak, as the memory (de)allocation is managed by the compiler.
OTOH, with dynamic memory allocation, allocation of memory is performed at runtime. Compiler has no information about the allocation, memory is allocated programatically, hence need to be freed programatically, also. Failing to do so leads to the "memory leak".
-32648375 0OK, I found a solution and I'll post it here to help others. This is the link that helped me, and this is the sample of code that I needed. (it was hard to find).
public void run() { Canvas canvas = null; while (_run){ try{ canvas = mSurfaceHolder.lockCanvas(null); if(mBitmap == null){ mBitmap = Bitmap.createBitmap (1, 1, Bitmap.Config.ARGB_8888);; } final Canvas c = new Canvas (mBitmap); c.drawColor(0, PorterDuff.Mode.CLEAR); commandManager.executeAll(c); canvas.drawBitmap (mBitmap, 0, 0,null); } finally { mSurfaceHolder.unlockCanvasAndPost(canvas); } } } }
-34695860 0 BFS for pacman ghostI've been several days with this problem. I've searched in this forum, and in google for a solution without any luck. My problem is I am not able to make a working BFS algorithm for managing the behaviour of a pacman ghost. I think I am ignoring something in the code. I'll paste the code here, if you can help me you'll be thanked :) pacman is number 2, and ghost is number 3.
Queue<Tile> path = new LinkedList<>(); Tile start = new Tile(canvas.g1.x, canvas.g1.y, 3); Tile end = new Tile(canvas.pacman.x, canvas.pacman.y, 2); start.distance = 1; path.add(start); while (!path.isEmpty()) { Tile current = path.remove(); System.out.println(path.size()); canvas.walls[current.y][current.x] = 0; if (canvas.walls[current.y][current.x] == canvas.walls[end.y][end.x]) { end = current; System.out.println("pacman found"); break; } ArrayList<Tile> list = adyacent(current); for (Tile c : list) { if (c.distance == 0) { c.distance = current.distance + 1; path.add(c); canvas.walls[c.y][c.x] = 20; for (Tile v : path) { System.out.println("x: " + v.x + " / y: " + v.y + " / distance: " + v.distance); } } } } int dist = end.distance; System.out.println("Recolection ended, size: " + dist); The class Tile():
public class Tile { public int x; public int y; public int distance; public int personaje; public Tile(int x, int y, int personaje) { this.x = x; this.y = y; this.personaje = personaje; distance = 0; } } and the method adyacent():
in this method, the numbers I check are the ones with wall(each one with a diferent drawing))
public ArrayList<Tile> adyacent(Tile c) { ArrayList<Tile> surrounding = new ArrayList<>(); int ant; ant = canvas.walls[c.y][c.x + 1]; if ((ant != 7) && (ant != 8) && (ant != 9) && (ant != 11) && (ant != 12) && (ant != 13) && (ant != 14) && (ant != 15) && (ant != 16)) { surrounding.add(new Tile(c.x + 1, c.y, 3)); } ant = canvas.walls[c.y][c.x - 1]; if ((ant != 7) && (ant != 8) && (ant != 9) && (ant != 11) && (ant != 12) && (ant != 13) && (ant != 14) && (ant != 15) && (ant != 16)) { surrounding.add(new Tile(c.x - 1, c.y, 3)); } ant = canvas.walls[c.y + 1][c.x]; if ((ant != 7) && (ant != 8) && (ant != 9) && (ant != 11) && (ant != 12) && (ant != 13) && (ant != 14) && (ant != 15) && (ant != 16)) { surrounding.add(new Tile(c.x, c.y + 1, 3)); } ant = canvas.walls[c.y - 1][c.x]; if ((ant != 7) && (ant != 8) && (ant != 9) && (ant != 11) && (ant != 12) && (ant != 13) && (ant != 14) && (ant != 15) && (ant != 16)) { surrounding.add(new Tile(c.x, c.y - 1, 3)); } return surrounding; } What I've observed is that it never reaches the System.out in which I return the size of the path. Also, where I see the size of the Queue, it seems right, but the System.out in which I see "x" and "y" and "distance" is bigger each time, much much bigger.
I set that the checked tiles change it's color, changing the number which I've got in the array: 0 is floor, 20 is transparent green. And it remains in center, and beggins to work slower and slower.
Forget to say that it never finds pacman :( thanks!
-2424660 0setAttribute is broken in IE7 and lower.
Use
div.className = 'pano_img_cont' instead.
IE's implementation of setAttribute is effectively:
HTMLElement.prototype.setAttribute = function (attribute, value) { this[attribute] = value; } … which is fine so long as the attribute name and the DOM property name are the same. class, however, is a reserved keyword in JS so the property is called className instead. This breaks in IE.
If you set the property directly, it works everywhere.
-37391061 0What you are doing here is creating an anonymous method that calls each service in turn and then executes that method in a parallel task. What you need is a task array.
List<Task> taskList = new List<Task>(); Task task1= Task.Factory.StartNew(() => var List1 = client1.GetList1();); Task task2= Task.Factory.StartNew(() => var List2 = client1.GetList2();); // and so forth taskList.Add(task1); taskList.Add(task2); Task.WaitAll(taskList.ToArray());
-25194045 0 Your function introducir_datos() is declared as follows:
void introducir_datos (struct agenda cliente[30]); But in your nested switch statement, you have this line:
introducir_datos(cliente); where cliente is declared as char cliente[30]. So instead of providing introducir_datos() with a struct agenda* argument, you are giving it a char* argument.
The function introducir_datos() expects to be given an array of 30 struct agenda items as its argument.
This means that the argument type is struct agenda*, because you are sending a pointer to the first item in the array. (This is just how arrays work in C.)
You can't call this function with a char[] array as the argument, because a char[] array consists of char variables. A char doesn't have any nombre, apellido, direccion, edad or telefono members.
So your code won't compile because the compiler can't figure out what you're trying to do.
Incidentally, although you declare the variable int x; in introducir_datos(), you don't initialize it anywhere, so you need to fix that too.
I have a simple Windows service that calls a batch file to setup some processes on startup. Most of the batch file is fired correctly but InstallUtil /i fails to run as the Windows Service fails to start. (InstallUtil /u beforehand works though which I find strange) Here's some code for the windows service and the batch file:
namespace RecipopStartupService { public partial class Service1 : ServiceBase { public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { ProcessBatchFile(); } public void ProcessBatchFile() { Process process = new Process(); process.StartInfo.WorkingDirectory = "C:\\Webs\\AWS\\"; process.StartInfo.FileName = "C:\\Webs\\AWS\\setup.bat"; process.StartInfo.Arguments = ""; process.StartInfo.Verb = "runas"; process.StartInfo.UseShellExecute = false; process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; process.StartInfo.CreateNoWindow = true; process.StartInfo.RedirectStandardOutput = false; process.Start(); System.IO.StreamReader myOutput = process.StandardOutput; process.WaitForExit(200000); if (process.HasExited) { string results = myOutput.ReadToEnd(); } } protected override void OnStop() { } } } The batch file:
"C:\Program Files (x86)\Subversion\bin\SVN.exe" cleanup "C:\Webs\AWS\webs" "C:\Program Files (x86)\Subversion\bin\SVN.exe" cleanup "C:\Webs\AWS\apps" "C:\Program Files (x86)\Subversion\bin\SVN.exe" update "C:\Webs\AWS\webs" REM The following directory is for .NET 2.0 set DOTNETFX2=%SystemRoot%\Microsoft.NET\Framework\v4.0.30319 set PATH=%PATH%;%DOTNETFX2% echo Uninstalling MyService... echo --------------------------------------------------- InstallUtil /u "C:\Webs\AWS\apps\MyService.exe" echo --------------------------------------------------- echo Done. "C:\Program Files (x86)\Subversion\bin\SVN.exe" update "C:\Webs\AWS\apps" REM The following directory is for .NET 2.0 set DOTNETFX2=%SystemRoot%\Microsoft.NET\Framework\v4.0.30319 set PATH=%PATH%;%DOTNETFX2% echo Installing MyService... echo --------------------------------------------------- InstallUtil /i "C:\Webs\AWS\apps\MyService.exe" echo --------------------------------------------------- echo Done. NET START MyService I've commented out various parts to determine what stops the service from starting. It's the InstallUtil /i section as I said previously.
If someone could advise that'd be great.
Thanks, Colin
-25321785 0In your for loop, you created var category which is already a variable
$scope.browseCategories = function(category, moveTo) { //looping in order to create a new <ul> of children categories. var html = "<ul class='unstyled'>"; for (var I = 0; I < category.Children.length; ++I) { var category = category.Children[I]; ^^^^^^^^ Try renaming that and see.
This might do whatever you are trying to achieve. Hope that helps.
But when you're doing it in angular, the best practice is to avoid any other libraries like jQuery and try to achieve it in the angular way. Angular is so powerful.
See this SO post: How do I "think in AngularJS" if I have a jQuery background?
-3601004 0import re if re.search("string_1|string_2|string_n", var_strings): print True The beauty of python regex it that it returns either a regex object (that gives informations on what matched) or None, that can be used as a "false" value in a test.
-14314029 0 In Rails, what is the best way to return a RecordNotFound Error from a Model.find call in JSON?What should be the right response for a RecordNotFound Error when doing something like this:
def destroy @post = current_user.posts.find(params[:id]) @post.destroy head :no_content end
-9074279 0 You may disable the URL escape behavior using escapeAmp="false" attribute. By default, this is enabled, so URL parameter & will render &. This will cause a problem on reading the parameter value with parameter name.
request.getParameter("amp;pageNumber_hidden")escapeAmp and set the value false as part of the <s:url> tag (Recommended)<s:url id="loadReportsForAPageInitial" value="/loadReportsForAPage.action" escapeAmp="false">
-863040 0 The zxing library is primarily Java, but, includes a port of the QR Code detector and decoder to C++.
-38025882 0 How to compare arabic- and kana full-width digits?How can I compare in PHP the two strings
県19−1県225−3県96−1 and
県19-1県225-3県96-1 ?
The first one contains kana full-width numbers, the comparison should treat them as equal to the arabic-numeral.
-40353192 0As of version 1.5.1, I'm able to access all the sockets in a namespace with:
var socket_ids = Object.keys(io.of('/namespace').sockets); socket_ids.forEach(function(socket_id) { var socket = io.of('/namespace').sockets[socket_id]; if (socket.connected) { // Do something... } }); For some reason, they're using a plain object instead of an array to store the socket IDs.
-21320562 0it might be a bug of hibernate, If you read (load() a proxy instance) and then call delete and save on it . https://hibernate.atlassian.net/browse/HHH-8374
-17184489 0e.target points to the a link inside the li. you should use e.target.parentElement.id
If you Inserted app indexing API code by mistake and an error like "Cannot resolve method ... " is popping up but cannot reverse it.
-34977826 0 Geolocation doesn't work with cordovaI'm currently working on a mobile application with Intel XDK (In background it's Cordova finally, that's why I put Cordova in title.)
With an Ajax request, I get some adresses and with these adresses I want to calculate the distance between them and the current position of user.
So, I get adresses, I convert them and I make the difference.
But actually, nothing is working !
function codeAddress(id, addresse) { geocoder.geocode( { 'address': addresse}, function(results, status) { if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) { setTimeout(function(){}, 100); } console.log(id); console.log(addresse); //document.addEventListener("intel.xdk.device.ready",function(){ if (navigator.geolocation) { if (status == google.maps.GeocoderStatus.OK) { navigator.geolocation.getCurrentPosition(function(position) { addressEvent = results[0].geometry.location; var pos = { lat: position.coords.latitude, lng: position.coords.longitude }; var position = new google.maps.LatLng(pos.lat, pos.lng) var resultat = google.maps.geometry.spherical.computeDistanceBetween(addressEvent, position); console.log(resultat); console.log(addressEvent); console.log(pos); console.log(position); var convert = Math.floor(resultat); var finalConvert = convert + " m"; var distance = document.createElement('span'); distance.innerHTML = finalConvert; distance.className = "geo"; document.getElementsByClassName('meta-info-geo')[id].appendChild(distance); }, function() { handleLocationError(true, infoWindow); }); } } //},false); }); } In the console.log(id), console.log(addresse), I HAVE results !
Actually i'm getting 4 IDs and 4 adresses.
I checked on all the topics I could find on StackOverFlow, and I had normally to add the line in // with the addEventListener but it changes nothing.
Is there someone who knows how to change that ?
ps : Of course, cordova geoloc is in the build and permissions are granted !
EDIT : I'm targeting Android 4.0 min and iOS 5.1.1. I'm using SDK.
-39776312 0var level=0; var levelarray=[]; function looptrough(obj){ for(key in obj){ if(typeof obj[key]=="object"){ level++; looptrough(obj[key]); level--; } levelarray[level]=levelarray[level] || {}; levelarray[level][key]=obj[key]; } } looptrough({a:true;b:{c:true}}); Levelarray should now contain:
0:{a:true;b:{c:true}} 1:{c:true} I thought using jquery is quite unecessary in that case, thats why i used for in...
-21223514 0This sequence of commands clones your GitHub repository (or any other repository if you change the URL) to ~/local-repos, initializes an empty repository in ~/remote-repos.git and pushes from ~/local-repos to ~/remote-repos.git all branches.
git clone 'https://github.com/nhnc-nginx/apache2nginx' ~/local-repos git init --bare ~/remote-repos.git cd ~/local-repos git remote add mirror-server ~/remote-repos.git git push --mirror mirror-server Later you update tracking branches (and get new ones) in your ~/local-repos with git fetch origin executed inside ~/local-repos. You can mirror everything to ~/remote-repos.git again with git push --mirror mirror-server. If you want to push a single branch (e.g. origin/gh-pages), use git push mirror-server origin/gh-pages.
Notice that https://github.com/nhnc-nginx/apache2nginx remote is named origin automatically. git fetch origin fetches accessible objects from origin repository and stores branches as tracking branches. Tracking branches are prefixed with the remote name (origin in this case). If you perform git checkout gh-pages and no gh-pages branch exists, Git performs git branch --track gh-pages origin/gh-pages before performing the checkout, which creates the gh-pages branch with upstream set to origin/gh-pages.
This was probably the source of the errors your Git reported. You fetched just origin/gh-pages and tried to push non-existent gh-pages branch. As part of checkout, gh-pages was created, so push work then.
Also notice that you are creating a mirror of your local repository, not origin. If you want to mirror your GitHub repository, you should execute git fetch origin inside the just created empty mirror with git remote add origin 'https://github.com/nhnc-nginx/apache2nginx'.
I installed XAMPP on my local machine. I had previously installed MySQL along with Mysql Workbench. Couple of questions:
I am running Windows 7. I am new with this and I am trying to use CakePHP and Xampp for a project and I am not sure how the previous installation of Mysql may conflict with Xampp. Thank you.
-21656677 0You can still use the interval() method, just ignore its result!
final Producer producer = ...; int n = ...; Observable<Object> obs = Observable.interval(n,TimeUnit.SECONDS) .map(new Func1<Integer,Object>() { @Override public Object call(Integer i) { return producer.readData(); } ));
-6545244 0 RichTextToolbar in GWT 2.3 I'm trying to create a RichTextArea (following the GWT Showcase : link )
When I do a code completion of RichTextToolbar, I'm not able to find it. Is this an external library?
And then I googled and found this : google code link. Is this the same library in the Google Showcase? Or is the RichTextToolbar is an old implementation that not being brought to version 2.3?
Update:I tested this and what I feel is although the implementation the same, the UI looks different though.
-15772057 0Only solution I found is to downgrade to CRM SDK version 1.0 (not 1.1 from current release). Then in VS 2010 works.
-15732208 0Further, it may interest you, the location where Google Drive stores offline docs in Android's file system.
sdcard/android/data/com.google.android.apps.docs/
File: test.jsx compiles to bundle.js using Gulp and Browserify.
File: test.jsx:
var $ = require('jquery'); $("div#addTagModal").modal("hide"); In browser when I load the page I get this error:
Uncaught TypeError: undefined is not a function On this line:
$("div#addTagModal").modal("hide"); I have no clue what is wrong. :/
$.ajax works fine so I assume that jQuery is loaded properly.
Bootstrap is included in html using a script tag and I have checked the ID of modal.
I have a button that once clicked opens that modal:
<button className="btn btn-success" data-toggle="modal" href="#addTagModal" type="button"> <i class="icon-plus"></i> </button> Any ideas?
This is my gulp task:
gulp.task('browserify', function() { gulp.src('app/assets/js/main.js') .pipe(browserify({ debug : true, transform: ['reactify'] })) .on('error', gutil.log) .pipe(rename('public/js/bundle.js')) .pipe(gulp.dest('./')) }); And in main.js I have this code:
var app = require('./test.jsx');
-34694547 0 Memory at runtime I have a problem which says I have to read an unknown number of text lines from a file in an array of pointers and allocate memory at runtime.
#include <stdio.h> #include <stdlib.h> int main() { FILE *fp = fopen("file.txt","r"); char *arrp[10]; int i=1; while(!feof(fp)) { arrp[i]=malloc(sizeof(char)*51); fgets(arrp[i],51,fp); i++; } return 0; } I wrote this program but I don't know how to do it without initializing the array first (*arrp[10]).
-12264142 0Try to use regex pattern
/(?=.*?(?<!@ )(\b\w+\b)).*\(@.*\1.*\)/ See this test code.
-4837977 0 Show blog posts in sidebar (rails 3)I want create a blog posts list in the sidebar.
My BlogsController
def bloglist @blog = Blog.all render 'bloglist' end And I call bloglist.html.erb in layout/application.html.erb:
<%= render "blogs/bloglist" %> After, I got missing template error:
Missing partial blogs/bloglist with {:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml], :formats=>[:html], :locale=>[:en, :en]} in view paths...
Whats wrong?
-8857572 0 Prolog - Help fixing a ruleI have a database full of facts such as:
overground(newcrossgate,brockley,2). overground(brockley,honoroakpark,3). overground(honoroakpark,foresthill,3). overground(foresthill,sydenham,2). overground(sydenham,pengewest,3). overground(pengewest,anerley,2). overground(anerley,norwoodjunction,3). overground(norwoodjunction,westcroydon,8). overground(sydenham,crystalpalace,5). overground(highburyandislington,canonbury,2). overground(canonbury,dalstonjunction,3). overground(dalstonjunction,haggerston,1). overground(haggerston,hoxton,2). overground(hoxton,shoreditchhighstreet,3). example: newcrossgate to brockley takes 2 minutes.
I then created a rule so that if I enter the query istime(newcrossgate,honoroakpark,Z). then prolog should give me the time it takes to travel between those two stations. (The rule I made is designed to calculate the distance between any two stations at all, not just adjacent ones).
istime(X,Y,Z):- istime(X,Y,0,Z); istime(Y,X,0,Z). istime(X,Y,T,Z):- overground(X,Y,Z), T1 is T + Z. istime(X,Y,Z):- overground(X,A,T), istime(A,Y,T1), Z is T + T1. istime(X,Y,Z):- overground(X,B,T), istime(B,X,T1), Z is T + T1. it seems to work perfectly for newcrossgate to the first couple stations, e.g newcrossgate to foresthill or sydenham. However, after testing newcrossgate to westcroydon which takes 26mins, I tried newcrossgate to crystalpalace and prolog said it should take 15 mins...despite the fact its the next station after westcroydon. Clearly somethings wrong here, however it works for most of the stations while coming up with a occasional error in time every now and again, can anyone tell me whats wrong? :S
-39126917 0Because AJAX always make request & wait response from server, we must put HTML file to web server (Apache HTTP server or NGINX), AJAX will run.
-31139129 0I use process.on(uncaughtException), because all you're really trying to do is catch the output from the error and shut the server down gracefully (and then restart). I don't see any reason to do anything more complicated than that, because by nature of the exception, you don't want your application doing anything else in that state other than shutting down.
Domains are an alternative way of dealing with this, but it's not necessarily better than using the process handler, because you're effectively writing custom logic to handle things that you aren't anticipating. It does give you finer granularity in terms of what your error handler does for different error types, but ultimately you're still potentially running your application in an unknown state after handling it. I'd rather have my application log the exception, shut down, and then i'll fix the error so it never happens again, rather than risking my user's data on a domain solution which may or may not have handled the error correctly, depending on the nuance of the error it encountered.
-4508743 0 jQuery doesn't return any API results in the Succes function of $.ajax() while using JSONPI'm having a lot of trouble getting any results out of the JSONP datatype of the jQuery $.ajax() function. This is my jQuery code:
$('#show_tweets').click(function(){ $.ajax({ type: 'get', url: 'http://api.twitter.com/1/statuses/user_timeline.json?screen_name=jquery', dataType: 'jsonp', succes: function(data) { $.each(data, function() { $('<div></div>') .hide() .append('<img src="'+ this.profile_image_url +'"/>') .append('<p>'+ this.text +'</p>') .appendTo('#tweets_gallery') .fadeIn(); }) }, error: function() { alert('Iets gaat fout!!'); } }); }); I've assigned the #show_tweets ID to a P tag. #tweets_gallery is an empty DIV. Now, I know I could also use the $.getJSON() function, but I just want to know how I can properly retrieve JSONP results with a $.ajax() request. I've clicked several times and it doesn't output anything.
Thanks in advance!
-6047724 0 PDO fetchAll array to one dimensionalthis may be a simple question but am struggling to understand how to solve it. I have a form which allows the user to select either "custom" or "all" staff" to assign to a job.
If custom is selected the user selects staff by clicking each checkbox, I then insert these into a jobs table. This produces the array below (3, 1, 10 are the staff IDs)
Array ( [0] => 3 [1] => 1 [2] => 10 ) If "all staff" is selected, I first query a select statement to get all the staff ID's from the staff table, and then insert these into the job table the same as above. However this produces the array :
Array ( [0] => Array ( [staffID] => 1 [0] => 1 ) [1] => Array ( [staffID] => 23 [0] => 23 ) [2] => Array ( [staffID] => 26 [0] => 26 ) [3] => Array ( [staffID] => 29 [0] => 29 ) ) How can I convert the array above to the first array shown?
I'm using the code below to query the database to get all the staff ID's and then inserting them.
$select = $db->prepare("SELECT staffID FROM staff"); if($select->execute()) { $staff = $select->fetchAll(); } for($i = 0; $i<count($staff); $i++) { $staffStmt = $db->prepare("INSERT INTO staffJobs (jobID, userID) VALUES (:jobID, :staffID)"); $staffStmt->bindParam(':jobID', $jobID, PDO::PARAM_INT); $staffStmt->bindParam(':staffID', $staff[$i], PDO::PARAM_INT); $staffStmt->execute(); } The first array inserts fine, however the last array inserts zeros for the staffID.
Any suggestions?
Thanks =).
-32433046 0The default dxSlideOut item template does not support the 'icon' field. So, you can use the menuTemplate option to define icon for a menu item.
<div data-options="dxTemplate:{ name:'menuItem' }"> <span data-bind="attr: {'class': 'dx-icon-' + icon}"></span> <span data-bind="text: text"></span> </div> I've created a small fiddle here - http://jsfiddle.net/dfc2ggck/1/
Also, be sure your icon exists in the DevExtreme Icon Library.
-26598833 0 Using a UIScrollView to change the alpha of an imageMy aim is to effectively use a UIScrollView as a UISlider.
I've managed to code a UISlider to change the alpha of an image however I want to code a scrollview to change the alpha of an image when it is scrolled.
I think I'm on the right lines by using the scroll views content offset to adjust alpha balances in the scroll view delegate but I just can't seem to get the code to work!
Any suggestions on how I can get do this?
Thanks
-32163675 0Is "05 - Listen to the Man_[plixid.com]" an asset within your project? If not I believe that's why this won't work. I'm pretty sure Resources.Load is just for loading your existing assets into RAM, so that they're ready when you need them.
I did a bit of looking around, and you might find this thread useful, as well as this page from the Unity reference docs.
Here's a sample of JS from there that should do the trick. Hopefully you can translate into C# easily enough if that's what you prefer :)
var www = new WWW ("file://" + Application.dataPath.Substring (0, Application.dataPath.LastIndexOf ("/")) + "/result.wav"); AudioClip myAudioClip= www.audioClip; while (!myAudioClip.isReadyToPlay) yield return www; gameObject.GetComponent<AudioSource> ().audio.clip = myAudioClip; audio.Play ();
-8190300 0 a.toString() does not do what you think it does.
Use TextView a = (TextView)findViewById(R.id.authentication); (a.getText().equals(""))
i think that you have to add following configuration:
sonar.forceAuthentication=true ldap.bindDn=[YOURLDAPSERVICEUSER] ldap.bindPassword=[YOURLDAPSERVICEUSERPWD] ldap.user.baseDn=ou=[YOUROU],dc=[DOMAINNAME] ldap.user.request=(&(objectClass=user)(sAMAccountName={login})) you should not change last line but you have to replace parameters which marked with []
-24424704 0You can't type cast int to byte implicitly. Call method as:
sum(1, (byte)2);
-23949360 0 If you are referring to the mangled key of files array then it's raw infohash - check out the spec:
I am going through a TCPDUMP file (in .txt format) and trying to pull out any line that contains the use of the "word" V.I.D.C.A.M. It is embedded between a bunch of periods and includes periods which is really screwing me up, here is an example:
E..)..@.@.8Q...obr.f...$[......TP..P<........SMBs......................................NTLMSSP.........0.........`b.m..........L.L.<...V.I.D.C.A.M.....V.I.D.C.A.M.....V.I.D.C.A.M.....V.I.D.C.A.M.....V.I.D.C.A.M..............W.i.n.d.o.w.s. .5...1...W.i.n.d.o.w.s. .2.0.0.0. .L.A.N. .M.a.n.a.g.e.r..
How do you handle something like that?
-13424379 0 How do I get browsers to trust self-signed certificates for testing? Website address is slightly different than fully qualified domain nameI have a website that is being configured with SSL, and I am using a self-signed certificate for testing purposes, for now. The machine is running Windows 2008 R2 with IIs 7.5 and Apache Tomcat 5.5.
The problem is FireFox is gives the error that the connection is untrusted because it's a self-signed certificate and it also says that the site is using an invalid security certificate. I tried importing the certificate into Firefox, to remedy the situation, and it did not help. However, with IE, exporting the certificate from IIS and importing it into the browser's Trusted Root Certificate Authorities store permitted IE to trust the self-signed certificate.
It's important to note that the server's fully qualified domain name is webdev.dev.mysite.com, whereas the website address is webdev.mysite.com and I've had no problems with the site under HTTP. And with the help of the site here, I setup the self-signed certificate such that it's name is webdev.mysite.com.
How can I get Firefox to trust the self-signed certificate?
Thank you very much for any help.
-4942312 0JS Beautifier will both reformat and unpack:
-32731449 0Use range.setValues, is the best choice. Works for any range in any sheet, as far as the origin and destination range are similar.
Here's a sample code:
function openCSV() { //Buscamos el archivo var files = DriveApp.getFilesByName("ts.csv"); //Cada nombre de archivo es unico, por eso next() lo devuelve. var file = files.next(); fileID = file.getId(); //Abrimos la spreadsheet, seleccionamos la hoja var spreadsheet = SpreadsheetApp.openById(fileID); var sheet = spreadsheet.getSheets()[0]; //Seleccionamos el rango var range = sheet.getRange("A1:F1"); values = range.getValues(); //Guardamos un log del rango //Logger.log(values); //Seleccionamos la hoja de destino, que es la activeSheet var ss = SpreadsheetApp.getActiveSpreadsheet(); var SSsheet = ss.getSheets()[0]; //Seleccionamos el mismo rango y le asignamos los valores var ssRange = SSsheet.getRange("A1:F1"); ssRange.setValues(values); }
-24450377 0 I managed to sort this so including the answer for anyone else who runs into this error message.
The error: unexpected TOK_IDENT basically means that a field referenced in the query doesn't exist in the index.
The best way to verify what's in your index is to run the Sphinx CLI using:
mysql -P9306 --protocol=tcp --prompt='sphinxQL> ' And run a SELECT * query like:
SELECT * FROM your_index_core WHERE sphinx_deleted = 0 LIMIT 0, 20; From here you can see the fields in the index across the top.
I can't figure out why they didn't exist in the index - I'd ran rake ts:rebuild multiple times to no avail. In the end I had to stop searchd, manually delete the configuration file and indexes and rebuild from scratch.
Change the imgs display to block
a { display:inline-block; } a img { display:block; } See this jsfiddle
So what does it do? The image inside the link has a default display of inline-block. The a you set to display:inline-block. It's the combination of the two in combination with whitespace inside the a element, that does the problem.
You can simulate with two nested inline-block divs which has the dimensions set only on the inner one. http://jsfiddle.net/TLBEx/4/
Below regex can match any type of number, remember, I have assumed + to be optional. However it does not handle number counting
^\+?(\d[\d-. ]+)?(\([\d-. ]+\))?[\d-. ]+\d$ Here are some valid numbers you can match:
+91293227214 +3 313 205 55100 99565433 011 (103) 132-5221 +1203.458.9102 +134-56287959 (211)123-4567 111-123-4567
-40699244 0 You would indeed use whatever server side configuration options are available to you.
Depending on how your hosting is set up you could either modify the include path for PHP (http://php.net/manual/en/ini.core.php#ini.include-path) or restricting the various documents/directories to specific hosts/subnets/no access in the Apache site configuration (https://httpd.apache.org/docs/2.4/howto/access.html).
If you are on shared hosting, this level of lock down isn't usually possible, so you are stuck with using the Apache rewrite rules using a combination of a easy to handle file naming convention (ie, classFoo.inc.php and classBar.inc.php), the .htaccess file and using the FilesMatch directive to block access to *.inc.php - http://www.askapache.com/htaccess/using-filesmatch-and-files-in-htaccess/
FWIW all else being equal the Apache foundation says it is better/more efficient to do it in server side config vs. using .htaccess IF that option is available to you.
-12221252 0 How pinterest type url's workWhen we click on pinterest pin the url changes to pinterest.com/pin/[pinid] But how come it happens without full loading of the page and only the url is changed.

Google has actually since added a method for receiving bounced messages via an HTTP Request. It requires adding to your app.yaml:
inbound_services: - mail_bounce Which will cause a request to hit /_ah/bounce each time a bounce is received. You can then handle the bounce by adding a handler for it. See the section there on Handling Bounce Notifications for more details on how to glean the additional information from those requests.
In order to be able to use DMA, the buffers should be in page-locked memory. AMD and NVIDIA state in their programming guide that to have a buffer in page-locked memory it should be created with the CL_MEM_ALLOC_HOST_PTR flag. Here is what NVIDIA says in the section 3.3.1 of its guide:
OpenCL applications do not have direct control over whether memory objects are allocated in page-locked memory or not, but they can create objects using the CL_MEM_ALLOC_HOST_PTR flag and such objects are likely to be allocated in page-locked memory by the driver for best performance.
Note the "likely" in bold.
Which OS? NVIDIA doesn't speak about the OS so any OS NVIDIA provides drivers for (the same for AMD).
Which Hardware? Any having DMA controller I guess.
Now to write only a part of a buffer you could have a look to the function:
clEnqueueWriteBufferRect() This function allow to write to a 2 or 3D region of a buffer. Another possibility would be to use sub buffers creating them with the function:
clCreateSubBuffer() However there is no notion of 2D buffer with it.
-25455225 0You could either use setInterval:
window.setInterval(jTTrackPage, 10000); // call it every 10 000 ms = 10 s or setTimeout:
function trackPage() { jTTrackPage(); window.setTimeout(trackPage), 10000); // call the function again in 10 000 ms } trackPage(); The difference between both is that the first one calls it every 10s, and if one call takes more than 10s (unlikely here) the next one will be triggered just after, without waiting 10s. The second solution solves this problem.
You can clear an interval or a timeout using respectively clearInterval and clearTimeout:
var interval = window.setInterval(jTTrackPage, 10000); window.clearInterval(interval); // <-- stop it var timeout = window.setTimeout(trackPage, 10000); window.clearTimeout(timeout); // <-- stop it
-26811906 0 Swift is designed to take advantage of optional value's and optional unwrapping.
You could also declare the array as nil, as it will save you a very small (almost not noticable) amount of memory.
I would go with an optional array instead of an array that represents a nil value to keep Swift's Design Patterns happy :)
I also think
if let children = children { } looks nicer than :
if(children != nil){ }
-22412698 0 Optimizing hand-evaluation algorithm for Poker-Monte-Carlo-Simulation I've written an equilator for Hold'em Poker as a hobbyproject. It works correctly, but there is still one thing I am not happy with: In the whole process of simulating hands, the process of evaluating the hands takes about 35% of the time. That seems to be pretty much to me compared with what else has to be done like iterating through and cloning large arrays and stuff.
Any idea of how to get this more performant would be great.
This is the code:
private static int getHandvalue(List<Card> sCards) { // --- Auf Straight / Straight Flush prüfen --- if ((sCards[0].Value - 1 == sCards[1].Value) && (sCards[1].Value - 1 == sCards[2].Value) && (sCards[2].Value - 1 == sCards[3].Value) && (sCards[3].Value - 1 == sCards[4].Value)) { if ((sCards[0].Color == sCards[1].Color) && (sCards[1].Color == sCards[2].Color) && (sCards[2].Color == sCards[3].Color) && (sCards[3].Color == sCards[4].Color)) return (8 << 20) + (byte)sCards[0].Value; // Höchste Karte Kicker else return (4 << 20) + (byte)sCards[0].Value; // Höchste Karte Kicker (Straight) } // --- Auf Wheel / Wheel Flush prüfen --- if ((sCards[4].Value == Card.CardValue.Two) && (sCards[3].Value == Card.CardValue.Three) && (sCards[2].Value == Card.CardValue.Four) && (sCards[1].Value == Card.CardValue.Five) && (sCards[0].Value == Card.CardValue.Ace)) { if ((sCards[0].Color == sCards[1].Color) && (sCards[1].Color == sCards[2].Color) && (sCards[2].Color == sCards[3].Color) && (sCards[3].Color == sCards[4].Color)) return(8 << 20) + (byte)sCards[1].Value; // Zweithöchste Karte Kicker else return(4 << 20) + (byte)sCards[1].Value; // Zweithöchste Karte Kicker (Straight) } // --- Auf Flush prüfen --- if ((sCards[0].Color == sCards[1].Color) && (sCards[1].Color == sCards[2].Color) && (sCards[2].Color == sCards[3].Color) && (sCards[3].Color == sCards[4].Color)) return (5 << 20) + ((byte)sCards[0].Value << 16) + ((byte)sCards[1].Value << 12) + ((byte)sCards[2].Value << 8) + ((byte)sCards[3].Value << 4) + (byte)sCards[4].Value; // --- Auf Vierling prüfen --- if (((sCards[0].Value == sCards[1].Value) && (sCards[1].Value == sCards[2].Value) && (sCards[2].Value == sCards[3].Value)) || ((sCards[1].Value == sCards[2].Value) && (sCards[2].Value == sCards[3].Value) && (sCards[3].Value == sCards[4].Value))) return (7 << 20) + (byte)sCards[1].Value; // Wert des Vierlings (keine Kicker, da nicht mehrere Spieler den selben Vierling haben können) // --- Auf Full-House / Drilling prüfen --- // Drilling vorne if ((sCards[0].Value == sCards[1].Value) && (sCards[1].Value == sCards[2].Value)) { // Full House if (sCards[3].Value == sCards[4].Value) return (6 << 20) + ((byte)sCards[0].Value << 4) + (byte)sCards[3].Value; // Drilling (höher bewerten) // Drilling return (3 << 20) + ((byte)sCards[0].Value << 8) + ((byte)sCards[3].Value << 4) + (byte)sCards[4].Value; // Drilling + Kicker 1 + Kicker 2 } // Drilling hinten if ((sCards[2].Value == sCards[3].Value) && (sCards[3].Value == sCards[4].Value)) { // Full House if (sCards[0].Value == sCards[1].Value) return (6 << 20) + ((byte)sCards[2].Value << 4) + (byte)sCards[0].Value; // Drilling (höher bewerten) // Drilling return (3 << 20) + ((byte)sCards[2].Value << 8) + ((byte)sCards[0].Value << 4) + (byte)sCards[1].Value; // Drilling + Kicker 1 + Kicker 2 } // Drilling mitte if ((sCards[1].Value == sCards[2].Value) && (sCards[2].Value == sCards[3].Value)) return (3 << 20) + ((byte)sCards[1].Value << 8) + ((byte)sCards[0].Value << 4) + (byte)sCards[4].Value; // Drilling + Kicker 1 + Kicker 2 // --- Auf Zwei Paare prüfen --- // Erstes Paar vorne, zweites Paar mitte if ((sCards[0].Value == sCards[1].Value) && (sCards[2].Value == sCards[3].Value)) return (2 << 20) + ((byte)sCards[0].Value << 8) + ((byte)sCards[2].Value << 4) + (byte)sCards[4].Value; // Erstes Paar + Zweites Paar + Kicker // Erstes Paar vorne, zweites Paar hinten if ((sCards[0].Value == sCards[1].Value) && (sCards[3].Value == sCards[4].Value)) return (2 << 20) + ((byte)sCards[0].Value << 8) + ((byte)sCards[3].Value << 4) + (byte)sCards[2].Value; // Erstes Paar + Zweites Paar + Kicker // Erstes Paar mitte, zweites Paar hinten if ((sCards[1].Value == sCards[2].Value) && (sCards[3].Value == sCards[4].Value)) return (2 << 20) + ((byte)sCards[1].Value << 8) + ((byte)sCards[3].Value << 4) + (byte)sCards[0].Value; // Erstes Paar + Zweites Paar + Kicker // --- Auf Paar prüfen --- // Paar vorne if (sCards[0].Value == sCards[1].Value) return (1 << 20) + ((byte)sCards[0].Value << 12) + ((byte)sCards[2].Value << 8) + ((byte)sCards[3].Value << 4) + (byte)sCards[4].Value; // Paar + Kicker 1 + Kicker 2 + Kicker 3 // Paar mitte-vorne if (sCards[1].Value == sCards[2].Value) return (1 << 20) + ((byte)sCards[1].Value << 12) + ((byte)sCards[0].Value << 8) + ((byte)sCards[3].Value << 4) + (byte)sCards[4].Value; // Paar + Kicker 1 + Kicker 2 + Kicker 3 // Paar mitte-hinten if (sCards[2].Value == sCards[3].Value) return (1 << 20) + ((byte)sCards[2].Value << 12) + ((byte)sCards[0].Value << 8) + ((byte)sCards[1].Value << 4) + (byte)sCards[4].Value; // Paar + Kicker 1 + Kicker 2 + Kicker 3 // Paar hinten if (sCards[3].Value == sCards[4].Value) return (1 << 20) + ((byte)sCards[3].Value << 12) + ((byte)sCards[0].Value << 8) + ((byte)sCards[1].Value << 4) + (byte)sCards[2].Value; // Paar + Kicker 1 + Kicker 2 + Kicker 3 // --- High Card bleibt übrig --- return ((byte)sCards[0].Value << 16) + ((byte)sCards[1].Value << 12) + ((byte)sCards[2].Value << 8) + ((byte)sCards[3].Value << 4) + (byte)sCards[4].Value; // High Card + Kicker 1 + Kicker 2 + Kicker 3 + Kicker 4 } This method returns an exact value for every sorted 5-Card-Combination in poker. It gets called by another method:
private static int getHandvalueList(List<Card> sCards) { int count = sCards.Count; if (count == 5) return getHandvalue(sCards); int HighestValue = 0; Card missingOne; int tempValue; for (int i = 0; i < count - 1; i++) { missingOne = sCards[i]; sCards.RemoveAt(i); tempValue = getHandvalueList(sCards); if (tempValue > HighestValue) HighestValue = tempValue; sCards.Insert(i, missingOne); } missingOne = sCards[count - 1]; sCards.RemoveAt(count - 1); tempValue = getHandvalueList(sCards); if (tempValue > HighestValue) HighestValue = tempValue; sCards.Add(missingOne); return HighestValue; } This recursive method returns the highest value of all possible 5-card-combinations. And this one gets called by the final public method:
public static int GetHandvalue(List<Card> sCards) { if (sCards.Count < 5) return 0; sCards.Sort(new ICardComparer()); return getHandvalueList(sCards); } It gets delivered a maximum of 7 cards.
Update
So far: Each time, the public function gets called with 7 cards (which is the case most of the time), it has to call the hand-evaluation method 21 times (one time for every possible 5-card-combo).
I thought about caching the value for each possible set of 5 to 7 cards in a hashtable und just look it up. But if I am not wrong, it would have to store more than 133.784.560 32-bit-integer values, which is about 500MB.
What could be good hashfunction to assign every possible combination to exactly one arrayindex?
Created a new question on that: Hashfunction to map combinations of 5 to 7 cards
Update: For further improvement regarding the accepted answer, have alook at: Efficient way to randomly select set bit
-27426305 0 Edmodo android image cropper, fix aspect ratioI've some problem using edmodo/cropper library on android lollipop. My app should take some pictures, and after each picture is taken, user should crop a square image. this is my layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <com.example.newapicamera.AutoFitTextureView android:id="@+id/texture" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/footer" /> <com.edmodo.cropper.CropImageView xmlns:custom="http://schemas.android.com/apk/res-auto" android:id="@+id/CropImageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/footer" android:visibility="invisible" /> <ImageView android:id="@+id/footer" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:src="@drawable/footer" /> <TextView android:id="@+id/current_picture" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:textColor="#FFFFFF" android:textSize="30sp" /> and this is how i launch library for crop after picture is taken;
crop_view.setImageBitmap(bitmap); mCameraDevice.close(); mTextureView.setVisibility(View.INVISIBLE); crop_view.setVisibility(View.VISIBLE); DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); int dpWidth = displayMetrics.widthPixels; crop_view.setFixedAspectRatio(true); crop_view.setAspectRatio(dpWidth, dpWidth); I have the sequent problem:
found the solution. this seems to work great http://gridster.net
-27501263 0The characters that represent decimal digits are laid out in ASCII space in numerical order.
'0' is ASCII 0x30'1' is ASCII 0x31'2' is ASCII 0x32This means that you can simply subtract '0' from your character to get the value you desire.
char a = ...; if (a >= '0' && a <= '9') { int digit = a - '0'; // do something with digit }
-20298283 0 MVVM approach, what's a good way? How to improve/speed up development? this post is meant to have a list of suggestions on MVVM approach... What tools do you use, what do you do to speed up development, how do you maintain your application, any special ways of finding defects in this design pattern......
here is what I do:
So first i create my model/db with EF.
Then I create Views (either user controls or windows) with their respective viewmodel. I usually place the viewmodel in the same location as my view. But while starting the name of my view with "UC-name", I call my viewmodel just "name-model".
In my viewmodel I implement InotifyPropertyChanged
in my xaml view I have a resource of my viewmodel, and bind my grids/controls via the itemsource to the staticresource.
I try to do a lot of front end logic with triggers and styles and also place some code in the xaml.cs file if it regards logic for behaviour of my controls.
I can reach my viewmodel from my view (xaml + xaml.cs).
for communiation between viewmodels I use MVVM lights.
that's pretty much it.
Things I'm thinking about
I'm thinking of using T4 templates for generating viewmodel/view. What do you guys think of this. is this worth it?
when using MVVM light Messenger, we get a subscription based communication, and sometimes I find it hard to track what has changed in my DataContext. Any suggestions on this?
any other improvements or suggestions are more than welcome !
Straight from Phonegap website -
PhoneGap is an HTML5 app platform that allows you to author native applications with web technologies and get access to APIs and app stores.
What this means is it is not browser dependent. The code compiles to native application. You don't need a browser to run it.
-6099466 0You could use a make file to generate the .i files first, run your processing on them, then compile them.
-17192485 0There have been numerous posts on here about trying to do OCR on camera generated images. The problem is not that the resolution is too low, but that its too high. I cannot find a link right now, but there was a question a year or so ago where in the end, if the image size was reduced by a factor of four or so, the OCR engine worked better. If you examine the image in Preview, what you want is the number of pixels per character to be say 16x16 or 32x32, not 256x256. Frankly I don't know the exact number but I'm sure you can research this and find posts from actual framework users telling you the best size.
Here is a nice response on how to best scale a large image (with a link to code).
-8302923 0 new created UIImageViews do not show up when added as subviewupon a tap, I want to let a few UIImageView objects appear on an underlaying UIView. So I created the following action:
- (IBAction)startStars: (id) sender { UIView* that = (UIView*) sender; // an UIButton, invisible, but reacting to Touch Down events int tag = that.tag; UIView* page = [self getViewByTag:mPages index:tag]; // getting a page currently being viewed if ( page != nil ) { int i; UIImage* image = [UIImage imageNamed:@"some.png"]; for ( i = 0 ; i < 10 ; ++i ) { // create a new UIImageView at the position of the tapped UIView UIImageView* zap = [[UIImageView alloc] initWithFrame:that.frame]; // assigning the UIImage zap.image = image; // make a modification to the position so we can see all instances CGPoint start = that.layer.frame.origin; start.x += i*20; zap.layer.position = start; [page addSubview:zap]; // add to the UIView [zap setNeedsDisplay]; // please please redraw [zap release]; // release, since page will retain zap } [image release]; } } Unfortunately, nothing shows up. The code gets called, the objects created, the image is loaded, even the properties are as expected. Page itself is a real basic UIView, created with interface builder to contain other views and controls.
Still, nothing of this can be seen....
Has anyone an idea what I am doing wrong? Do I need to set the alpha property (or others)?
Thanks
Zuppa
-36526756 0You can use:
private float x; public float X { get { return x; } } Now you only set x from within your class.
-10701272 0 iTextSharp cyrillic lettersI used http://www.codeproject.com/Articles/260470/PDF-reporting-using-ASP-NET-MVC3 to generate pdf files from my razor views and it works great but i can't display cyrillic letters like č,ć . I tried everything and i can't get it working.
I must somehow tell the HtmlWorker to use different font:
using (var htmlViewReader = new StringReader(htmlText)) { using (var htmlWorker = new HTMLWorker(pdfDocument)) { htmlWorker.Parse(htmlViewReader); } } Can you help?
EDIT:
I was missing one line
styleSheet.LoadTagStyle(HtmlTags.BODY, HtmlTags.ENCODING, BaseFont.IDENTITY_H); The rest was the same as the answer.
-4615607 0Famous Game of Life seems to be a good idea. Cells are persistence units, JSF, web beans + ejb to display the working area, scheduled beans - to put it in motion. Game's logic can be implemented in EJB or JMS (or even both). You could extend original logic, introduce new objects or rules and finally get Nobel prize for achievements in social modeling :)
-741437 0Add @Key(types=String.class) @Value(types=String.class)
since "Properties" is a bit of a hack in that it can also contain non-String, and doesn't allow generic specification so you need to restrict it. The next version of AppEngine will have a version of DataNucleus that doesn't require this additional info.
-7426257 0Task Manager is one way to do it. I prefer Process Explorer because it gives a lot more info than Task Manager.
-902480 0 Error parsing .dae,Error#1009 in flash player,Augmented Reality flashWhenever I am trying to use an animate.dae file(I am creating small project using flartoolkit+papervision3d+ascollada) .The flash player is reporting me the errors pasted below.If I am pressing continue then I can see my .dae file but without animation :( And Please note that I am not using any heavy animation.
ERROR:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at org.papervision3d.objects.parsers::DAE/buildAnimationChannels()[C:..\org\papervision3d\objects\parsers\DAE.as:657]
at org.papervision3d.objects.parsers::DAE/onParseAnimationsComplete()[C:..\org\papervision3d\objects\parsers\DAE.as:1722]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at org.ascollada.io::DaeReader/loadNextAnimation()[C:..\Libs\org\ascollada\io\DaeReader.as:169]
at flash.utils::Timer/_timerDispatch()
at flash.utils::Timer/tick()
-14842016 0To achieve a pause of x milliseconds between each restart:
myAnimation.setAnimationListener(new AnimationListener(){ @Override public void onAnimationStart(Animation arg0) { } @Override public void onAnimationEnd(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { myAnimation.setStartOffset(x); } });
-2480477 0 Is there a way to override java.io.File to perform the file path translation with custom code? In this case, I would translate the remote paths to a mount point
Yes, you can perform your own implementation of java.io.File and place it in a separate jar and then load it instead of the real java.io.File.
To have the JVM load it you can either use the java.endorsed.dirs property or java -Xbootclasspath/p:path option in the java launcher ( java )
BUT!!!
Creating your own version of the java.io.File class won't be as easy as modifying the legacy source code.
If you're afraid of breaking something you could first extract all your hardcoded paths to use a resource bundle:
So:
File file = new File("C:\\Users\\oreyes\\etc.txt"); Would be:
File file = new File( Paths.get( "user.dir.etc" )); And Paths would have a resource bundle internally
class Paths { private static ResourceBundle rs = ResourceBundle.getBundle("file.paths"); public static String get( String key ) { rs.getString( key ); } } You can have all this hardcoded paths extraction with an IDE ( usually an internationalization plugin )
Provide a different resource bundle for Linux and your done. Test and re-test and re-test
So, use provide your own java.io.File only as a last resource.
I'm using python2.7 to define a function like this
def foo(*args, **kwargs): print 'args = ', args print 'kwargs = ', kwargs print '---------------------------------------' and by calling foo(3), the output is as the following:
args = (3,) kwargs = {} which is desired.
But as for __init__ function in a class in which the parameters are the same form as foo, I can't instantize the class Person by invoking Person(3)
def Person(): def __init__(self, *args, **kwargs): print args print kwargs x = Person(3) The output is
x = Person(3) TypeError: Person() takes no arguments (1 given) That confused me a lot, have I missed something?
-3883227 0There are several problems you need to address — both in your code and both in your current knowledge :-) Start with this:
Read a few articles about ASP.NET's page life-cycle, so you become more familiar with what to do in each life-cycle event handler (OnInit, OnLoad, …). Good starting point might be this MSDN overview. However, google for “ASP.NET page life cycle” and read a few other articles and examples as well.
Also, you will need to get familiar with the request-response nature of ASP.NET page processing. In the beginning, bear in mind that when the user hits some 'Submit' button which in turn causes an HTTP POST request to occur, you are responsible to creating the page's control tree to match its structure, IDs, etc. as they were in the previous request. Otherwise ASP.NET doesn't know how in which controls to bind the data the user filled-in.
Near the line tagged //Lost and confused here :/ you are creating a new control and immediately querying it for the 'results' (which I expect to be values of some edit boxes within it). This cannot work, because it's most probably too early for the form to have the data received from the Page object that drives the request processing.
Your Results property is poorly designed. First, you shouldn't be using properties that actually 'generate' data in such a way they can change without notice. Properties shall be used as “smart fields”, otherwise you end up with less manageable and less readable code. Second, the setter you left there like “set;” causes any value assigned into the property to be actually lost, because there's no way to retrieve it. While in some rare cases this behavior may be intentional, in your case I guess it's just an error.
So, while you can currently leave behind any “good OOP way” to approach your problem, you certainly should get more familiar with the page life-cycle. Understanding it really requires some thinking about the principles how ASP.NET web applications are supposed to work, but I'm sure it will provide you with the kick forward you actually need.
UPDATE: In respect to Tony's code (see comments) the following shall be done to move the code forward:
The list of form data in the requestForm property shall have tuple of [form ASCX path, control ID, the actual RequestForm data class]
GatherForms shall be called only when the page is initially loaded (i.e. if (Page.IsPostBack)) and it shall fill requestForm with the respective tuples for available ASCX forms.
Both chklApplications and wizard steps shall be created in LoadForms on the basis of requestForm's content.
When results are to be gathered, the ID stored in the respective requestForm entry can be used to look-up the actual user control.
I have following query:
SELECT DISTINCT(a1.actor) FROM actions a1 JOIN actions a2 ON a1.ip = a2.ip WHERE a2.actor = 143 AND a2.ip != '0.0.0.0' AND a2.ip != '' AND a2.actor != a1.actor AND a1.actor != 0 This is the explain of the query:
+----+-------------+-------+-------+------------------+---------+---------+------------------+------+--------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+-------+------------------+---------+---------+------------------+------+--------------------------+ | 1 | SIMPLE | a2 | range | actor,ip,actorIp | actorIp | 66 | NULL | 3800 | Using where; Using index | | 1 | SIMPLE | a1 | ref | ip | ip | 62 | formabilio.a2.ip | 11 | Using where | +----+-------------+-------+-------+------------------+---------+---------+------------------+------+--------------------------+ Even if from this it doesn't seem a problematic query, in my machine it takes more or less 69 seconds with MyIsam and 56 seconds in InnoDB. The table has more or less 1 thousand records. As you can see from the explain I have indeces both on the actor column, on the ip column and even on both columns. I have mysql version 5.5.35.
Do you have any idea on why this query takes so long? How can I optimize it?
-33198428 1 jwt: 'module' object has no attribute 'encode'I am getting Module not found error when using jwt. Here is how I declared it:
def create_jwt_token(): payload = { "iat": int(time.time()) } shared_key = REST_API_TOKEN payload['email'] = EMAIL payload['password'] = PASSWORD jwt_string = jwt.encode(payload, shared_key) encoded_jwt = urllib.quote_plus(jwt_string) # url-encode the jwt string return encoded_jwt The error message says encode is not found in jwt. I did a tab on jwt and found that the encode is a method inside jwt.JWT. I tried changing it to
jwt_string = jwt.JWT.encode(payload, shared_key) and it gives an error "unbound method encode() must be called with JWT instance as first argument (got dict instance instead)"
What am I doing it wrong? Here is the version info of my python environment:
2.7.10 |Anaconda 2.3.0 (64-bit)| (default, May 28 2015, 16:44:52) [MSC v.1500 64 bit (AMD64)]
-4071677 0There are wrappers to inotify that make it easy to use from high-level languages. For example, in ruby you can do the following with rb-inotify:
notifier = INotify::Notifier.new # tell it what to watch notifier.watch("path/to/foo.txt", :modify) {puts "foo.txt was modified!"} notifier.watch("path/to/bar", :moved_to, :create) do |event| puts "#{event.name} is now in path/to/bar!" end There's also pyinotify but I was unable to come up with an example as concise as the above.
-8804373 0For the XSLT part I recommend using the "Fill-in the blasnks" technique -- see a simple example here: http://stackoverflow.com/a/8674694/36305.
The form skeleton will look like this:
<form name="formRoot" xmlns:gen="my:gen"> <gen:name/> </form> The XSLT code will contain a template matching gen:name that produces:
<p>Name</p><input name="name" value="Name"/> The URL to the form-skeleton is passed as an external parameter to the XSLT transformation.
The source XML document (URL or itself) is passed as another external parameter.
Thus the XSLT transformation can process any source XML document and insert the results of processing into any form-skeleton document.
-33541643 0java.lang.NoSuchMethodException: <init> [class android.content.Context, interface android.util.AttributeSet] Your HackySwipeBackLayout is missing a constructor:
public HackySwipeBackLayout(Context context, AttributeSet attrs) { super(context, attrs); } If you look more closely at the HackyViewPager, you'll notice that it is in there too. As a matter of fact, any view that needs to support inflating from xml should have this constructor defined. You may find the documentation on how to create custom views helpful too.
Edit: since your intention is to catch the exception thrown, make sure to catch the ArrayIndexOutOfBoundsException accordingly:
@Override public boolean onInterceptTouchEvent(MotionEvent ev) { try { return super.onInterceptTouchEvent(ev); } catch (ArrayIndexOutOfBoundsException e) { e.printStackTrace(); return false; } } That should stop your app from crashing on this particular exception, but is of course not a 'fix' for the underlying issue that is causing the ArrayIndexOutOfBoundsException to be thrown in the first place. It may or may not lead to the desired behaviour. Either way, consider opening a ticket with the maintainer of the SwipeBack repo.
adb is not in your PATH.
Bash will first try to look for a binary called adb in your Path, and not in the current directory. Therefore, if you are currently in the platform-tools directory, just call
./adb --help The dot is your current directory, and this tells Bash to use adb from there.
Otherwise, you can add platform-tools to your PATH, by placing a line like this in your ~/.profile or ~/.bash_profile, then re-starting the Terminal. On Linux, you might want to modify ~/.bashrc instead, depending on what is used.
export PATH=/Users/espireinfolabs/Desktop/soft/android-sdk-mac_x86/platform-tools:$PATH If you've installed the platform tools somewhere else, change the path accordingly. For Android Studio on OS X, for example, you'd use the following—note the double-quotes that prevent a possible space from breaking the path syntax:
export PATH="/Users/myuser/Library/Android/sdk/platform-tools":$PATH
-20760914 0 Program not asking expected number of values #include <stdio.h> main() { int n,i; FILE *fptr; fptr=fopen("f3.txt","w"); if(fptr==NULL) { printf("Error!"); exit(1); } printf("Enter n: "); for(i=0;i<=2;i++) { scanf("%d \n",&n); fprintf(fptr,"%d ",n); } fclose(fptr); return 0; } EDIT: *In the above program, I am entering 3 values, but why this is asking for 4 values? Although its writing only three times but its asking for the values 4 times. Can u tell d reason? And what to do to make it to take exact number of values which I am typing.?* thanks in advance..
So this is known that it was due to space next to %d in loop. Can someone explain Carriage Return in a little detail, I searched but could not understand exactly what that is.
-22460842 0 MySQL Query To Produce Output Per Month Based On Variable Duration EntriesOk, so I have a table that contains payments associated with dates and durations.
Example data:
purchase_id date_purchased user_id duration (in months) amount_income 1 2013-12-28 00:00:00 1 2 £15 2 2014-01-04 00:00:00 2 1 £10 3 2014-02-04 00:00:00 3 6 £40 *So the longer duration users pay for, the less they pay per month overall.
What I'm trying to display is the total income per month based on this table. So a payment of £15 over 2 months would mean £7.50 income per month for 2 months.
Sample output:
Month Amount 2013-12 £7.50 2014-01 £17.50 2014-02 £6.66 2014-03 £6.66 2014-04 £6.66 2014-05 £6.66 2014-06 £6.66 2014-07 £6.66 This output corresponds to the sample input above. Hopefully it clarifies the breakdown of the income per month.
Any ideas how to do this in a query?
-12756608 0see XMPP: http://www.amazon.com/Professional-Programming-JavaScript-jQuery-Programmer/dp/0470540710
-40139193 0Check to see if your version provides a variable named "yylineno", many of them do.
I know flex 2.6.0 does.
-24432502 0 Force Storyboard to present specific base localizationI have a story board with base localisation (The story board itself is not localised) I wish to use base locazation to localize the app and still to be able to change the localization from within the app itself.
Right now I am dong so with this approach -
+(NSString*)localizedStringForKey:(NSString*) key { NSBundle* languageBundle = [self localizationBundle]; NSString* str=[languageBundle localizedStringForKey:key value:@"" table:nil]; return str; } But this works only for dynamic strings that I assign in the code. Is there any way to force the story board to use specific base localizatio or should I give up using this option and create all the strings in code ?
Thanks SHani
-39533353 0Are you able to sort the group in Descending order? I have an idea but it will be less work for you if they're grouped newest to oldest.
WhileReadingRecords:
In each group you'll need to determine the 1st and 6th visit. (You're currently suppressing any groups with less than 6.) To do this, I would make a Shared Variable called Counter that increments by one every record and resets every time it reaches a new group. (Set it to zero in the Group Header.)
Next you'll need two more Shared Variables called FirstDate and SixthDate. These populate with the date value if Counter equals one or six respectively. Just like Counter you'll reset these every time the group changes.
WhilePrintingRecords:
If everything works, you should now have the two dates values you need for calculations. Add an additional clause in your current Suppression formula:
.... AND DateDiff("d", FirstDate, SixthDate)
-31822889 0 The css-width/-height of the canvas have to get set to something else than they would be with 100%. (e.g. 101%)
Only this (after trying 9 other methods of a redraw/repaint) induces Safari to render it correctly.
Most likely it does not work because of your match pattern:
{R:1} will only match (.*) in your pattern, and will never match files/123...files/\d+... and not /files/\d+...Try this one instead (works fine for me):
<rule name="1" stopProcessing="true"> <match url="^files/\d+/.*\.html$" /> <action type="Redirect" url="default.aspx?url={R:0}" redirectType="Permanent" /> </rule>
-9754228 0 how to initialize private members of class in c++ Hi i have a c++ class with some private members as follows
template <typename V, typename E> class Vertex { public: Vertex(); ~Vertex(); typedef std::pair<int, E> edgVertPair; typedef std::vector<edgeVertPair> vectEdges; void setVertexID(int data); int getVertexID(); void setEdgeVertPair(int vertID, E edge); edgVertPair getEdgeVertPair(); void setEdgeList(edgeVertPair edgeVert); vectEdges getEdgeList(); private: int vertexID; edgVertPair evp; vectEdges edgeList; }; Now i want to create a pair i.e. something like
evp.first="someint"; evp.second="somestring";
and then push this evp into the edgeList i.e. edgeList.push_back(evp); Now the problem is in the setter function i did something like this:
template<typename V, typename E> void Vertex<V, E>::setEdgeVertPair(int vertID, E edge){ ...populate evp;... } now i don't know how to populate the evp pair with vertID, edge.
-29532816 0 PHP - Method with parameters as a parameter to other methodI am trying to get result from this method (1st param is the service name, 2nd is method with its own parameters):
$userFacade->getSet('users', 'findBy([], [\'id\' => \'DESC\'])') This is the getSet method:
public function getSet($service, $function) { return new Set($this->$service->getRepository()->$function); } All I want to achieve is to make writing of calls of the repository's functions easier. I haven't found anything useful yet because I don't know the proper term to search for (if there is one). I just wonder whether it's possible (how?) or not (ok...).
Now I get an error:
Cannot read an undeclared property EntityRepository::$findBy([], ['id' => 'DESC'])
-20885994 0 Try this
<Grid Background="LightGray" > <Grid.Triggers> <EventTrigger RoutedEvent="MouseEnter"> <BeginStoryboard> <Storyboard > <DoubleAnimation From="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="Grid_Bd" Duration="0:0:0.1"></DoubleAnimation> </Storyboard> </BeginStoryboard> </EventTrigger> <EventTrigger RoutedEvent="MouseLeave"> <BeginStoryboard> <Storyboard > <DoubleAnimation From="1" To="0" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="Grid_Bd" Duration="0:0:0.1"></DoubleAnimation> </Storyboard> </BeginStoryboard> </EventTrigger> </Grid.Triggers> <Grid Height="50" Width="50"> <Border x:Name="TextBlock_Bd" Opacity="0" BorderBrush="Blue" BorderThickness="1"/> <TextBlock Text="Hello !!" HorizontalAlignment="Center" VerticalAlignment="Center"> <TextBlock.Triggers> <EventTrigger RoutedEvent="MouseEnter"> <BeginStoryboard> <Storyboard > <DoubleAnimation From="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="TextBlock_Bd" Duration="0:0:0.1"></DoubleAnimation> </Storyboard> </BeginStoryboard> </EventTrigger> <EventTrigger RoutedEvent="MouseLeave"> <BeginStoryboard> <Storyboard > <DoubleAnimation From="1" To="0" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="TextBlock_Bd" Duration="0:0:0.1"></DoubleAnimation> </Storyboard> </BeginStoryboard> </EventTrigger> </TextBlock.Triggers> </TextBlock> </Grid> <Border x:Name="Grid_Bd" Opacity="0" BorderBrush="Red" BorderThickness="1"/> </Grid>
-3695905 0 That's a floating point number. Unlike any other language I've ever encountered, all numbers in Javascript are actually 64-bit floating numbers. Technically, there are no native integers in Javascript. See The Complete Javascript Number Reference for the full ugly story.
-10950584 0Well, it turned out to be simpler than I thought. I decided to read the code of the plugin and modify it by commenting out the code that sorts my output.
That is when I found a variable 'sortResults:true' in defaults. So, all I needed was to set that variable to false. I didn't find this in the documentation though.
$('#search').autocomplete ( { url: "index.php", sortResults: false } )
Now the output is in the exact order that I require.
I got the idea of reading the code to find/solve the problem from here : jQuery "Autocomplete" plugin is messing up the order of my data (That isn't the same plugin)
Thanks. :)
-38540009 0 Create automatic tasks in wordpressI want to make wordpress create automatic tasks from a text file and assign them to the users. Acctually the text file should be separated in paragraphs and each paragraph should be assigned to the users as a job. What can I do? Do we have a plugin for this process?
Thanks
-6382543 0You have a couple of choices. You can isolate the common functionality into a third object that Class1 and Class2 share (aggregation), or you can actually create a hierarchy of objects (inheritance). I'll talk about inheritance here.
JavaScript doesn't have classes, it's a prototypical language. An object instance is "backed" by a prototype object. If you ask the instance for a property it doesn't have (and functions are attached to objects as properties), the JavaScript interpreter checks the prototype behind the object to see if it has the property (and if not, the prototype behind that object, etc., etc.). This is how prototypical inheritance works.
JavaScript is an unusual prototypical language in that, until recently, there was no way to create an object and assign its prototype directly; you had to do it through constructor functions. If you're using class-based terminology, you're probably going to be more comfortable with constructor functions anyway. :-)
Here's a basic inheritance setup (this is not how I would actually do this, more on that below):
// Constructs an Vehicle instance function Vehicle(owner) { this.owner = owner; } // Who's this Vehicle's owner? Vehicle.prototype.getOwner = function() { return this.owner; }; // Constructs a Car instance function Car(owner) { // Call super's initialization Vehicle.call(this, owner); // Our init this.wheels = 4; } // Assign the object that will "back" all Car instances, // then fix up the `constructor` property on it (otherwise // `instanceof` breaks). Car.prototype = new Vehicle(); Car.prototype.constructor = Car; // A function that drives the car Car.prototype.drive = function() { }; Now we can use Car and get the features of Vehicle:
var c = new Car("T.J."); alert(c.getOwner()); // "T.J.", retrived via Vehicle.prototype.getOwner The above is a bit awkward and it has a couple of issues with when things happen that can be tricky. It also has the problem that most of the functions are anonymous, and I don't like anonymous functions (function names help your tools help you). It's also awkward to call your prototype's version of a function if you also have a copy of it (e.g., a "supercall" — not an uncommon operation with hierarchies). For that reason, you see a lot of "frameworks" for building hierarchies, usually using class-based terminology. Here's a list of some of them:
Class feature of Prootype, a general-purpose JavaScript libraryOf those four, I'd recommend Resig's or mine. Resig's uses function decompilation (calling toString on function instances, which has never been standardized and doesn't work on some platforms), but it works even if function decompilation doesn't work, it's just slightly less efficient in that case.
Before jumping on any of those, though, I encourage you to look at the true prototypical approach advocated by Douglas Crockford (of JSON fame, also a big wig at YUI). Crockford had a great deal of input on the latest version of ECMAScript, and some of his ideas (most notably Object.create) are now part of the latest standard and are finding their way into browsers. Using Object.create, you can directly assign a prototype to an object, without having a constructor function.
I prefer constructor functions (with my syntactic help) for places where I need inheritance, but Crockford's approach is valid, useful, and gaining popularity. It's something you should know about and understand, and then choose when or whether to use.
-4360581 0sorry, I should've read further in the tutorial I'm following. Apparently, the custom fields aren't part of the node object until you've retrieved them using hook_load(). Works fine now.
-8943778 0To initialize many contacts in a loop you may want to do something like this:
Contact *FirstOne = new Contact(); Contact *current = FirstOne; while(...) { current->next = new Contact(); current = current->next; //do stuff to current, like adding info } That way you are building up your Contact list. After that *FirstOne ist the first and *current is the last element of your list. Also you may want to make sure that the constructor sets *next to NULL to detect the end of the list.
I've completed my implementation of my first OpenRasta RESTful webservice and have successfully got the GET requests I wish for working.
Therefore I've taken some 'inspiration' from Daniel Irvine with his post http://danielirvine.com/blog/2011/06/08/testing-restful-services-with-openrasta/ to built a automated test project to test the implmentation.
I've created my own test class but I'm constantly getting a 404 error as the reponse status code.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using OpenRasta.Hosting.InMemory; using PoppyService; using OpenRasta.Web; using System.IO; using System.Runtime.Serialization.Json; using Microsoft.VisualStudio.TestTools.UnitTesting; using NUnit.Framework; namespace PoppyServiceTests { //http://danielirvine.com/blog/2011/06/08/testing-restful-services-with-openrasta/ [TestFixture] class OpenRastaJSONTestMehods { [TestCase("http://localhost/PoppyService/users")] public static void GET(string uri) { const string PoppyLocalHost = "http://localhost/PoppyService/"; if (uri.Contains(PoppyLocalHost)) GET(new Uri(uri)); else throw new UriFormatException(string.Format("The uri doesn't contain {0}", PoppyLocalHost)); } [Test] public static void GET(Uri serviceuri) { using (var host = new InMemoryHost(new Configuration())) { var request = new InMemoryRequest() { Uri = serviceuri, HttpMethod = "GET" }; // set up your code formats - I'm using // JSON because it's awesome request.Entity.ContentType = MediaType.Json; request.Entity.Headers["Accept"] = "application/json"; // send the request and save the resulting response var response = host.ProcessRequest(request); int statusCode = response.StatusCode; NUnit.Framework.Assert.AreEqual(200, statusCode, string.Format("Http StatusCode Error: {0}", statusCode)); // deserialize the content from the response object returnedObject; if (response.Entity.ContentLength > 0) { // you must rewind the stream, as OpenRasta // won't do this for you response.Entity.Stream.Seek(0, SeekOrigin.Begin); var serializer = new DataContractJsonSerializer(typeof(object)); returnedObject = serializer.ReadObject(response.Entity.Stream); } } } } }
If I navigate to the Uri manually in the browser I'm getting the correct responce and HTTP 200.
It's possibly something to do with my Configuration class, but if I test all the Uris manaully again I get the correct result.
public class Configuration : IConfigurationSource { public void Configure() { using (OpenRastaConfiguration.Manual) { ResourceSpace.Has.ResourcesOfType<TestPageResource>() .AtUri("/testpage").HandledBy<TestPageHandler>().RenderedByAspx("~/Views/DummyView.aspx"); ResourceSpace.Has.ResourcesOfType<IList<AppUser>>() .AtUri("/users").And .AtUri("/user/{appuserid}").HandledBy<UserHandler>().AsJsonDataContract(); ResourceSpace.Has.ResourcesOfType<AuthenticationResult>() .AtUri("/user").HandledBy<UserHandler>().AsJsonDataContract(); ResourceSpace.Has.ResourcesOfType<IList<Client>>() .AtUri("/clients").And .AtUri("/client/{clientid}").HandledBy<ClientsHandler>().AsJsonDataContract(); ResourceSpace.Has.ResourcesOfType<IList<Agency>>() .AtUri("/agencies").And .AtUri("/agency/{agencyid}").HandledBy<AgencyHandler>().AsJsonDataContract(); ResourceSpace.Has.ResourcesOfType<IList<ClientApps>>() .AtUri("/clientapps/{appid}").HandledBy<ClientAppsHandler>().AsJsonDataContract(); ResourceSpace.Has.ResourcesOfType<Client>() .AtUri("/agencyclients").And .AtUri("/agencyclients/{agencyid}").HandledBy<AgencyClientsHandler>().AsJsonDataContract(); ResourceSpace.Has.ResourcesOfType<Client>() .AtUri("/agencyplususerclients/{appuserid}").HandledBy<AgencyPlusUserClientsHandler>().AsJsonDataContract(); ResourceSpace.Has.ResourcesOfType<IList<Permission>>() .AtUri("/permissions/{appuserid}/{appid}").HandledBy<PermissionsHandler>().AsJsonDataContract(); ResourceSpace.Has.ResourcesOfType<IList<Role>>() .AtUri("/roles").And .AtUri("/roles/{appuserid}").And.AtUri("/roles/{appuserid}/{appid}").HandledBy<RolesHandler>().AsJsonDataContract(); ResourceSpace.Has.ResourcesOfType<IList<AppVersion>>() .AtUri("/userappversion").And .AtUri("/userappversion/{appuserid}").HandledBy<UserAppVersionHandler>().AsJsonDataContract(); } } } Any suggestions would be greatfully received.
-18484561 0This is not a very nice fix but it works:
CSS:
.new-tab-opener { display: none; } HTML:
<a data-href="http://www.google.com/" href="javascript:">Click here</a> <form class="new-tab-opener" method="get" target="_blank"></form> Javascript:
$('a').on('click', function (e) { var f = $('.new-tab-opener'); f.attr('action', $(this).attr('data-href')); f.submit(); }); Live example: http://jsfiddle.net/7eRLb/
-8387988 0Perhaps the most natural thing to do here is to present the login view controller modally. When the user has logged in successfully, the first controller can then push the third view controller onto the navigation stack. This way, the back button will lead directly back to the first view controller, and the user will understand why.
-14888591 0 google maps marker clusterer not working in IE7 & IE8 due to an 'is null or not an object' errorI have a google Map (js api v3) + marker clusterer which doesn't display in Internet Explorer 7 & 8 - I get the classical js error:
Message: 'addresses[...].lt' is null or not an object
On the other hand, this other example which uses a very similar json file, but doesn't use marker clusterer - displays the same error, but renders the markers on the map.
So I'm not even sure it's .json syntax error, rather something that bothers the marker clusterer instance, but I have no idea what
-26631222 0 cannot resolve method setGroupI wanted to assign a notification to a group with setGroup() for stacking notifications and summarising them.
Like HERE
final static String GROUP_KEY_SAPPHIRE = "group_key_emails"; NotificationCompat.Builder oneBuilder = new NotificationCompat.Builder(this); oneBuilder.setSmallIcon(R.drawable.warning_icon) .setContentTitle("Warning: ") .setContentText(message) .setPriority(0x00000002) .setLights(Color.GREEN, 500, 500) .setGroup(GROUP_KEY_SAPPHIRE) .addAction (R.drawable.ic_action_accept_dark, getString(R.string.ok), warningPendingIntent); NotificationManager oneNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); oneNotificationManager.notify(NOTIFICATION_ID, oneBuilder.build()); editText.setText(""); But I always got the response that the method setGroup couldn't be resolved. I've imported the .v4.support library.
Thanks in advance
-40864199 0 Couldn't get facebook Pages and groups details with facebook C# SDKI have integrated facebook DLL into my desktop application (C#.Net), in this one need to authenticate facebook account via OAuth and its working correctly. I got Access Token also and email too. But i want to access users pages and groups also, for this i have mentioned extendedPermissions like below:
FacebookExtendedPermissions = "email,user_groups,publish_stream,manage_pages"
I have used below block of code for getting users Page details:
FacebookClient _fb = new FacebookClient(); _fb.AccessToken = FacebookOAuthResult.AccessToken; dynamic results = _fb.Get("/me/accounts"); But i'm gatting empty value in data. What i'm doing wrong here can't get it.
I have tried in other way too like this:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://graph.facebook.com/me/accounts?access_token=" + longLivedToken); request.AutomaticDecompression = DecompressionMethods.GZip; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) using (Stream stream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(stream)) { string html = reader.ReadToEnd(); } But again no luck. Any help or pointers will be much appreciated. Thanks in advance.
-27120879 0Use 2 variables. First variable will store the last execution date and the next one will store the version. Whenever you execute the script, first check if the date is same. If yes, increment the version else set the version to 1. Export the variables so that they retain their values.
if [ "`date +'%Y%m%d'`" == "$LAST_EXEC_DATE" ]; then (( VERSION += 1 )) else VERSION=1 LAST_EXEC_DATE=`date +"%Y%m%d"` fi export LAST_EXEC_DATE export VERSION
-412696 0 While I adore the grep solution for its elegance and for reminding (or teaching) me about a method in Enumerable that I'd forgotten (or overlooked completely), it's slow, slow, slow. I agree 100% that creating the Array#mode method is a good idea, however - this is Ruby, we don't need a library of functions that act on arrays, we can create a mixin that adds the necessary functions into the Array class itself.
But the inject(Hash) alternative uses a sort, which we also don't really need: we just want the value with the highest occurrence.
Neither of the solutions address the possibility that more than one value may be the mode. Maybe that's not an issue in the problem as stated (can't tell). I think I'd want to know if there was a tie, though, and anyway, I think we can improve a little on the performance.
require 'benchmark' class Array def mode1 sort_by {|i| grep(i).length }.last end def mode2 freq = inject(Hash.new(0)) { |h,v| h[v] += 1; h } sort_by { |v| freq[v] }.last end def mode3 freq = inject(Hash.new(0)) { |h,v| h[v] += 1; h } max = freq.values.max # we're only interested in the key(s) with the highest frequency freq.select { |k, f| f == max } # extract the keys that have the max frequency end end arr = Array.new(1_000) { |i| rand(100) } # something to test with Benchmark.bm(30) do |r| res = {} (1..3).each do |i| m = "mode#{i}" r.report(m) do 100.times do res[m] = arr.send(m).inspect end end end res.each { |k, v| puts "%10s = %s" % [k, v] } end And here's output from a sample run.
user system total real mode1 34.375000 0.000000 34.375000 ( 34.393000) mode2 0.359000 0.000000 0.359000 ( 0.359000) mode3 0.219000 0.000000 0.219000 ( 0.219000) mode1 = 41 mode2 = 41 mode3 = [[41, 17], [80, 17], [72, 17]] The "optimised" mode3 took 60% of the time of the previous record-holder. Note also the multiple highest-frequency entries.
EDIT
A few months down the line, I noticed Nilesh's answer, which offered this:
def mode4 group_by{|i| i}.max{|x,y| x[1].length <=> y[1].length}[0] end It doesn't work with 1.8.6 out of the box, because that version doesn't have Array#group_by. ActiveSupport has it, for the Rails developers, although it seems about 2-3% slower than mode3 above. Using the (excellent) backports gem, though, produces a 10-12% gain, as well as delivering a whole pile of 1.8.7 and 1.9 extras.
The above applies to 1.8.6 only - and mainly only if installed on Windows. Since I have it installed, here's what you get from IronRuby 1.0 (on .NET 4.0):
========================== IronRuby ===================================== (iterations bumped to **1000**) user system total real mode1 (I didn't bother :-)) mode2 4.265625 0.046875 4.312500 ( 4.203151) mode3 0.828125 0.000000 0.828125 ( 0.781255) mode4 1.203125 0.000000 1.203125 ( 1.062507) So in the event that performance is super-critical, benchmark the options on your Ruby version & OS. YMMV.
-2369455 0I recommend you start by reading up on computational color theory. Wikipedia is actually a fine place to educate yourself on the subject. Try looking up a color by name on Wikipedia. You will find more than you expect. Branch out from there until you've got a synopsis of the field.
As you develop your analytic eye, focus on understanding your favorite (or most despised) interface colors and palettes in terms of their various representations in different colorspaces: RGB, HSB, HSL. Keep Photoshop/GIMP open so you can match the subjective experience of palettes to their quantifiable aspects. See how your colors render on lousy monitors. Notice what always remains readable, and which color combos tend to yield uncharismatic or illegible results. Pay attention to the emotional information conveyed by specific palettes. You will quickly see patterns emerge. For example, you will realize that high saturation colors are best avoided in UI components except for special purposes.
Eventually, you'll be able to analyze the output of the palette generators recommended here, and you'll develop your own theories about what makes a good match, and how much contrast is needed to play well on most displays.
(To avoid potential frustration, you might want to skip over to Pantone's free color perception test. It's best taken on a color calibrated display. If it says you have poor color perception, then numeric analysis is extra important for you.)
-18928967 0 Vertically center a table usingI want to center align a Table VERTICALLY in html. I am using the following code which is working on all browsers except SAFARI. I need this to work in safari too. What is going wrong? Any help will be appreciated.
HTML:
<div tabindex="0" title="Style1" class="button_class size_class" role="button" aria-pressed="false" style="display: table;" unselectable="on"> <div class="Container" aria-hidden="true" style="text-align: center; vertical-align: middle; display: table-cell;"> <table class="Preview"> <tbody> <tr><td style="">—</td><td style="">—</td><td style="">—</td><td style="">—</td><td style="">—</td></tr> <tr><td style="">—</td><td style="">—</td><td style="">—</td><td style="">—</td><td style="">—</td></tr> <tr><td style="">—</td><td style="">—</td><td style="">—</td><td style="">—</td><td style="">—</td></tr> <tr><td style="">—</td><td style="">—</td><td style="">—</td><td style="">—</td><td style="">—</td></tr> <tr><td style="">—</td><td style="">—</td><td style="">—</td><td style="">—</td><td style="">—</td></tr> </tbody> </table> </div> </div> CSS:
.button_class { border:1px solid transparent; display:inline-block; margin-left:0px; margin-right:2px; } .size_class { width:74px; height:58px; overflow:hidden; } .container { height: 48; width: 64; white-space: nowrap; overflow: hidden; } .preview { height: 32px; width: 64px; white-space: nowrap; overflow: hidden; vertical-align: baseline; display: block; }
-5655522 0 The C++ runtime dlls you need are the ones provided with the compiler as redistributable package and exactly this one! Other redist packages won't necessary work because of the manifests embedded in the executables which require an exact version (checked by a hash value of the binaries in the side by side assembly directory C:\Windows\SxS)
So you are right with the redistributable but you need the one that was installed with the compiler not one from a best guess from the internet. The exact versions can be looked at in the manifest files (XML)
-1803047 0I have finished this, just to let anyone know who may have this problem in the future. It turns out the reason there was nothing being taken in was because ADO tries to determine a column type. If other values in this column are not of said type, it removes them completely.
To counter this, you need to create a schema.ini file, like so:
StreamWriter writer = new StreamWriter(File.Create(dir + "\\schema.ini")); writer.WriteLine("[" + fileToBeRead + "]"); writer.WriteLine("ColNameHeader = False"); writer.WriteLine("Format = CSVDelimited"); writer.WriteLine("CharacterSet=ANSI"); int iColCount = dTable.Columns.Count + 1; for (int i = 1; i < iColCount; i++) { writer.WriteLine("Col" + i + "=Col" + i + "Name Char Width 20"); } //writer.WriteLine("Col1=Col1Name Char Width 20"); //writer.WriteLine("Col2=Col1Name Char Width 20"); //etc. writer.Close(); Thanks for everyone's suggestions!
-34332386 0If you are not locked in to using SWT, you could use the e(fx)clipse e4 renderer for JavaFX instead.
e(fx)clipse has more possibilities to control the lifecycle of the application. For example you can return a Boolean from @PostContextCreate to signal whether you want to continue the startup or not. You will not be able to use EPartService here though, but you can roll your own login dialog using dependency injection as greg-449 has described it in his answer.
public class StartupHook { @PostContextCreate public Boolean startUp(IEclipseContext context) { // show your login dialog LoginManager loginManager = ContextInjectionFactory.make(LoginManager.class, context); if(!loginManager.askUserToLogin()) { return Boolean.FALSE; } return Boolean.TRUE; } } (You can also restart the application. Form more details see http://tomsondev.bestsolution.at/2014/11/03/efxclipse-1-1-new-features-api-to-restart-your-e4-app-on-startup/).
-18609387 0You can use jQuery stop propagation function , it prevents events from bubling
-36632150 0 How to do a partial sum of table rows in LiveCycle - JavascriptI have 4 rows (and 3 columns) in a table. The last row is the total. I need to sum only the first two rows, excluding the last one. The problem is they are all calculated values from different tables, how do I do it? I am new to Adobe LiveCycle and Javascript.
This is what I currently have:
var times = xfa.resolveNodes("Row2[*].Time"); this.rawValue = Calculate.SumRawValues(times); I am trying something like this:
var times = xfa.resolveNodes("Row2[*].Time"); var timesFlushing = xfa.resolveNode("Row2[2].Time"); this.rawValue = Calculate.SumRawValues(times) - timesFlushing.value; or something like this:
var times = xfa.resolveNodes("Row2[*].Time"); this.rawValue = Calculate.SumRawValues(times) - xfa.resolveNode("Row2[2].Time"); or even this:
this.rawValue = Row2.Time + xfa.resolveNode("Row2[1].Time") Clearly I am new to this and none of these work. Help please??? Comments?
-8416406 0for i, fname in enumerate(dirList): print "%s) %s" % (i + 1, fname) selectedInt = int(raw_input("Select a file above: ")) selected = dirList[selectedInt - 1] However, note that there is no error correction done. You should catch cases, where the input is no integer.
-3935900 0 How to commit and rollback transaction in sql server?I have a huge script for creating tables and porting data from one server. So this sceipt basically has -
So I have this code but it does not work basically @@ERROR is always zero I think..
BEGIN TRANSACTION --CREATES --INSERTS --STORED PROCEDURES CREATES -- ON ERROR ROLLBACK ELSE COMMIT THE TRANSACTION IF @@ERROR != 0 BEGIN PRINT @@ERROR PRINT 'ERROR IN SCRIPT' ROLLBACK TRANSACTION RETURN END ELSE BEGIN COMMIT TRANSACTION PRINT 'COMMITTED SUCCESSFULLY' END GO Can anyone help me write a transaction which will basically rollback on error and commit if everything is fine..Can I use RaiseError somehow here..
-40194256 0Your immediate problem is that you need parentheses around (List.length xs). The code also treats an empty input list as an error in all cases, which is not correct. An empty list is a legitimate input if the desired length k is 0.
Update
You also have one extra parameter in your definition. If you say this:
let myfun k xs = function ... the function myfun has 3 parameters. The first two are named k and xs and the third is implicitly part of the function expression.
The quick fix is just to remove xs.
I think you might be asking for the wrong number of elements in your recursive call to take. Something to look at anyway.
You can just use Windows Explorer. Open Windows Explorer and go into the assembly folder inside your Windows folder. You should then see all the assemblies that are registered, if you want to add yours in, just drag and drop it in there.
Or if you prefer, you can locate the gacutil.exe and use that to do it (but it's not installed with the framework nowdays, only with the SDK I think).
-36075549 0You should unquote to the true:
if(html==true) //or just, if(html) Otherwise it will look for string "true" and this is why it goes to the else part.
-39980536 0 Geolocation.getCurrentPosition: Timeout expiredI am using Ionic2.
I am using the following code, but get an error:
import { Geolocation } from 'ionic-native'; public getPosition(): void { if (this.markers && this.markers.length > 0) { var marker: google.maps.Marker = this.markers[0]; // only one this.latitude = marker.getPosition().lat(); this.longitude = marker.getPosition().lng(); this.getJobRangeSearch(this.searchQuery); } else { let options = { timeout: 10000, enableHighAccuracy: true }; Geolocation.getCurrentPosition(options).then((position) => { this.latitude = position.coords.latitude; this.longitude = position.coords.longitude; this.getJobRangeSearch(this.searchQuery); }).catch((error) => { console.log(error); this.doAlert(error+' Timeout trying to get your devices Location'); }); } } error:
PositionError {message: "Timeout expired", code: 3, PERMISSION_DENIED: 1, POSITION_UNAVAILABLE: 2, TIMEOUT: 3}
package.json
"ionic-native": "^1.3.2", Thank you
-34970499 0 AWS S3 + CDN Speed, significantly slowerOk,
So I've been playing around with amazon web services as I am trying to speed up my website and save resources on my server by using AWS S3 & CloudFront.
I ran a page speed test initially, the page speed loaded in 1.89ms. I then put all assets onto an s3 bucket, made that bucket available to cloudfront and then used the cloudfront url on the page.
When I ran the page speed test again using this tool using all their server options I got these results:
Server with lowest speed of : 3.66ms
Server with highest speed of: 5.41ms
As you can see there is a great increase here in speed. Have I missed something, is it configured wrong? I thought the CDN was supposed to make the page speed load faster.
-14665748 0 Differences between p-values in summary and from the anova in R lm()I am seeing differences in the p-value for the anova depending on how I access this.
Is there a way to get the same value that is returned by the summary?
One easy to represent case returns < 2.2e-16 in the summary and in the anova but gives me 8.129959e-100 when I access the value directly:
x <- lm(formula = eruptions ~ waiting, data = faithful) summary(x) anova(x) anova(x)$"Pr(>F)"[1] In another more difficult to represent case (there is a lot more data) I get p-value: < 2.2e-16 in the summary but 0 from anova.
Is there any way to get the actual value that is returned in the summary and anova?
I really appreciate your help -
-19440168 0you're creating temporary variable a in function calculateFlexibility, then you store pointer to f.flex variable, but after function is ended - a is gone from memory, so your f.flex pointer is now pointing to nowhere
if you want to have really variable length, you should do something like this:
Flexibility calculateFlexibility() { Flexibility f; f.flex = (int*)malloc(....); return f; } and at the end of program:
free(f.flex); for proper arguments of malloc I suggest you to read: http://en.cppreference.com/w/c/memory/malloc
-27113111 0Your fetch XML looks correct to me. When you set up the subgrid did you set "Records" = "All Record Types" in the Data Source section? If you did not then the subgrid will append a condition to your fetchxml so that it returns only records related to the specific relationship that you specified.
-23628064 0If you want to create instance of your class from name = Paul AND age = 16 AND country = china that kind of script, then you could create yourself method
public <T> T builder(Class<T> clazz, String line) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException { T instance = clazz.newInstance(); String[] exps = line.split("AND"); for (String exp : exps) { String[] tokens = exp.split("=", 2); // TODO check if token has length==2 tokens[0] = tokens[0].trim(); tokens[1] = tokens[1].trim(); String methodName = "set" + (("" + tokens[0].charAt(0)).toUpperCase()) + tokens[0].substring(1); Method m1 = instance.getClass().getMethod(methodName, String.class); m1.invoke(instance, tokens[1]); } return instance; } and when you call it builder(Person.class,"name = Paul AND age = 16 AND country = china") you will get instance of Person class with populated fields name, age and country.
Is that what you are looking for?
-8377059 0 Which character is Ctrl+Backspace?There are several places that you can enter this character by typing ctrl-backspace, including windows loggon password.
Which character is this and can I use it in a password?
-11869820 0 TSQL Passing a varchar variable of column name to SUM functionI need to write a procedure where I have to sum an unknown column name.
The only information I have access to is the column position.
I am able to get the column name using the following:
SELECT @colName = (SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='TABLENAME' AND ORDINAL_POSITION=@colNum) I then have the following:
SELECT @sum = (SELECT SUM(@colName) FROM TABLENAME) I then receive the following error:
Operand data type varchar is invalid for sum operator
I am confused about how to make this work. I have seen many posts on convert and cast, but I cannot cast to an float, numeric, etc because this is a name.
I would appreciate any help.
Thank you
-39832012 0 Does gcc use "LD_LIBARRY_PATH" when doing linking '-L'?I've got libo.a file under current directory, I found I have to use '-L.' to make gcc able to find current directory's archive files.
I know under linux/solaris, there's environment variable of "LD_LIBRARY_PATH" to specify shared_library path. I found it doesn't work with gcc when doing link, 'export LD_LIBRARY_PATH' cannot be used to replace '-L.'
Question(1) Is this by design of gcc, that linker search path doesn't read from environment variable, but should be specified by command line options?
More weird is, I did 'export LIBPATH=.', it doesn't work either, but if I add LIBPATH into a scons file:
Library('o.c') Program('n.c',LIBS=['o'],LIBPATH='.') Then it works!
Question(2) What is the difference between environment shell variable of 'LIBPATH', and the scons parameter of 'LIBPATH'. Does scons has an internal parameter named 'LIBPATH', which has nothing to do with shell environment?
Thanks!
-24956706 0 use *this as std::shared_ptrhere is a "chess++" problem that I'm facing wright now with my nested class, although it may look like some joke, it's not a joke but real problem which I want to either solve or change the way to achieve the same thing in my project.
#include <map> #include <memory> #include <iostream> #include <sigc++/signal.h> class foo { public: struct bar; typedef sigc::signal<void, std::shared_ptr<bar>> a_signal; struct bar { bar() { some_signal.connect(sigc::mem_fun(*this, &foo::bar::func)); } void notify() { some_signal.emit(this); // how to ?? } void func(std::shared_ptr<foo::bar> ptr) { std::cout << "you haxor!" << std::endl; // use the pointer ptr-> } a_signal some_signal; }; std::map<int, std::shared_ptr<bar>> a_map; }; int main() { std::shared_ptr<foo::bar> a_foo_bar; foo foo_instance; foo_instance.a_map.insert(std::pair<int, std::shared_ptr<foo::bar>>(4, a_foo_bar)); foo_instance.a_map.at(0)->notify(); return 0; } What I want to do here is to emit a signal. the signal is declared as one that triggers a handler that takes a shared_ptr as an argument. the function notify() should convert *this into shared_ptr, how do I do that to make the above code run?
-23239638 0 Youtube brandingI want to place YouTube video on my site with no branding . also I don't want any one to right click and grabbing the vid URL. JW player will support this but ppl still can click the YT watermark. is thire any way I could add allow networking internal only function to jw play. basically I don't want any onto go to YouTube and also to copy the url
-7431908 0 Wifi Device to Device Communication problemI wrote a code in my application to enable Device to Device wifi Communication(transferring only a text/string).The code is same as the Apple's sample Witap Application which is downloaded from Developer.Apple.com.
Its working in my network fine and another networks also.
However its not working in my client site.
I spent time at the Client site to sort out the issue with the Devices not communicating to each other and this is what I found. They in their security setup block peer to peer communication…" and my device communication is identified as peer to peer .
Is there any way to solve this problem Is there anything other than PEER 2 PEER wifi communication which apple supports?
Prototype WIFI applications Working Concepts
There are mainly four classes in WiFi application named as AppController, Picker, BrowserViewController, TCP Server.
When application loads the AppController class will initialize NSInputStraem and NSOutPut Stream.
And also it will call “start” method from TcpServer class to set port number.
After it will call “enableBounjourWithDomain” method from TcpServer class.
The above method call with a parameter called as identifier (it is a common name eg:WiTap) and the sender part is searching devices with this common identifier.
After the execution of this method the sender device can identify our device and able to connect.
Getting Own Device Name
Tcp serverServer delegate “DidEnabledBounjer” will work after the above code execution and it will give the current device name.
Then NSNetservice delegate “didFindService” will work (it work when each service discovered) and retrieve the discovered service name.
After getting the new service name we will check either it is same to our device name which we got from “DidEnabledBounjer” delegate.
if not ,the new service name will add into a NSMutable array named as services.
Then services array bind t o the Table view and we can see the list of discovered device names.
discovering the new devices:
No timer settings for discovering the new devices.
When a new device is connected in the same WiFi net work the “DidFindservice” delegate will trigger(it is a NSNetservice delegate implemented in BrowserViewController class).
DidFindservice will give the new device name .After getting it we will check either it is same to our device name witch we got from “DidEnabledBounjer” delegate.
if not ,the service name will add into a NSMutable array named as services.
Then sort all the discovered ;device names according to the Device name and reload the Table View.
Working after selecting a device name from Table View
After clicking device name on the TableView it will call “didSelectRowAtIndexPath” delegate which is implemented in BrowserViewController class( it is a TableView Class delegate) .
It will select a NetService name from our services array(holds all the discovered services) according to the TableView index and set resultant NSService as Current Service.
Trigger a delegate “didResolveInstance” and it will set the InPutStream and OutPutStream values.
After get ting values for InPutStream and OutPutStream it will call “OpenStream” method to open the input and output Streams.
Finally it release the NSService and Picker objects and ready to send messages with selected devices.
Working of send Button
Call “send “ function from BrowserViewController class with a string parameter .It may be user text input or generated string after speech recognition.
Convert the input string as a uint_8 data type and send it to the receiver device.
Receiver Side Working
When a data came to receiver device the “TcpServerAcceptCallBack” delegate will trigger(implemented in TcpServer Class).
It will call “DidAcceptConnectionForServer” method from BrowserViewControll calss through another TcpServer class delegate named “HandleNewConnectionFromAddress”.
Trigger the “stream handle delegate” which is in “AppController “ class and it will check is there any bites available or not.
If bytes are available convert the uint_8 type data to string and we are displaying the resultant string in receiver text box.
And also loading images and displaying it in Image View from AppBundle using the resultant string.< /p>
-39063011 0 gsap animation - import only one svg or multiple svgsI would like to do "complex" animation with gsap and svgs. but I don't know what is the best approach to this. it is better to create and to import an unique svg with all the elements or maybe it is better 4 different svgs?
I have 4 different characters: a tree, a lamp, a desk and a man. basically my animation is move the objects on the x, and appearing and to disappearing stuff.
-35227417 0 Custom GcmListenerService not workingThis is my manifest file
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="be.customapp" > <uses-permission android:name="android.permission.INTERNET" /> <!-- GCM: keep device awake while receiving a notification --> <uses-permission android:name="android.permission.WAKE_LOCK"/> <!-- GCM: receive push notifications --> <permission android:name="be.customapp.permission.C2D_MESSAGE" android:protectionLevel="signature" /> <uses-permission android:name="be.customapp.permission.C2D_MESSAGE" /> <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <!-- Meta data --> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="@string/google_maps_key"/> <!-- Activities --> <activity android:name=".ui.activities.MainActivity" android:label="@string/app_name" android:launchMode="singleTop" android:screenOrientation="portrait"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- Services --> <service android:exported="false" android:name=".services.gcm.MyGcmListenerService"> <intent-filter> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> </intent-filter> </service> <service android:exported="false" android:name=".services.gcm.GcmRegisterService"/> <service android:name=".services.gcm.MyInstanceIDListenerService" android:exported="false"> <intent-filter> <action android:name="com.google.android.gms.iid.InstanceID"/> </intent-filter> </service> <!-- Broadcastreceivers --> <receiver android:name="com.google.android.gms.gcm.GcmReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND" > <intent-filter> <action android:name="com.google.android.c2dm.intent.REGISTRATION" /> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> <category android:name="be.prior_it.evapp" /> </intent-filter> </receiver> </application> </manifest> And this is the service that gets/registers my registration id;
InstanceID instanceID = InstanceID.getInstance(this); String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); MyGcmListenerService;
public class MyGcmListenerService extends GcmListenerService { @Override public void onMessageReceived(String from, Bundle data) { super.onMessageReceived(from, data); Log.i(Constants.LOG_TAG, "Got GCM message " + data.getString("message")); } } The server uses PushJack and sends to the registration id's. I can see that the server can send the messages, I can get my registration id and register it with our server, but the onMessageReceived never gets called... I also made the google-services.json using the link on the website, so that should also be okay.
Any or all ideas are welcome.
-8151662 0 TestNG enabled = false tests not showing as SkippedWe have a number of TestNG tests that are disabled due to functionality not yet being present (enabled = false), but when the test classes are executed the disabled tests do not show up as skipped in the TestNG report. We'd like to know at the time of execution how many tests are disabled (i.e. skipped). At the moment we have to count the occurrences of enabled = false in the test classes which is an overhead.
Is there a different annotation to use or something else we are missing so that our test reports can display the number of disabled tests?
-30565155 0the question is a bit too broad.
you have to step back and look at how source code in general ends up being executed (i.e. it is used).
In case of some programming languages (e.g. C/C++) it's compiled to a native form and can be executed directly afterwards;
In case of other languages it's compiled to an intermediate form (e.g. Java/C#) and executed by a vm (jvm/clr)
In case of yet other languages is interpreted at runtime (e.g. Ruby/Python).
So in the specific case of Ruby, you have the interpreter that loads the rb files and runs them. This can be in the context of standalone apps or in th e context of a web server, but you almost always have the interpreter making sense of the ruby files. you don't get an executable the same way as the you get for languages that are compiled to machine code.
-10012046 0The problem is that you have no template. Your XAML should look somehow like this:
<Window x:Class="HKC.Desktop.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="487" Width="765.924" Loaded="Window_Loaded"> <Window.Resources> <ControlTemplate x:Key="buttonTemplate" TargetType="{x:Type Button}"> <Ellipse Name="el1" Fill="Orange" Width="100" Height="100"> <ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center" Content="{TemplateBinding Button.Content}" /> </ControlTemplate> </Window.Resources> <Grid x:Name="mainGrid" Background="#FF252525"> <Button Content="Push Me" Template="{StaticResource buttonTemplate}" Name="button1" Height="100" Width="100"/> </Grid> </Window>
-22774115 0 Google Maps API data.setStyle not showing icons on map I'm trying to create a little app using the Google Maps JS API. I'm using the data layer to load a bunch of points from a GeoJSON file. The file seems to be loading properly, and the map is displaying, but the icons that are set in the map.data.setstyle() won't show...
Below is my HTML, CSS, and JS. I've been looking at this for 2 days, and I can't figure out what's going wrong. Thank you in advance!
HTML
<body> <div id="map-canvas"></div> </body> CSS
html { height: 100% } body { height: 100%; margin: 0; padding: 0 } #map-canvas { height: 100% } JS
$(document).ready(function() { var map; function initialize() { var mapOptions = { center: new google.maps.LatLng(37.000, -120.000), zoom: 7 }; map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions); map.data.loadGeoJson('/map.json'); map.data.setStyle(function(feature) { var theaterName = feature.getProperty('name'); return { icon: "https://maps.gstatic.com/mapfiles/ms2/micons/marina.png", visible: true, clickable: true, title: theaterName }; }); } google.maps.event.addDomListener(window, 'load', initialize); }); JSON
{ "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": { "rentrak_id": "9183", "name": "Palm Theatre", "address": "817 Palm St, San Luis Obispo, CA"}, "geometry": { "type": "Point", "coordinates": [35.2815558, -120.6638196] } }, { "type": "Feature", "properties": { "rentrak_id": "8961", "name": "King City 3", "address": "200 Broadway St, King City, CA"}, "geometry": { "type": "Point", "coordinates": [36.21372, -121.1261771] } }, {"type": "Feature", "properties": { "rentrak_id": "5549", "name": "Van Buren 3 DI", "address": "3035 Van Buren Blvd, Riverside, CA"}, "geometry": { "type": "Point", "coordinates": [33.9113137, -117.4364228] }}, {"type": "Feature", "properties": { "rentrak_id": "990802", "name": "CGV Cinemas LA", "address": "621 S Western Ave, Los Angeles, CA"}, "geometry": { "type": "Point", "coordinates": [34.0626656, -118.3093961] }}, {"type": "Feature", "properties": { "rentrak_id": "5521", "name": "Rancho Niguel 7", "address": "25471 Rancho Niguel Rd, Laguna Niguel, CA"}, "geometry": { "type": "Point", "coordinates": [33.5560509, -117.68533] }}]} EDIT::
So, my script is working when I use this file: http://earthquake.usgs.gov/earthquakes/feed/geojsonp/2.5/week
Which makes me think there is something wrong with my local json file... However when I step through the javascript, I can look at each feature and check for the properties and geometries, and they seem to be correctly loaded into the google.maps.feature objects. So, I still have no idea why the points wouldn't be showing up.
-16743471 0Thomas's answer is much better than any of the three approaches I tried. Here I compare the four approaches with microbenchmark. I have not yet tried Thomas's answer with the actual data. My original nested for-loops approach is still running after 22 hours.
Unit: milliseconds expr min lq median uq max neval fn.1(x, weights) 98.69133 99.47574 100.5313 101.7315 108.8757 20 fn.2(x, weights) 755.51583 758.12175 762.3775 776.0558 801.9615 20 fn.3(x, weights) 564.21423 567.98822 568.5322 571.0975 575.1809 20 fn.4(x, weights) 367.05862 370.52657 371.7439 373.7367 395.0423 20 ######################################################################################### # create data set.seed(1234) n.rows <- 40 n.cols <- 40 n.sample <- n.rows * n.cols x <- sample(20, n.sample, replace=TRUE) x.NA <- sample(n.rows*n.cols, 10*(n.sample / n.rows), replace=FALSE) x[x.NA] <- NA x <- as.data.frame(matrix(x, nrow = n.rows)) weights <- sample(4, n.sample, replace=TRUE) weights <- as.data.frame(matrix(weights, nrow = n.rows)) weights ######################################################################################### # Thomas's function fn.1 <- function(x, weights){ newx <- reshape(x, direction="long", varying = list(seq(1,(n.cols-1),2), seq(2,n.cols,2)), v.names=c("v1", "v2")) newwt <- reshape(weights, direction="long", varying = list(seq(1,(n.cols-1),2), seq(2,n.cols,2)), v.names=c("w1", "w2")) condwtmean <- function(x,y,wtx,wty){ if(xor(is.na(x),is.na(y))){ if(is.na(x)) x <- (y / wty) * wtx # replacement function if(is.na(y)) y <- (x / wtx) * wty # replacement function return(weighted.mean(c(x,y),c(wtx,wty))) } else if(!is.na(x) & !is.na(y)) return(weighted.mean(c(x,y),c(wtx,wty))) else return(NA) } newx$wtmean <- mapply(condwtmean, newx$v1, newx$v2, newwt$w1, newwt$w2) newx2 <- reshape(newx[,c(1,4:5)], v.names = "wtmean", timevar = "time", direction = "wide") newx2 <- newx2[,2:(n.cols/2+1)] names(newx2) <- paste('X', 1:(n.cols/2), sep = "") return(newx2) } fn.1.output <- fn.1(x, weights) ######################################################################################### # nested for-loops with 4 if statements fn.2 <- function(x, weights){ for(i in 1: (ncol(x)/2)) { for(j in 1: nrow(x)) { if( is.na(x[j,(1 + (i-1)*2)]) & !is.na(x[j,(1 + (i-1)*2 + 1)])) x[j,(1 + (i-1)*2 + 0)] = (x[j,(1 + ((i-1)*2 + 1))] / weights[j,(1 + ((i-1)*2 + 1))]) * weights[j,(1 + (i-1)*2 + 0)] if(!is.na(x[j,(1 + (i-1)*2)]) & is.na(x[j,(1 + (i-1)*2 + 1)])) x[j,(1 + (i-1)*2 + 1)] = (x[j,(1 + ((i-1)*2 + 0))] / weights[j,(1 + ((i-1)*2 + 0))]) * weights[j,(1 + (i-1)*2 + 1)] if( is.na(x[j,(1 + (i-1)*2)]) & is.na(x[j,(1 + (i-1)*2 + 1)])) x[j,(1 + (i-1)*2 + 0)] = NA if( is.na(x[j,(1 + (i-1)*2)]) & is.na(x[j,(1 + (i-1)*2 + 1)])) x[j,(1 + (i-1)*2 + 1)] = NA } } x.weights = x * weights numerator <- sapply(seq(1,ncol(x.weights),2), function(i) { apply(x.weights[,c(i, i+1)], 1, sum, na.rm=T) }) denominator <- sapply(seq(1,ncol(weights),2), function(i) { apply(weights[,c(i, i+1)], 1, sum, na.rm=T) }) weighted.x <- numerator/denominator for(i in 1: (ncol(x)/2)) { for(j in 1: nrow(x) ) { if( is.na(x[j,(1 + (i-1)*2)]) & !is.na(x[j,(1 + (i-1)*2 + 1)])) weighted.x[j,i] = sum(c(x[j,(1 + ((i-1)*2))], x[j,(1 + ((i-1)*2 + 1))]), na.rm = TRUE) if(!is.na(x[j,(1 + (i-1)*2)]) & is.na(x[j,(1 + (i-1)*2 + 1)])) weighted.x[j,i] = sum(c(x[j,(1 + ((i-1)*2))], x[j,(1 + ((i-1)*2 + 1))]), na.rm = TRUE) if( is.na(x[j,(1 + (i-1)*2)]) & is.na(x[j,(1 + (i-1)*2 + 1)])) weighted.x[j,i] = NA } } return(weighted.x) } fn.2.output <- fn.2(x, weights) fn.2.output <- as.data.frame(fn.2.output) names(fn.2.output) <- paste('X', 1:(n.cols/2), sep = "") ######################################################################################### # nested for-loops with 2 if statements fn.3 <- function(x, weights){ for(i in 1: (ncol(x)/2)) { for(j in 1: nrow(x)) { if( is.na(x[j,(1 + (i-1)*2)]) & !is.na(x[j,(1 + (i-1)*2 + 1)])) x[j,(1 + (i-1)*2 + 0)] = (x[j,(1 + ((i-1)*2 + 1))] / weights[j,(1 + ((i-1)*2 + 1))]) * weights[j,(1 + (i-1)*2 + 0)] if(!is.na(x[j,(1 + (i-1)*2)]) & is.na(x[j,(1 + (i-1)*2 + 1)])) x[j,(1 + (i-1)*2 + 1)] = (x[j,(1 + ((i-1)*2 + 0))] / weights[j,(1 + ((i-1)*2 + 0))]) * weights[j,(1 + (i-1)*2 + 1)] } } x.weights = x * weights numerator <- sapply(seq(1,ncol(x.weights),2), function(i) { apply(x.weights[,c(i, i+1)], 1, sum, na.rm=T) }) denominator <- sapply(seq(1,ncol(weights),2), function(i) { apply(weights[,c(i, i+1)], 1, sum, na.rm=T) }) weighted.x <- numerator/denominator for(i in 1: (ncol(x)/2)) { for(j in 1: nrow(x) ) { if( is.na(x[j,(1 + (i-1)*2)]) & !is.na(x[j,(1 + (i-1)*2 + 1)])) weighted.x[j,i] = sum(c(x[j,(1 + ((i-1)*2))], x[j,(1 + ((i-1)*2 + 1))]), na.rm = TRUE) if(!is.na(x[j,(1 + (i-1)*2)]) & is.na(x[j,(1 + (i-1)*2 + 1)])) weighted.x[j,i] = sum(c(x[j,(1 + ((i-1)*2))], x[j,(1 + ((i-1)*2 + 1))]), na.rm = TRUE) if( is.na(x[j,(1 + (i-1)*2)]) & is.na(x[j,(1 + (i-1)*2 + 1)])) weighted.x[j,i] = NA } } return(weighted.x) } fn.3.output <- fn.3(x, weights) fn.3.output <- as.data.frame(fn.3.output) names(fn.3.output) <- paste('X', 1:(n.cols/2), sep = "") ######################################################################################### # my reshape solution fn.4 <- function(x, weights){ new.x <- reshape(x , direction="long", varying = list(seq(1,(n.cols-1),2), seq(2,n.cols,2)), v.names = c("v1", "v2")) wt <- reshape(weights, direction="long", varying = list(seq(1,(n.cols-1),2), seq(2,n.cols,2)), v.names = c("w1", "w2")) new.x$v1 <- ifelse(is.na(new.x$v1), (new.x$v2 / wt$w2) * wt$w1, new.x$v1) new.x$v2 <- ifelse(is.na(new.x$v2), (new.x$v1 / wt$w1) * wt$w2, new.x$v2) x2 <- reshape(new.x, direction="wide", varying = list(seq(1,3,2), seq(2,4,2)), v.names = c("v1", "v2")) x <- x2[,2:(n.cols+1)] x.weights = x * weights numerator <- sapply(seq(1,ncol(x.weights),2), function(i) { apply(x.weights[,c(i, i+1)], 1, sum, na.rm=T) }) denominator <- sapply(seq(1,ncol(weights),2), function(i) { apply(weights[,c(i, i+1)], 1, sum, na.rm=T) }) weighted.x <- numerator/denominator for(i in 1: (ncol(x)/2)) { for(j in 1: nrow(x) ) { if( is.na(x[j,(1 + (i-1)*2)]) & !is.na(x[j,(1 + (i-1)*2 + 1)])) weighted.x[j,i] = sum(c(x[j,(1 + ((i-1)*2))], x[j,(1 + ((i-1)*2 + 1))]), na.rm = TRUE) if(!is.na(x[j,(1 + (i-1)*2)]) & is.na(x[j,(1 + (i-1)*2 + 1)])) weighted.x[j,i] = sum(c(x[j,(1 + ((i-1)*2))], x[j,(1 + ((i-1)*2 + 1))]), na.rm = TRUE) if( is.na(x[j,(1 + (i-1)*2)]) & is.na(x[j,(1 + (i-1)*2 + 1)])) weighted.x[j,i] = NA } } return(weighted.x) } fn.4.output <- fn.4(x, weights) fn.4.output <- as.data.frame(fn.4.output) names(fn.4.output) <- paste('X', 1:(n.cols/2), sep = "") ######################################################################################### rownames(fn.1.output) <- NULL rownames(fn.2.output) <- NULL rownames(fn.3.output) <- NULL rownames(fn.4.output) <- NULL all.equal(fn.1.output, fn.2.output) all.equal(fn.1.output, fn.3.output) all.equal(fn.1.output, fn.4.output) all.equal(fn.2.output, fn.3.output) all.equal(fn.2.output, fn.4.output) all.equal(fn.3.output, fn.4.output) library(microbenchmark) microbenchmark(fn.1(x, weights), fn.2(x, weights), fn.3(x, weights), fn.4(x, weights), times=20) #########################################################################################
-15164620 0 Instead of trying to parse the output of ls, which is bad, you should simply use file system operation provided by node.js. Using file system operations you can be sure your program will work in (almost) any edge case as the output is well defined. It will even work in case the folder will contain more or less files than three in the future!
As you stated in the comments that you want the names and date / time of the files from a folder. So let us have a look at:
fs.readdir(path, callback): fs.readdir will give you an array of filenames in the folder specified in path. You can pass them to fs.stat to find out the mtime:
fs.stat(path, callback): fs.stat() will give you an object of fs.Stats which contains the mtime in the mtime property.
So your code will look something like this afterwards:
fs.readdir('dir', function (err, files) { for (var i = 0; i < files.length; i++) { (function () { var filename = files[i] fs.stat('dir/' + filename, function (err, stats) { console.log(filename + " was last changed on " + stats.mtime); }); })(); } }); The output is:
[timwolla@~/test]node test.js 5 was last changed on Fri Mar 01 2013 20:24:35 GMT+0100 (CET) 4 was last changed on Fri Mar 01 2013 20:24:34 GMT+0100 (CET) 2 was last changed on Fri Mar 01 2013 20:24:33 GMT+0100 (CET) In case you need a return value use the respective Sync-versions of these methods. These, however, will block your node.js eventing loop.
I was trying to parse a page (Kaggle Competitions) with xpath on MacOS as described in another SO question:
curl "https://www.kaggle.com/competitions/search?SearchVisibility=AllCompetitions&ShowActive=true&ShowCompleted=true&ShowProspect=true&ShowOpenToAll=true&ShowPrivate=true&ShowLimited=true&DeadlineColumnSort=Descending" -o competitions.html cat competitions.html | xpath '//*[@id="competitions-table"]/tbody/tr[205]/td[1]/div/a/@href' That's just getting a href of a link in a table.
But instead of returning the value, xpath starts validating .html and returns errors like undefined entity at line 89, column 13, byte 2964.
Since man xpath doesn't exist and xpath --help ends with nothing, I'm stuck. Also, many similar solutions relate to xpath from GNU distributions, not in MacOS.
Is there a correct way of getting HTML elements via XPath in bash?
-13031542 0 algorithms to emulate human movement in a stick figureI need to make a program that lets you animate a stick figure, so I'm looking for some information on algorithms to emulate human movement. I found some software that lets you create animations with stick figures, but are hard to use because basically they don't help you emulate realistic movement, so the animator is responsible for everything. That's cool when you are or have an animator, but I'm not, I'm only a programmer.
I would really appreciate if someone knows about a library, or text with an explanation of these kinds of algorithms.
-16197557 0If you can specify what kinds of search strings this method will accept, you can use regular expressions. Here's an example which also uses Linq for brevity:
public IList<String> GetMatchingRemoteFiles(String SearchPattern, bool ignoreCase) { var options = ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None; return thirdPartyTool.ftpClient.GetCurrentDirectoryContents() .Where(fn => Regex.Matches(fn, SearchPattern, options)) .ToList(); } Even if you cannot control what kinds of search strings this method accepts, it's still probably easier to convert the search string to a regular expression than write your own algorithm for matching the patterns. See Bobson's answer for details on how to do this.
-14441548 0Do you mean something like this?
<html> ... <?php include('codesnippet.php') ?> ... </html> or the other way (showing the code up in a HTML document)?
<pre> <code> <!-- your snippet goes here, with escaped characters --> </code> </pre>
-14347509 0 So I came up with a different solution. Instead of trying to save an array, I just saved the post ID which would allow me access to the title of the post as well as the permalink.
This is my modified code
<select name="pastor_select"> <?php $args = array( 'post_type' => 'employee', 'position' => 'pastor' ); $pastorList = new WP_Query($args); while ($pastorList->have_posts()) : $pastorList->the_post(); $employeeID = get_the_ID(); // THIS FIXED THE PROBLEM $is_selected = ($employeeID == $selected) ? 'selected="selected"' : ''; echo '<option value="'.$employeeID.'" '.$is_selected.'>'.get_the_title().'</option>'; endwhile; wp_reset_postdata(); ?> </select> And this is how I am calling it on the front end
<?php $id = $post_meta_data['pastor_select'][0]; echo '<a href="'.get_permalink($id).'">'; echo get_the_title($id); echo '</a>'; ?>
-36472256 0 How to set the child control size inside ellipse when resize wpf I am creating a user control which has a shape (a curved line) inside a circle. I used ellipse control to create the circle.how to keep the size of the shape inside the ellipse when resize?
-11672334 0 save special character in Database using Grailsnew Trainingcamp(name:"Höhentraining", region:"Alpen").save() tr1 = Trainingcamp.findByName("Höhentraining") tr2 = Trainingcamp.findByRegion("Alpen") println("Tr1: " + tr1?.name) println("Tr2: " + tr2?.name) Output on console is:
Tr1: Tr2: H?hentraining So it seems to me that by saving the domainobject something happens that replaces the Special character "ö" with a questionmark "?". How do I get rid of this problem? Thanks in advanced!
Using Grails 1.3.7
__edit1: I started the application with prod run-app and then checked the pordDb.log. I found the following insert:
INSERT INTO TRAININGCAMP VALUES('H\ufffdhentraining','Alpen') No matter I write an "ö" or "ü or "ä" it allways replace it with "\ufffd" So, any suggestions to solve this problem?
__edit2: New insight: The Problem only occur when I save the domain in BootStrap.groovy. By saving the domain in a controller the output on the console is as expected:
Tr2: Höhentraining
-35500216 0 YourListView.setOnItemClickListener(new ListView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> a, View v, int pos, long l) { try { Toast.makeText(this,"Position is===>>"+pos , Toast.LENGTH_LONG).show(); } catch(Exception e) { System.out.println("Nay, cannot get the selected index"); } } }); Hope it helps.
-13840495 0 mysql - combining 2 tables with different conditionHere i have 2 tables user and userStore
user Table ╔════╦══════╦════════╦═══════════╗ ║ ID ║ NAME ║ ROLE ║ STORECODE ║ ╠════╬══════╬════════╬═══════════╣ ║ 1 ║ A ��� Admin ║ ║ ║ 2 ║ B ║ Store ║ 1 ║ ║ 3 ║ C ║ Store ║ ║ ║ 4 ║ D ║ Client ║ ║ ║ 5 ║ E ║ Staff ║ ║ ╚════╩══════╩════════╩═══════════╝ userStore Table ╔════╦══════════╗ ║ ID ║ CATEGORY ║ ╠════╬══════════╣ ║ 1 ║ X ║ ║ 2 ║ X ║ ╚════╩══════════╝ Output ╔════╦══════╦════════╦═══════════╦══════════╗ ║ ID ║ NAME ║ ROLE ║ STORECODE ║ CATEGORY ║ ╠════╬══════╬════════╬═══════════╬══════════╣ ║ 1 ║ A ║ Admin ║ ║ ║ ║ 2 ║ B ║ Store ║ 1 ║ X ║ ║ 4 ║ D ║ Client ║ ║ ║ ║ 5 ║ E ║ Staff ║ ║ ║ ╚════╩══════╩════════╩═══════════╩══════════╝ I want to fetch all the rows from user table with the role other than store. And wanted to include the store role only if it have match in the userstore table. In the output you can see that the id=3 is not available since it doesn't have match from user store.
-39160340 0yes better way is change textbox in razor view @Html.TextboxFor bind automaticaly or other way is you can add
[HttpPost] public ActionResult AddtopoOrderList(string Qty, string ProductName, string Description, string Price, string Amount) { POdb.poOrderList.Add(new PO_OrderList { Qty = Convert.ToInt32(Qty), ProductName = ProductName, Description = Description, UnitPrice = Convert.ToInt16(UnitPrice), Amount = Convert.ToInt16(Amount) }); POdb.SaveChanges(); return RedirectToAction("Index"); } pls give parameter name same as textbox name you given then its work fines
-5867844 0 Change letter case in jEditable input fieldsI would like to change case (all caps or capitalize first letter of sentence) when editing field in place with jEditable plugin. My code looks similar to this:
$(".edit").editable("some/url/", { type : 'text', submitdata: { _method: "put" }, select : true, event : "dblclick", submit : 'OK', cancel : 'cancel', id : 'edititem', name : 'newvalue' }); I would like to add onkeyup function to my input fields, something like onkeyup="javascript:this.value=this.value.toUpperCase()" but I'm really not sure how to do that... Maybe there is some other way to achieve this??
Thanks for any help!
-18754795 0The convention for REST is that we use HttpMethods for CRUD operations selection:
The detailed description: Creating a Web API that Supports CRUD Operations
And then with a very default Routing setting (see more here: Routing in ASP.NET Web API )
routes.MapHttpRoute( name: "API Default", routeTemplate: "api/{controller}/{id}", // the Director as controller defaults: new { id = RouteParameter.Optional } ); So, we've just instructed the Web API infrastructure, that if there is method:
[HttpPost] public void InsertDirector(Director director) ... It will be used for creation, and the HttpMethod used must be POST and
//[HttpPost] [HttpPut] // !! Attention, here is the difference public void UpdateDirector(Director director)... the UpdateDirector will be called if the HttpMethod is PUT
NOTE: because during the update we do have the ID of existing product, the Update method should look like:
// the id parameter is a convention as well, // to be sure that we are updating existing item // so this would be better public void UpdateDirector(int id, Director director)...
-39155598 0 What is the best way to represent constant in YAML? I writing a framework where we represent code in YAML and on the fly it will get converted to Java code.
What is the best way to represent java function in YAML?
Configuration: - name1: "a" - name2: computeName() While parsing YAML, I should be able to parse "a" as string and computeName() as function.
I am looking for best practice so that it will be intuitive and easy for user write YAML.
-12289216 0$('a[id]').closest('li').addClass('active');
-24059510 0 Posting comment as an answer since Bury says it works:
It appears your vr is a character string. If you go this route, you'll need to do the infamous eval(parse(text= paste0('subset(frame,' , vr,')' ))) construction.
Im creating a 2D game. Where the hero moves in a map. Where there are walls which the hero obviously cant go through. And i have enemies that are simple AI. So far the AI just move in random directions. The next step would be introducing another mode for the AI where he knows the hero position and chase him. I know how i calculate the distance betweeen the enemy and the hero. And the angle the enemy need to move to intersect with the hero. But then im stuck and dont known how to make it move in that specific direction. I would really appriciate answers!
Thx!!!
-22665951 0 Why is NullReferenceException being returned when trying to add an object to my cache?This is an asp.net-mvc application and I am trying to add an object, specifically a list of user objects to the cache. I feel like I'm missing a key concept or component when it comes to caching data, so any help would be greatly appreciated.
var cache = new Cache(); cache["Users"] = users; The second line throw's "Object reference not set to an instance of an object. The users variable is not null, I'm certain I'm not creating or using the cache correctly, but cannot find any information in MSDN or SO regarding the right way to set up a cache. What's my mistake?
-20075028 0 Garbage collector going crazyI have just noticed that because of one action(that i am trying to find out) virtual machine stucked few times(looks like Garbage Collector stopped the world). Normally small GC takes 0.05 second and suddently something happened, i can see in logs that it increased to even 15 seconds per one small GC. Virtual Machine was unstable for about 10 minutes.
Is there any way to find out the cause in source code(except asking users what they were doing in that moment)?
Virtual Machine is run in dedicated machine(Linux OS) and i have got access to it only remotely. Total memory used by the process is 6 gb(in the stable moment) so it takes a lot of time to create memory snapshot
-2755665 0TCP has no concept of packets. A TCP stream is a continuous stream of bytes - if you want a structure within that stream of bytes, you have to impose it yourself, by implementing some kind of framing mechanism. A simple one is the "length prefix" - when sending an application-level frame, you first send the length of the frame, then the data.
-21873610 0 jquery.touchwipe.cycle slider NOT WORKING for WINDOWS PHONE TOUCH SWIPEwe have used jquery.touchwipe.cycle JQuery in our site for image slider. Though the touch swipe works fine in iPhone, it does not work in windows phone (lumia 520 | windows 8)
-20959054 0 Why is there a dramatic difference between aov and lmer?I have a mixed model and the data looks like this:
> head(pce.ddply) subject Condition errorType errors 1 j202 G O 0.00000000 2 j202 G P 0.00000000 3 j203 G O 0.08333333 4 j203 G P 0.00000000 5 j205 G O 0.16666667 6 j205 G P 0.00000000 Each subject provides two datapoints for errorType (O or P) and each subject is in either Condition G (N=30) or N (N=33). errorType is a repeated variable and Condition is a between variable. I'm interested in both main effects and the interactions. So, first an anova:
> summary(aov(errors ~ Condition * errorType + Error(subject/(errorType)), data = pce.ddply)) Error: subject Df Sum Sq Mean Sq F value Pr(>F) Condition 1 0.00507 0.005065 2.465 0.122 Residuals 61 0.12534 0.002055 Error: subject:errorType Df Sum Sq Mean Sq F value Pr(>F) errorType 1 0.03199 0.03199 10.52 0.001919 ** Condition:errorType 1 0.04010 0.04010 13.19 0.000579 *** Residuals 61 0.18552 0.00304 Condition is not significant, but errorType is, as well as the interaction.
However, when I use lmer, I get a totally different set of results:
> lmer(errors ~ Condition * errorType + (1 | subject), data = pce.ddply) Linear mixed model fit by REML Formula: errors ~ Condition * errorType + (1 | subject) Data: pce.ddply AIC BIC logLik deviance REMLdev -356.6 -339.6 184.3 -399 -368.6 Random effects: Groups Name Variance Std.Dev. subject (Intercept) 0.000000 0.000000 Residual 0.002548 0.050477 Number of obs: 126, groups: subject, 63 Fixed effects: Estimate Std. Error t value (Intercept) 0.028030 0.009216 3.042 ConditionN 0.048416 0.012734 3.802 errorTypeP 0.005556 0.013033 0.426 ConditionN:errorTypeP -0.071442 0.018008 -3.967 Correlation of Fixed Effects: (Intr) CndtnN errrTP ConditionN -0.724 errorTypeP -0.707 0.512 CndtnN:rrTP 0.512 -0.707 -0.724 So for lmer, Condition and the interaction are significant, but errorType is not.
Also, the lmer result is exactly the same as a glm result, leading me to believe something is wrong.
Can someone please help me understand why they are so different? I suspect I am using lmer incorrectly (though I've tried many other versions like (errorType | subject) with similar results.
-23419903 0Just add this line:
$('[class^=menu]').hide('fadeIn'); Like this:
$(document).ready(function () { //hide all dropdown menus $("#pageHeadings div[class^=menu]").hide(); $("#pageHeadings div[id^=heading]").click(function () { // $(this).find('[class^=menu]').hide(); if (!$(this).find('[class^=menu]').is(":visible")) { $('[class^=menu]').hide('fadeIn'); $(this).find('[class^=menu]').slideToggle("fast"); } }); }); That will hide all others before toggling the current one.
-35003851 0 Is PyramidAdaptedFeatureDetector gone in OpenCV 3?I have an OpenCV 2 C++ program which makes use of PyramidAdaptedFeatureDetector (used over a GoodFeaturesToTrackDetector for a Lukas-Kanade optical flow) and would like to port it to OpenCV 3. However I cannot find any trace of that class in the docs or in the code for OpenCV 3. Has it been removed? What is suggested as a replacement?
I decided to save a file using internal storage into a folder. My code is:
File dir = new File (getFilesDir(), "myFolder"); dir.mkdirs(); File file = new File(dir, "myData.txt"); try { FileOutputStream f = new FileOutputStream(file); PrintWriter pw = new PrintWriter(f); pw.println("Hi"); pw.println("Hello"); pw.flush(); pw.close(); f.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } tv.append("\n\nFile written to "+file); The directory shown is data/data/packageName/file/myFolder/myData.txt However, I wanted to check whether the file contains the strings inputted but i can't seem to find where the created file is. I tried to output the contents of the file but i failed. I know this sounds ridiculous. All i wanna do is to check the contents and also know whether a file is created or not. Can anybody please help?
-27212097 0The first one gets filename from the path, but second one will directly give the uploaded filename via upload control PostedFile property whose properties have information about uploaded file like name,size and extension .
I suggest to use second one, no need of System.IO as control has property which returns filename.
-22471171 0Try calling invalidateLayout on your layout before calling reloadSections:. That will cause the layout to be re-applied after the sections are redrawn, which should cause your footer to redraw.
What would be the most efficient way to say that float value is half of integer for example 0.5, 1.5, 10.5?
First what coming on my mind is:
$is_half = (($number - floor($number)) === 0.5); Is there any better solutions?
-11593960 0 Loading html5 pages which use javascript into a webview for a native iOS AppWas wondering if anyone knew how to load html5 pages which use javascript into a webview in XCode. I keep getting errors and the main one is warning: no rule to process file '$(PROJECT_DIR)/donk/javascript/highlight.pack.js' of type sourcecode.javascript for architecture i386 I have seen apps that can do this. Can someone please let me know how to do this? Would be forever greatful.
Cheers!
-40868428 0 Tree Network in D3 with custom HTMLI am trying to draw a tree like a path in d3 but I haven't been able to make it work. The idea is to have nodes with custom HTML in them. The paths start at the same node and end in the same node. How can I draw this with d3?
Some nodes repeat themselves in different places. For example D happens after C and it also happens after A. Also C happens after A and after D. The start and end is always the same but everything in between is not.
I tried using treant JS and D3 but so far nothing I have done has worked.
Thanks
-40597026 0 regex character appears exactly x timesI'm working in bash and I have a large file in which I want to remove all the lines that do not match a certain regex, probably using $ grep -e "<regex>" <file> > output.txt
What I want to keep is any line that contain exactly x times a specified character, for example in the binary sequence
0000, 0001, 0010, 0011, 0100, 0101, 0111, 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111
I would like to keep only those who have 2 1, leaving me with
0011, 0101, 0110, 1001, 1010, 1100
I would then use a bash variable to vary the amount I need (always exactly half of the length, working with strings of the same length) I'm litterally looking for lines that are half 0 and half 1
I have this right now. It's not using regex. It works, but is very slow:
($1 is the length of every string, $d is just a directory)
sed -e 's/\(.\)/\1 /g' < $d/input.txt > $d/spaces.txt awk '{c=0;for(i=1;i<=NF;++i){c+=$i};print c}' $d/spaces.txt > $d/sums.txt grep -n "$(($1/2))" $d/sums.txt | cut -f1 -d: > $d/linenums.txt for i in $(cat $d/linenums.txt) do sed "${i}q;d" $d/input.txt done > $d/valids.txt In case you wonder this puts spaces in between every digit turning 1010 into 1 0 1 0, then it adds the values together, saves the results in sums.txt, grep for length/2 and save only the line numbers in linenums.txt, then it reads linenums.txt and outputs the corresponding line from input.txt to output.txt
I need something quicker, the for loop is what's taking way too long
Thanks for your time and for sharing your knowledge with me.
-25129810 0zerkms's answer cuts to the gist of what you actually need to know, and is correct. Transaction isolation will make sure you're not affected by concurrency issues in this simple case (but note, it's not a magic solution to all concurrency).
To answer your question literally as written: they're actually interleaved.
If you write:
SELECT SUM(field1)+SUM(field2)+SUM(field3)-SUM(field4) FROM mytable; then Pg reads mytable once. It reads each row and feeds the mytable.field1 to the first sum, mytable.field2 into the second sum, etc. Then it repeats for each row.
So all the aggregation is done in parallel (though not using multiple CPUs).
-1037865 0a short notice on the installation. .NET is as default xcopy-able so you wouldn't need an installer for the exe to be usable. Mail it around (or with the next release of the .NET framework optionaly leave it on a network share)
-19638245 0 C# service: setup returns error 1001. Source MyService already exists on the local computer. EventID 11001Currently I try to create a C# (2010) service.
I have created a visual studio setup project. Whenever I try to install the service I get the message
Error 1001. Source MyService already exists on the local computer. In the eventlog I find the following info:
- System - Provider [ Name] MsiInstaller - EventID 11001 [ Qualifiers] 0 Level 2 Task 0 Keywords 0x80000000000000 - TimeCreated [ SystemTime] 2013-10-28T14:28:23.000000000Z EventRecordID 206256 Channel Application Computer <MyComputer> - Security [ UserID] S-1-5-21-703477020-2137377117-2121179097-8027 - EventData Product: MyServiceSetup -- Error 1001. Error 1001. Source MyService already exists on the local computer. (NULL) (NULL) (NULL) (NULL) (NULL) 7B30353636304544462D374645372D344243312D414442422D4534424244343645393646457D I have tried the following commands (in a command window with admin-rights):
InstallUtil /u MyService.exe and
sc delete MyService But I keep getting this error. I install with sufficient rights. And I have absolutely no idea where I have to look for the solution.
Can somebody please help me? I have almost no hair left to pull out...
Thanx!!!
-1461672 0 Sorting Two Combo Boxes Differently in WPFI have in a form two combo boxes that have the exact itemssource property. Both combo boxes need to be sorted, but in two different ways. One is sorted by the ID (numeric), the other one by Name(Alphabetic).
Is it possible to do such a thing?
Thanks
-33100847 0 Global variable inside of functionCode below prints produces error:
Notice: Undefined variable: x in C:\wamp\www\h4.php on line 9 and output:
Variable x inside function is: Variable x outside function is: 5 Code:
<html> <body> <?php $x = 5; // global scope function myTest() { // using x inside this function will generate an error echo "<p>Variable x inside function is: $x</p>"; } myTest(); echo "<p>Variable x outside function is: $x</p>"; ?> </body> </html> What gets wrong with x global variable inside of myTest function?
I have weird problem with event.preventDefault. This works fine on Chrome but doesn't work on Firefox. I know many people fix it by adding event arg like this: myFunction(event) but doing this makes it stop working on both Chrome and Firefox. Can someone help me get this code working on all browsers?
<script type="text/javascript"> function myFunction() { var asdf = $('input[name=payment_type]:checked', '#buy').val() if (asdf == 'theRightOne') { event.preventDefault() alert("stuff") } } </script>
-14595845 0 Gtkmm getting label color I do not have a code error, I have just looked everywhere and cannot figure out how to do this. I want to get the color of a Gtk::widget, the Gtk::label. I can override the color of a label like this: l.override_color( c, l.get_state_flags() ); , but I have no idea how to get that color back from the label, thanks!
-9008252 0To start an app you need to call CeCreateProcess. Registry access starts with CeRegOpenKeyEx (there are reads, writes, etc too). All of these are also wrapped in managed code in this open-source library.
My way of doing this is simple:
In this way, I can keep track of users accurately to the minute. Just divide by 60 to get the hours.
-5280646 0Add 3 to your allocation amount. Allocate the memory. If the returned address isn't already a multiple of 4, round it up until it is. (The most you'd have to round up is 3, which is why you pad your allocation by that much in advance.)
When you free the memory, remember to free the original address, not the rounded-up value.
-20091695 0Try this:
string myscript = "$('a.fancybox-messageboard').fancybox({ width: 600, height: 440,closeClick: true, hideOnOverlayClick: true, href: 'http://upload.wikimedia.org/wikipedia/commons/1/1a/Bachalpseeflowers.jpg' }).trigger('click');" ScriptManager.RegisterClientScriptBlock(this, this.GetType(), Guid.NewGuid().ToString(), "<script>" + myscript + "</script>", false);
-29298688 0 Add all the spans to your HTML, but hide them initially. Then use an if statement to show the one you want.
function calculate() { var myBox1 = document.getElementById('box1').value; var myBox2 = document.getElementById('box2').value; var myBox3 = document.getElementById('box3').value; var result = document.getElementById('result'); var divide = (document.getElementById('changeValue').checked ? 35 : 25); var myResult = myBox1 * myBox2 * myBox3 / divide; var links = document.getElementsByClassName("link"); for (var i = 0; i < links.length; i++) { links[i].style.display = "none"; } var linkToShow; if (myResult < 30) { linkToShow = 0; } else if (myResult < 50) { linkToShow = 1; } else if (myResult < 70) { linkToShow = 2; } else { linkToShow = 3; } links[linkToShow].style.display = "inline"; result.value = myResult.toFixed(2) + ' eggs'; } .link { display: none; } <input type="text" id="box1" oninput="calculate()" /> <input type="text" id="box2" oninput="calculate()" /> <input type="text" id="box3" oninput="calculate()" /> <input id="result" /> <a class="link" href="link-1">link-1</a> <a class="link" href="link-2">link-2</a> <a class="link" href="link-3">link-3</a> <a class="link" href="link-4">link-4</a> <br /> <br /> <br /> <input type="checkbox" name="changeValue" id="changeValue" /> <label for="changeValue">Divide with 35</label> The way you are storing data breaks normalization rules. Only a single atomic value should be stored in each field. You should store each item in a single row.
-15627355 0From the error log i.e. MediaPlayer Event 11 was not found in the queue, already cancelled is a warning and not an error. Please refer to this link. Hence, if your MediaPlayer is exiting, then there should be some other issue.
This warning is printed when an event which was expected to be triggered gets removed from the queue before it actually triggered. This can happen in multiple cases. For example, in case of pause, all player events are cancelled as shown here.
In your case, I feel that one of the potential scenario would be thus. AwesomePlayer would have triggered an event to read the next video frame from the video decoder i.e. mVideoSource. In between you pressed pause which caused all events to be removed. So when TimedEventQueue triggered in this threadRun loop, it would observe that this event has been removed and hence, the log.
That’s a runtime exception so the compiler can’t help you with catching it at a compile time. And the try-catch block helps you to handle this exception, not to prevent it from being thrown at the runtime. If you don’t make a try-catch block it will be handled at a general application level.
A quote from MSDN:
When an exception is thrown, the common language runtime (CLR) looks for the catch statement that handles this exception. If the currently executing method does not contain such a catch block, the CLR looks at the method that called the current method, and so on up the call stack. If no catch block is found, then the CLR displays an unhandled exception message to the user and stops execution of the program.
Please refer to the MSDN try-catch for more information.
-21804382 0 Completely stuck on where to start on programingI've been given a task to produce a webpage which solves the quadratic formula. Talking to friends they have said the simplised way is to learn java script and build the webpage. I have been learning the language on code academy and that's fine but where and how do I i write in my own code and execute it for java script? All I have been using so far is the editor page on code academy. Im completely lost in where to go next
-4730448 0I'm not sure php is the right tool here. Why not use something that is closer to the shell environment, like a bash script?
The only reason I can imagine you want to use PHP is so you can start the process by clicking a link on a page somewhere, and thereby punch a large hole in whatever security your system supposedly has. But if you really must, then it is still easier to write a script in a more shell friendly language and simply use php as a gateway to invoke the script.
-2510115 0 jQuery: Can I call delay() between addClass() and such?Something as simple as:
$("#div").addClass("error").delay(1000).removeClass("error");
doesn't seem to work. What would be the easiest alternative?
-7819402 0 How to open a config file app settings using ConfigurationManager?My config file is located here:
"~/Admin/Web.config" I tried opening it via the below code but it didn't work:
var physicalFilePath = HttpContext.Current.Server.MapPath("~/Admin/Web.config"); var configMap = new ConfigurationFileMap(physicalFilePath); var configuration = ConfigurationManager.OpenMappedMachineConfiguration(configMap); var appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings"); when appsettings line runs, it throws the below error message:
Unable to cast object of type 'System.Configuration.DefaultSection' to type 'System.Configuration.AppSettingsSection'. My Web.Config looks like below:
<?xml version="1.0"?> <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"> <appSettings> <add key="AdminUsername" value="Test1"/> <add key="AdminPassword" value="Test2"/> </appSettings> <connectionStrings></connectionStrings> </configuration> How could I get the appsettings?
-7051243 0This will work in quirks mode, but the browser which is compatible with standard mode will not work depend upon your doctype. Avoiding quirks mode is one of the keys to successfully producing cross-browser compatible web content
Some modern browsers have two rendering modes. Quirk mode renders an HTML document like older browsers used to do it, e.g. Netscape 4, Internet Explorer 4 and 5. Standard mode renders a page according to W3C recommendations. Depending on the document type declaration present in the HTML document, the browser will switch into either quirk mode or standard mode. If there is no document type declaration present, the browser will switch into quirk mode.
http://www.w3.org/TR/REC-html32#dtd
JavaScript should not behave differently; however, the DOM objects that JavaScript operates on may have different behaviors.
-37803892 0The API is // Hopefully your alarm will have a lower frequency than this! alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, AlarmManager.INTERVAL_HALF_HOUR, AlarmManager.INTERVAL_HALF_HOUR, alarmIntent); Details : https://developer.android.com/training/scheduling/alarms.html
-10222772 0 I'm new with WTForms but it seems to me that the solution could be improved instead of using :
{{ form.field(autofocus=true, required=true, placeholder="foo") }} use :
{% if field.flags.required %} {{ field(autofocus=true, required=field.flags.required, placeholder="foo") }} {% else %} {{ field(autofocus=true, placeholder="foo") }} {% endif %} WTForms seems not to handle correctly required=false for 100% HTML5 and sets in the HTML an attr required="False" instead of removing the attr. Could this be improved in next version of WTForms?
I have a box that is initiated without a frame so it has 0 center and size.
let blackBox = UIView() blackBox.backgroundColor = .blackColor() blackBox.translatesAutoresizingMaskIntoConstraints = false view.addSubview(blackBox) view.addConstraint(NSLayoutConstraint(item: blackBox, attribute: .Width, relatedBy: .Equal, toItem: view, attribute: .Width, multiplier: 0.1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: blackBox, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Height, multiplier: 0.5, constant: 0)) view.addConstraint(NSLayoutConstraint(item: blackBox, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: blackBox, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1, constant: 0)) Is there anyway to insert a centered subview into the blackBox without using autolayout or is there a neater way I could/should use it. The only way I can see this happening is:
let blueBox = UIView() blackBox.addSubview(blueBox) blueBox.translatesAutoresizingMaskIntoConstraints = false blueBox.backgroundColor = UIColor.blueColor() view.addConstraint(NSLayoutConstraint(item: blueBox, attribute: .CenterX, relatedBy: .Equal, toItem: blackBox, attribute: .CenterX, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: blueBox, attribute: .CenterY, relatedBy: .Equal, toItem: blackBox, attribute: .CenterY, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: blueBox, attribute: .Width, relatedBy: .Equal, toItem: blackBox, attribute: .Width, multiplier: 0.4, constant: 0)) view.addConstraint(NSLayoutConstraint(item: blueBox, attribute: .Height, relatedBy: .Equal, toItem: blackBox, attribute: .Height, multiplier: 0.4, constant: 0))
-38393992 1 Error while creating folder using google drive api I have activated drive api using this link:https://developers.google.com/drive/v3/web/quickstart/python. Quickstart.py is working fine and can read metadata.
Now i am trying to create a folder in a parent folder using parent id.Program is working fine till verification but no folder is getting created.I am just stuck here.Even console is not giving any errors. Plz find full code below and if possible suggest somthing.
import os import httplib2 # pip install --upgrade google-api-python-client from oauth2client.file import Storage from apiclient.discovery import build from oauth2client.client import OAuth2WebServerFlow # Copy your credentials from the console # https://console.developers.google.com CLIENT_ID = 'xxxxxxxxxx.apps.googleusercontent.com' CLIENT_SECRET = 'yyyyyyyyyyyyy' OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive' REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob' OUT_PATH = os.path.join(os.path.dirname(__file__), 'out') CREDS_FILE = os.path.join(os.path.dirname(__file__), 'credentials.json') storage = Storage(CREDS_FILE) credentials = storage.get() if credentials is None: # Run through the OAuth flow and retrieve credentials flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI) authorize_url = flow.step1_get_authorize_url() print 'Go to the following link in your browser: ' + authorize_url code = raw_input('Enter verification code: ').strip() credentials = flow.step2_exchange(code) storage.put(credentials) # Create an httplib2.Http object and authorize it with our credentials http = httplib2.Http() http = credentials.authorize(http) drive_service = build('drive', 'v2', http=http) def createRemoteFolder(self, folderName, parentID = '0B-mk9lmuB70PTkIwUmtMeEREaEU'): # Create a folder on Drive, returns the newely created folders ID body = { 'title': folderName, 'mimeType': "application/vnd.google-apps.folder" } if parentID: body['parents'] = [{'id': parentID}] root_folder = drive_service.files().insert(body = body).execute() return root_folder['id']
-16874029 0 For Python 3
positionNewD = {k: (x, -y) for k, (x, y) in positionD.items()} ... as iteritems() has been renamed items()
http://docs.python.org/3.1/whatsnew/3.0.html#views-and-iterators-instead-of-lists
-33757717 0It's just wrong call parametters.
If you want to change your code, this solution can help you.
Class GUI just inherits from Canvas and doesn't implement anything.
from Tkinter import* root = Tk() class GUI(Canvas): '''inherits Canvas class (all Canvas methodes, attributes will be accessible) You can add your customized methods here. ''' def __init__(self,master,*args,**kwargs): Canvas.__init__(self, master=master, *args, **kwargs) polygon = GUI(root) polygon.create_polygon([150,75,225,0,300,75,225,150], outline='gray', fill='gray', width=2) polygon.pack() root.mainloop() For more help add comments.
-20365954 0 Entity Framework: DefiningQuery errorI have a Junction table with clustered index
CREATE TABLE [dbo].[MeetingTags] ( [MeetingId] INT NOT NULL, [TagId] INT NOT NULL, CONSTRAINT [FK_MeetingTags_Tags] FOREIGN KEY ([MeetingId]) REFERENCES [dbo].[Meetings] ([Id]), CONSTRAINT [FK_Tags_MeetingTags] FOREIGN KEY ([TagId]) REFERENCES [dbo].[Tags] ([Id]) ); GO CREATE CLUSTERED INDEX [cdxMeetingTags] ON [dbo].[MeetingTags]([MeetingId] ASC, [TagId] ASC); Obviously, it has common field of the table Meetings and Tags so that I can add record on it by this way
var tag= new Tag() { Title = "Meeting Title", }; meeting.Tags.Add(tag); Looks good, however I'm getting this error in Context.SaveChanges() when Inserting new Tags record.
Unable to update the EntitySet 'MeetingTags' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation Tags has Primary Key.
I think putting a Primary Key in the MeetingTags is not possible as it will break the Many-to-Many relationship of Meeting and Tags in the EF, and it will also add Meeting.MeetingTags.Tags in the syntax instead of just Meeting.Tags
Any workaround on this?
-4794785 0Take a look at Xtext. It's a framework on top of the eclipse platform that autogenerates much of the infrastructure (like syntax highlighting and autocomplete) from the language grammar - basically you get a pretty powerful editor in minutes rather than months of work.
-2033822 0You have to check everything is the same...
Edit: What was it of my list, out of interest please?
-6567405 0Download Web Matrix from
http://www.microsoft.com/web/webmatrix/
http://www.microsoft.com/web/post/add-a-photo-gallery-to-your-website-using-lightbox-and-javascript
-25607090 0There is no significant difference between these, you will get pretty much the same results:
str.Split(';').First() vs. str.Split(';')[0] For your second comparison, here you are asking only the first element
list.Where(x => x > 1).First() So as soon as WhereIterator returns an item it's done. But in second you are putting all results into list then getting the first item using indexer , therefore it will be slower.
Calculating your angle using just x value seem strange, try this:
angle = Math.atan( (startY - endY) / (startX - endX) ); // in rad This will give you the angle in radian.
For calculating the velocity you must have a timing variable between the start and the end touch. You can use getTimer() to get beginTime and endTime in your functions onTouchBegin and onTouchEnd respectively.
After that you just have to calculate velocity with distance and time.
distance = Math.sqrt( ((startX - endX)*(startX - endX)) / ((startY - endY)*(startY - endY)) ); velocity = distance / (endTime-beginTime); // in pixel/ms Hope that helps ;)
-1907218 0You could do something like this:
public class MyString { public static implicit operator string(MyString ms) { return "ploeh"; } } The following unit test succeeds:
[TestMethod] public void Test5() { MyString myString = new MyString(); string s = myString; Assert.AreEqual("ploeh", s); } In general however, I don't think this is a sign of good API design, because I prefer explicitness instead of surprises... but then again, I don't know the context of the question...
-40393257 0I agree with JDillon's answer to set the data-src and then switch the src when ready to init the player. Like so:
html
<iframe id="sc-widget" width="0" height="0" scrolling="no" frameborder="no" src="" data-src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/3333333%3Fsecret_token%3Dx-xxxx&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&visual=true"></iframe> js (es6)
let widgetIframe = document.getElementById('sc-widget') widgetIframe.src = widgetIframe.dataset.src let $embedPlayer = SC.Widget(widgetIframe) /* example of using soundcloud embed player */ $embedPlayer.bind(SC.Widget.Events.PLAY, () => { $embedPlayer.getDuration((duration) => setDuration(duration)) }) $embedPlayer.bind(SC.Widget.Events.PLAY_PROGRESS, () => { $embedPlayer.getPosition((position) => setPosition(position)) }) function setPosition(pos) { console.log(pos) } function setDuration(dur) { console.log(dur) } Then I also agree with adi's answer that you cannot use display: none; to hide the player if you are creating your own player to control the soundcloud embed player. In this case you need to hide it with the following styles:
css
iframe { max-width: 10rem; opacity: 0; position: absolute; visibility: hidden; }
-1994963 0 Did you take a look at the Go tutorial at http://golang.org/doc/go_tutorial.html
Here's how to compile and run our program. With 6g, say, $ 6g helloworld.go # compile; object goes into helloworld.6 $ 6l helloworld.6 # link; output goes into 6.out $ 6.out Hello, world; or Καλημέρα κόσμε; or こんにちは 世界 $ With gccgo it looks a little more traditional. $ gccgo helloworld.go $ a.out Hello, world; or Καλημέρα κόσμε; or こんにちは 世界-26989491 0
You have some bugs in your getMessages function in the while loop:
1. use count += len(rs)
2. The major bug: you don't need the
or len(rs) < 10 condition because SQS can get up to 10 messages and if your queue is full and each time you get 10 messages you'll have an infinite loop.
Also I think you should consider using yield statement to return the messages, process them and after they are processed, only then , remove them from Queue.
One more thing, the pythonic way to check if len(rs) < 1: is if not rs:
I'm writing a Qt (5.3) program which has a joystick test UI in it, but I need a separate thread for an infinite while loop looking for joystick axis/button value changes through SDL. That part of the code is working fine as I can have the thread qDebug() messages and it seems to work. But from the main window, when I try to open the test joystick UI, the program crashes. I've had the test joystick UI running separation WITHOUT the JoystickThread thread and it seems to open up fine.
The error messages are inconsistent though - some times, I just get
The program has unexpectedly finished. /home/narendran/QtWorkspace/build-LinkControl-Desktop-Debug/LinkControl crashed
This has shown up once:
QXcbWindow: Unhandled client message: "_GTK_LOAD_ICONTHEMES"
And a few other times:
[xcb] Unknown sequence number while processing queue [xcb] Most likely this is a multi-threaded client and XInitThreads has not been called [xcb] Aborting, sorry about that. star: ../../src/xcb_io.c:274: poll_for_event: Assertion `!xcb_xlib_threads_sequence_lost' failed.
I found that this was common if XInitThreads(); is not run in the main function, but even with it on there, it crashes with the same error(s).
main.cpp
#include <qsplashscreen.h> #include "linkcontrol.h" #include "configure.h" #include <unistd.h> #include <QApplication> #include <QPixmap> #include <QStyle> #include <QDesktopWidget> #include "linkports.h" #include "joystickthread.h" #include <X11/Xlib.h> int main(int argc, char *argv[]) { XInitThreads(); QApplication a(argc, argv); QPixmap pix(":splash.png"); QSplashScreen splash(pix); splash.show(); a.processEvents(); JoystickThread jsThread; jsThread.start(); LinkControl linkcontrol; usleep(1000000); splash.finish(&linkcontrol); usleep(100000); linkcontrol.show(); linkcontrol.setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter,linkcontrol.size(),a.desktop()->availableGeometry())); return a.exec(); } The actual thread is in joystickthread.cpp
#include "joystickthread.h" #include "global.h" #include "unistd.h" /* JoystickThread::JoystickThread(int _interval) { this->interval_us = _interval; } */ void JoystickThread::run() { while(1) { if(joystick->connected) { joystick->updateJSData(); // Check for changed values for(int i=0; i<joystick->axis.count(); i++) { if(joystick->axis.value(i) != joystick->axis_last[i]) { joystick->axisUpdateEmit(i); // qDebug() << "AXIS: " << i << "\tVALUE: " << joystick->axis.value(i); } joystick->axis_last[i] = joystick->axis.value(i); } for(int i=0; i<joystick->button.count(); i++) { if(joystick->button.value(i) != joystick->button_last[i]) { joystick->btnUpdateEmit(i); // qDebug() << "BUTTON: " << i << "\tVALUE: " << joystick->button.value(i); } joystick->button_last[i] = joystick->button.value(i); } } usleep(2500); } } The function that causes the program to crash is in linkcontrol.cpp
void LinkControl::on_actionJoystick_Test_triggered() { qDebug() << "STARTING CHECK"; if(!js_test->initialized) { qDebug() << "NOT INIT"; js_test = new TestJoystick(); js_test->initialized = true; qDebug() << "FININSH INIT"; } if(joystick->connected) { qDebug() << "SHOWING UI"; js_test->show(); } else { QMessageBox::critical(this, tr("No Joystick Connected!"), tr("Please connect a joystick first...")); } } Where js_test is declared as a TestJoystick object in the linkcontrol.h file
public: explicit LinkControl(QWidget *parent = 0); QSlider *portSliders[16]; QLineEdit *setVals[16]; SerialTerminal *ser_term; TestJoystick *js_test; ~LinkControl(); Thank you very much! Please let me know if you need anymore information.
-18603273 0 NodeJS Code Coverage of Automated TestsAs part of a custom testing framework for a NodeJS REST API, I'd like to automatically detect when my tests are no longer providing proper coverage by comparing all possible outcomes with what the test suite received.
What methods exist for doing this? We can assume that it's being used for a REST API with a list of entry functions (API endpoints) that need coverage analysis, and each entry function will end with a known 'exit function' that responds to the requester in a standard way.
Here's what I've found so far:
1: Basic solution (Currently implemented)
Pros: Very basic and easy to use; Doesn't change performance testing times
Cons: Highly prone to error with lots of manual checking; Doesn't flag any issues if there are 5 ways to 'FailDueToX' and you only test 1 of them. Very basic definition of 'coverage'
2: Static analysis
Pros: Automatic; Catches the different branches that may result in the same output code
Cons: Generating the parse tree is non trivial; Doesn't detect dead code that never gets run; test suite needs to be kept in sync
3: Profiling
I've done this in the past on Embedded Systems with GreenHills Code Coverage Tools
Pros: Semi Automatic; Gives more information about total coverage to a developer; Can see
Cons: Slows down the tests; Unable to do performance testing in parallel; Doesn't flag when a possible outcome is never made to happen.
What else is there, and what tools can help me with my Static Analysis and Profiling goals?
-39745238 0Using java 8 shouldn't give this problem but it did for me
I created my jar initially from Eclipse Export -> Runnable Jar and it was fine. When I moved to Maven it failed with the above.
Comparing the two jars showed that nothing fx related was packaged with the jar (as I'd expect) but that the Eclipse generated manifest had Class-Path: . in it. Getting maven to package the jar with the following worked for me (with Java 8)
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <configuration> <archive> <manifest> <addClasspath>true</addClasspath> <mainClass>com.pg.fxapplication.Main</mainClass> </manifest> <manifestEntries> <Class-Path>.</Class-Path> </manifestEntries> </archive> </configuration> </plugin> </plugins> </build>
-24218714 0 What is imageAdapter.mThumbIds[position]? I think you should try this.
imageView.setImageResource(MainActivity.ICONS[position]);
-35866624 0 openweathermap API issue with mobile appI am using openweathermap API in my iOS app.
Below is my URL which i am call for get whether info.
While open this url in browser i got response properly.
But when i call Web-service from my iOS app i do not get response. I get below error :
{ cod = 401; message = "Invalid API key. Please see http://openweathermap.org/faq#error401 for more info."; } I had created API key from this URL : Create API key on Open Wheather
-30672928 0 MATLAB error in ode45: must return a column vectorI am getting this error in my code:
But in the MATLAB documentation there is an example Example 3 where the vectors are given as input but it works just fine. Why is that I get an error in my code?
This is my code:
Ca_ER = 10e-6; c0 = 2e-6; c1 = .185; v1 = 6; v2 = .11; v3 = .09e6; v4 = 1.2; k3 = .1e-6; a1 = 400e6; a2 = 0.2e6; a3 = 400e6; a4 = 0.2e6; a5 = 20e6; b2 = .21; d1 = 0.13e-6; d2 = b2/a2; d3 = 943.4e-9; d4 = d1*d2/d3; d5 = 82.34e-9; IP= .5e-6; Ca=.001e-6:.01e-6:1e-6; num=Ca.*IP.*d2; deno= (Ca.*IP+ IP*d2+d1*d2+Ca.*d3).*(Ca+d5); p_open=( num./deno).^3; %this is the vector input dc=@(t,c) (c1.*((v1.*p_open)+v2).*(Ca_ER-c))-((v3.*(c.^2))/(c.^2+(k3^2))); [t,c]=ode45(dc,linspace(0, 100, 1000),.19e-6); plot(t,c);
-19899982 0 Apple doesn't offer support for that, but one workaround could be to use a category for UIImage with a method that loads the right version based on the OS version:
+(UIImage)imageNamed2:(NSString *)imageName{ NSString *finalImageName; if([[UIDevice currentDevice].systemVersion floatValue] >= 7){ finalImageName = [NSString stringWithFormat:@"ios7-%@",imageName]; }else{ finalImageName = imageName; } return [self imageNamed:finalImageName]; } This way, the images would be named:
example.png example@2x.png ios7-example@2x.png And you can instantiate the image this way:
[UIImage imageNamed2:@"example.png"]; Hope this helps
-949006 0You can use the bash(1) built-in compgen
compgen -c will list all the commands you could run.compgen -a will list all the aliases you could run.compgen -b will list all the built-ins you could run.compgen -k will list all the keywords you could run.compgen -A function will list all the functions you could run.compgen -A function -abck will list all the above in one go.Check the man page for other completions you can generate.
To directly answer your question:
compgen -ac | grep searchstr should do what yout want.
-12891500 0 asp.net website builds fine but publish gives errorI am working on asp.net website using ablecommerce asp.net CMS. I am trying to build the website and it works. but when I try to publish the website locally to deploy it on IIS, I start getting errors that this page is not available etc. I see that the page not found errors are actually located in some dll and reference is added.
Errors are like this:
Error 5 The type or namespace name 'admin_orders_create_creditcardpaymentform_ascx' does not exist in the namespace 'ASP' (are you missing an assembly reference?) \Final Code\WebSite\Admin\Orders\Create\CreateOrder4.aspx.cs Regards, Asif Hameed
-9119303 0Not exactly what you were asking for but as a Java programmer that spent some time with Scala I've liked Google Guava implementation of Optional idiom.
Elvis and Safe Operator Proposal didn't make it into Java 7, maybe for 8. This stackoverflow topic may be a interesting read too.
I access my page at http://web.dev/web/app_behat.php and it works when I do it manually in browser.
So I set
base_url: "http://web.dev/web/app_behat.php/" and I get no route matched for any route but if i set
base_url: "http://web.dev/app_behat.php/" route seems to be matched but i get missing table error, i have set up SymfonyDoctrineContext to take care of schema creation.
Full behat.yml:
default: formatter: name: progress context: class: FootballRadar\Features\Context\FeatureContext extensions: Behat\Symfony2Extension\Extension: mink_driver: true kernel: env: test debug: true Behat\MinkExtension\Extension: base_url: "http://web.dev/app_behat.php/" default_session: symfony2 show_cmd: 'open -a "Google Chrome" %s' EDIT:
My config_behat.yml:
imports: - { resource: "config_dev.yml" } assetic: debug: true use_controller: enabled: true profiler: false framework: test: ~ session: storage_id: session.storage.mock_file profiler: collect: false web_profiler: toolbar: false intercept_redirects: false swiftmailer: disable_delivery: true doctrine: dbal: connections: default: driver: pdo_sqlite user: behat path: %kernel.root_dir%/behat/default.db.cache charset: utf8 model: driver: pdo_sqlite user: behat path: %kernel.root_dir%/behat/model.db.cache charset: utf8 monolog: handlers: test: type: test Seems that all of You misunderstood my question and/or completely ignored my first sentence.
I have a working application and I access it using
http://web.dev/web/ (http://web.dev/web/app.php/) <-- for prod
http://web.dev/web/app_dev.php/ <-- for dev
http://web.dev/web/app_behat.php/ <-- for behat
all of them work as when i use them manually in chrome or other browser
That is why I am surprised why http://web.dev/web/app_behat.php/ gives me
No route found for "GET /web/app_behat.php/login" and
http://web.dev/app_behat.php/ gives
SQLSTATE[HY000]: General error: 1 no such table: users_new With little debugging I confirmed SymfonyDoctrineContext does read my entities mappings and issues queries to create db schema, both db files have read/write permissions (for sake of test I gave them 777)
Another thing I just realised, all this errors gets written to test.log file instead of behat.log. I create kernel with $kernel = new AppKernel('behat', true);
Maybe I just greatly misunderstood how behat is supposed to work?
EDIT2:
I have noticed that there are no entries made to apache access log when running behat feature for either of the paths
versions i'm using from composer.json
"behat/behat": "2.5.*@dev", "behat/common-contexts": "1.2.*@dev", "behat/mink-extension": "*", "behat/mink-browserkit-driver": "*", "behat/mink-selenium2-driver": "*", "behat/symfony2-extension": "*",
-32783381 0 Assuming you still can get the node by id, you can check if the Name property is null
string.IsNullOrEmpty(node.Name) It's not pretty but should work
-36260897 0 Why slide show didn't work in live preview?1-Why slide show didn't work in live preview?
it working in my desktop but when i share it in live preview it didn't work
<div class="slide-show-content"><!-- /image gallery slideshow--> <div class="slide-show-default"> <div class="container"> <div class="row"> <div id="app" class="col-xs-12"> <div id="wrapper-sliderTv"> <!-- sliderTV html--> <div id="sliderTV" class="sliderTV"> <!-- slidable items in carousel --> <div id="item-0" class="sliderTV__item"> <h1>Amélie</h1> <img src="assets/amelie.jpg"> </div> <div id="item-1" class="sliderTV__item"> <h1>Django Unchained</h1> <img src="assets/django-unchained.jpg"> </div> <div id="item-2" class="sliderTV__item"> <h1>Fight Club</h1> <img src="assets/fight-club.jpg"> </div> <div id="item-3" class="sliderTV__item"> <h1>Forrest Gump</h1> <img src="assets/forrest-gump.jpg"> </div> <div id="item-4" class="sliderTV__item"> <h1>Inglourious Basterds</h1> <img src="assets/inglourious-basterds.jpg"> </div> <div id="item-5" class="sliderTV__item"> <h1>Inside Out</h1> <img src="assets/inside-out-2015.jpg"> </div> <div id="item-6" class="sliderTV__item"> <h1>Interstellar</h1> <img src="assets/interstellar.jpg"> </div> <div id="item-7" class="sliderTV__item"> <h1>Léon: The Professional</h1> <img src="assets/leon-the-professional.jpg"> </div> <div id="item-8" class="sliderTV__item"> <h1>San Andreas</h1> <img src="assets/san-andreas.jpg"> </div> <!-- optional navigational arrows --> <div class="sliderTV__prev">❰</div> <div class="sliderTV__next">❱</div> </div> </div> </div> </div> </div> </div> 2-why when i used owl carousel slider let some other jquery hidden?
here the problem it hidden when i use in same section the owl carousel
<li class="body"> <div class="collapse" id="media-one"> <div class="body-content"> <div class="icons-default"><!--icons--> <div class="icons"> <ul class="icons-content"> <li> <button class="btn" type="button"> <i class="fa fa-commenting"></i> </button> <span>comment</span> </li> <li> <button class="btn" type="button"> <i class="fa fa-heart"></i> </button> <span>like</span> </li> <li> <button class="btn" type="button"> <i class="fa fa-share-alt"></i> </button> <span>share</span> </li> </ul> </div> </div> <div class="comments"><!-- comments--> <ul class="comments-content clearfix"> <!-- item 1--> <li class="img"> <img src="imgs/media/post-profile.png" alt="//" /> </li> <li class="details"> <span class="head">Mohamed Samy</span> <span class="text"> Praesent ac condimentum felis. Nulla at nisl orci, at dignissim dolor raesent ac condimentum felis </span> </li> </ul> <ul class="comments-content clearfix"> <!-- item 2--> <li class="img"> <img src="imgs/media/post-profile.png" alt="//" /> </li> <li class="details"> <span class="head">Mohamed Samy</span> <span class="text"> Praesent ac condimentum felis. Nulla at nisl orci, at dignissim dolor raesent ac condimentum felis </span> </li> </ul> <ul class="comments-content clearfix"> <!-- item 3--> <li class="img"> <img src="imgs/media/post-profile.png" alt="//" /> </li> <li class="details"> <span class="head">Mohamed Samy</span> <span class="text"> Praesent ac condimentum felis. Nulla at nisl orci, at dignissim dolor raesent ac condimentum felis </span> </li> </ul> </div> </div> </div> </li> i hope my question is clear now
live link
http://atonvision.github.io/mediadata/
-8225900 0Further to Gabe's answer, I can confirm that the difference appears to be caused by the cost of re-constructing the delegate for every call to GetPointData.
If I add a single line to the GetPointData method in your IterationRangeLookupSingle class then it slows right down to the same crawling pace as LinqRangeLookupSingle. Try it:
// in IterationRangeLookupSingle<TItem, TKey> public TItem GetPointData(DateTime point) { // just a single line, this delegate is never used Func<TItem, bool> dummy = i => i.IsWithinRange(point); // the rest of the method remains exactly the same as before // ... } (I'm not sure why the compiler and/or jitter can't just ignore the superfluous delegate that I added above. Obviously, the delegate is necessary in your LinqRangeLookupSingle class.)
One possible workaround is to compose the predicate in LinqRangeLookupSingle so that point is passed to it as an argument. This means that the delegate only needs to be constructed once, not every time the GetPointData method is called. For example, the following change will speed up the LINQ version so that it's pretty much comparable with the foreach version:
// in LinqRangeLookupSingle<TItem, TKey> public TItem GetPointData(DateTime point) { Func<DateTime, Func<TItem, bool>> builder = x => y => y.IsWithinRange(x); Func<TItem, bool> predicate = builder(point); return this.items.FirstOrDefault(predicate); }
-19787198 1 Logging in web2py I'm working on a web application that handles a bit of traffic. I tried using FileHandler, set up when handling each request, for logging but that resulted in wsgi crashing from too many open files, current limit is 1024 which seems reasonable.
How do people handle logging when dealing with a bit of traffic? Is there a way for the wsgi process to use one filehandle for all requests?
-40384521 0 R: replace values in a vector before and after a condition is metConsider a vector with missing values:
myvec <- c('C', NA, 'test', NA, 'D') [1] "C" NA "test" NA "D" How to replace all the elements in the vector before 'test' with, say, 'good' and after it with 'bad'? The outcome should be:
[1] "good" "good" "test" "bad" "bad" My attempt below succeeds only in replacing everything with 'good', which is not so good:
replace(myvec, is.na(myvec) | myvec!='test', 'good') [1] "good" "good" "test" "good" "good"
-34526156 0 HTML5 Notification With PHP I noticed Facebook started using the HTML5 notification for desktop and I thought I would start dabbling in it for fun for my blog. My idea is pretty simple: new blog comes out, apache cronjob runs every X minutes and calls a file, does some PHP wizardry and out goes the notification.
I have looked online and found examples using node.js and angular, but I'm not comfortable using either of those so I'd rather stick with PHP.
Here is my process: The user goes to my blog and will click a button to allow notifications. For brevity, the below code sends the users a notification when they click the "notify" button. This works perfectly, and in theory should subscribe them to any future notifications.
if ('Notification' in window) { function notifyUser() { var title = 'example title'; var options = { body: 'example body', icon: 'example icon' }; if (Notification.permission === "granted") { var notification = new Notification(title, options); } else if (Notification.permission !== 'denied') { Notification.requestPermission(function (permission) { if (permission === "granted") { var notification = new Notification(title, options); } }); } } $('#notify').click(function() { notifyUser(); return false; }); } else { //not happening } You can see the fiddle of the above.
Access to the user is granted and now I should be able to send them notifications whenever I want. Awesome! I then write up a blog entry and it has the ID of XYZ. My cronjob goes and calls the following PHP script, using the above node.js example as a template.
(In this example I am just calling the script manually from my phone and watching my desktop screen. Since my desktop is "subscribed" to the same domain, I think the following would/should work.)
$num = $_GET['num']; $db = mysql_connect(DB_HOST, DB_USER, DB_PASS); if($db) { mysql_select_db('mydb', $db); $select = "SELECT alert FROM blog WHERE id = ".$num." && alert = 0 LIMIT 1"; $results = mysql_query($select) or die(mysql_error()); $output = ''; while($row = mysql_fetch_object($results)) { $output .= "<script> var title = 'new blog!'; var options = { body: 'come read my new blog!', icon: 'same icon as before or maybe a new one!' }; var notification = new Notification(title, options); </script>"; $update = "UPDATE blog SET alert = 1 WHERE id = ".$num." && alert = 0 LIMIT 1"; mysql_query($update) or die(mysql_error()); } echo $output; } I then check the database and blog entry XYZ's "alert" is now set to "1", yet my desktop browser never got notified. Since my browser is subscribed to the same URL that is pushing out the notification, I would imagine I'd get a message.
Either I'm doing something wrong (perhaps PHP isn't the right language for this?), or I'm misunderstanding the spec. Could somebody help point me in the right direction? I think I'm missing something.
Thanks a lot.
Update 1
According to the comments, if I just call a script with this in it:
var title = 'new blog!'; var options = { body: 'come read my new blog!', icon: 'same icon as before or maybe a new one!' }; var notification = new Notification(title, options); It should hit all devices that are subscribed to my notifications. I tried this on my phone but my desktop still didn't get a notification. I still think I'm missing something as my notifications seem stuck to one device and can only be called on page-load or on click as opposed to Facebook which sends you notifications even if the page isn't open in your browser.
-8084077 0The literal-object syntax cannot be used for non-literal keys. To use a non-literal key with an object requires the object[keyExpression] notation, as below. (This is equivalent to object.key when keyExpression = "key", but note the former case takes an expression as the key and the latter an identifier.)
var output = [] $('.grab').each(function(index) { var obj = {} obj[$(this).attr('name')] = $(this).val() output.push(obj) }) Happy coding.
Also, consider using .map():
var output = $('.grab').map(function() { var obj = {} obj[$(this).attr('name')] = $(this).val() return obj })
-5224759 1 is python good for making games? i hear people say python is just as good as c++ and java but i cant find many good games made in python. a few in pygames but not many
just trying to choose the right language
edit: sorry, many games really, i would love to make a roguelike, basically my dream. also an overhead rpg. nothing to complex, i dont want to reinvent the wheel but i would like to make a fun game. i have minor java experience, but like the looks of python. i dont plan on making a 3d game really.
-33981738 1 What Python 3 version for my Django projectI will try to port my Python 2.7 with Django to Python 3. But now my question is what version is the most stable one today? I've heard people use 3.2 and 3.4 and recommend it. But now I'm asking you guys.
What version is the most stable one today?
-20211228 0 Android SDK (Eclipse) : How to create a simple timer for a simple App?i have a simple Application about writing the sentence which is shown when the application starts.The only Problem is, i need the application to calculate the time it took the user to write the sentence .. like when you touch "Submit" Button , the Toast message will say " Thats Right ! , It took you 3.2 Second" As Example .
I heard you can set a timer to start on when specific action occurs ... and you can order it to stop .
So let's say The Timer will start when you start the app and it will stop when you touch "Submit" button , and give a toast message like above calculating the exact time it took you to write the sentience after starting the App ! *
Here is the App Code hope it helps : *
Button w; TextView t; EditText e; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); w = (Button) findViewById(R.id.Write); t= (TextView) findViewById(R.id.FTS); e = (EditText) findViewById(R.id.Text); w.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String check1 = t.getText().toString(); String check2 = e.getText().toString(); if (check1.equals(check2)) Toast.makeText(MainActivity.this,"You Wrote it Right !!!",Toast.LENGTH_LONG).show(); else if (check2.equals("")) Toast.makeText(MainActivity.this,"It's Empty",Toast.LENGTH_LONG).show(); else Toast.makeText(MainActivity.this,"You wrote it wrong,try again !",Toast.LENGTH_LONG); I'm Totally new to Android so I really don't know how to do it , Thanks for your Time .*
-1984039 0You could have your Line object implement the Comparable interface. You could then put the comparison logic within the Line class in the compareTo method. The logic there will test whether the slope and the intercept match, and if so return 0. Other results could return 1 or -1 to enforce ordering, if you want.
Obviously, you don't need to implement this interface to effect your desired results. However, as this is homework, doing so will allow you to play around with some features of the JDK, like using sorted Lists, etc. With a sorted list, for example, you could obviate the need for a nested loop, as you would only need to compare the object in question against one you just removed from the Iterator in the previous iteration to see if you need to add it to an existing linelist or start a new one.
To debug, I increased the size of the curved edge and I can see that the shadow is still shown, but the bottom of my view is being clipped..
Looks like there is a bad or missing constraint somewhere..
-38352993 0 Why Promise.all cannot work after all asynchronous function are completed?Hi I'm new to Js and I'd like to wait some async functions complete before print ni. But the code never print it I cannot understand why. Please help me:(
// public function this.run = function() { 'use strict'; let compile_lib = lib_array.map((item) => { return new Promise(() => {compileEntry(item);}) }); Promise.all(compile_lib).then(() => { console.log("ni"); }); }
-40884127 0 Generally, nowadays you shouldn't ever need to manually add /// <reference... references. If you've got your type definitions installed using NPM then they should be automatically included in your compilation process.
All you need to do is import the module and start using it. For example, in a new empty test project I've just installed xlsx (npm install xlsx @types/xlsx) and I can now successfully compile and run the below:
import xlsx = require("xlsx"); var workbook = xlsx.readFile("test.xlsx"); That should be all you need.
-34858358 0 If expression in QlikviewMy expression:
IF(Min(MONTHYEAR) > Min(MONTHYEAR2) and isnull(FIELD1),FIELD1B,if(Min(MONTHYEAR) > Min(MONTHYEAR2) and len(FIELD1)>0,FIELD1)) as Value
I need this: 1.-if(Min(MONTHYEAR) > Min(MONTHYEAR2) and isnull(FIELD1) output FIELD1B 2.-if(Min(MONTHYEAR) > Min(MONTHYEAR2) and isnotnull(FIELD1) output FIELD1
What I am doing wrong? Thanks!
-24130827 0In fact it's not cut off at the top, it just has a space at the bottom, which is rendered by the inline img. If your div contains only the image, you can just set font-size:0 for your div. Also you can set the border for your img instead:
.details-big { border-top: 8px solid #f0f0f0; border-bottom: 8px solid #f0f0f0; font-size:0; } You can also set display:block for your img:
.details-big > img { display:block; } there is 2 options one is you need to use namespace otherwise use that way
public function index() { return \App\MemberModel::test(); }
-7633965 0 PHP - XML conversion I'm new to stackoverflow and after some searching didn't find an answer to my question so I'm hoping someone can help me out.
I have to use this web service method that takes three parameters, a string and two xml params.
Below's an example of the code I'm using. The web service method throws an exception, 'Required parameters for method SubmitXml are null.'
So I'm guessing it's not receiving any xml on the 2nd and 3rd params. Can anyone give me a hint on how to correctly use the DOM or any other with PHP here? thank you in advance.
$soapClient = new SoapClient($this-SOAPURL, array('login'=>$this->account,'password'=>$this->password)); $xmlstr ='<xmlbody>'; $xmlstr.='<someXML>Some XML text content here!</someXML>'; $xmlstr.='</xmlbody>'; $dom = new DOMDocument(); $dom->loadXML($xmlstr); $filter = new DOMDocument(); $filter->loadXML('<_ xmlns=""/>'); print_r ($soapClient->SubmitXml('userIDString',$dom->saveXML(), $fil->saveXML()));
-30967702 0 Send UDP data from Windows Service to browser running webpage on same machine Let's say I have the following code running on a Windows service. I have to send data from a Windows service on a machine to a webpage that is open on the same machine(but not hosted on that machine).
static void Main(string[] args) { Int32 counter = 0; while (counter < 100) { SendUDP("127.0.0.1", 49320, counter.ToString(), counter.ToString().Length); Thread.Sleep(2000); counter++; } } public static void SendUDP(string hostNameOrAddress, int destinationPort, string data, int count) { IPAddress destination = Dns.GetHostAddresses(hostNameOrAddress)[0]; IPEndPoint endPoint = new IPEndPoint(destination, destinationPort); byte[] buffer = Encoding.ASCII.GetBytes(data); Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); for (int i = 0; i < count; i++) { socket.SendTo(buffer, endPoint); } socket.Close(); System.Console.WriteLine("Sent: " + data); } I have to listen for the data sent to port 49320 and then process it in the browser.
I can create a listener on the webpage with Node.js like below, but I have to start this service separately and also install node.js on the client.
Is there any alternative to this? Something more lightweight ?
I could also create an AJAX to query a webservice every 2 seconds that would do the same thing as Windows Service, but it seems like a lot of queries sent all the time for nothing.
//websocket gateway on 8070 var app = require('http').createServer(handler) , io = require('socket.io').listen(app) , fs = require('fs'); var mysocket = 0; app.listen(8070); function handler (req, res) { fs.readFile(__dirname + '/index.html', function (err, data) { if (err) { res.writeHead(500); return res.end('Error loading index.html'); } res.writeHead(200); res.end(data); }); } io.sockets.on('connection', function (socket) { console.log('index.html connected'); mysocket = socket; }); //udp server on 49320 var dgram = require("dgram"); var server = dgram.createSocket("udp4"); server.on("message", function (msg, rinfo) { console.log("msg: " + msg); if (mysocket != 0) { mysocket.emit('field', "" + msg); mysocket.broadcast.emit('field', "" + msg); } }); server.on("listening", function () { var address = server.address(); console.log("udp server listening " + address.address + ":" + address.port); }); server.bind(49320);
-26208978 0 change the option, then re-initialize:
$('ul').circleMenu({direction:'bottom-right'}).circleMenu('init');
-26026088 0 search bar in TableView : App crashes when type last character of search text string Added search bar in the storyboard on top of tableview app crashes when type last character of search text string with the error
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[PFUser copyWithZone:]: unrecognized selector sent to instance
- (void)viewDidLoad { [super viewDidLoad]; PFQuery *query = [PFUser query]; [query orderByAscending:@"username"]; [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { if (error){ NSLog(@"Error:%@ %@", error, [error userInfo]); } else { self.allUsers = objects; self.searchResults = [[NSArray alloc] init]; [self.tableView reloadData]; } }]; - (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope { NSPredicate *predicate = [NSPredicate predicateWithFormat:@"username like %@", searchText]; self.searchResults = [self.allUsers filteredArrayUsingPredicate:predicate]; } -(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString { [self filterContentForSearchText:searchString scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]]; return YES; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if (tableView == self.searchDisplayController.searchResultsTableView){ return [self.searchResults count]; } else { //[self filterData]; return [self.allUsers count]; } } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; if (tableView == self.searchDisplayController.searchResultsTableView) { cell.textLabel.text = [self.searchResults objectAtIndex:indexPath.row]; } else { PFUser *user = [self.allUsers objectAtIndex:indexPath.row]; cell.textLabel.text = user.username; } return cell; } -(void) tableView:(UITableView *) tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { if (tableView == self.tableView){ self.title = [self.allUsers objectAtIndex:indexPath.row]; } else { self.title = [self.searchResults objectAtIndex:indexPath.row]; } } EDIT:
When i type bt at lldb prompt this is what i get
* thread #1: tid = 0x86e99, 0x029b68b9 libobjc.A.dylib`objc_exception_throw, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1 frame #0: 0x029b68b9 libobjc.A.dylib`objc_exception_throw frame #1: 0x02cd4243 CoreFoundation`-[NSObject(NSObject) doesNotRecognizeSelector:] + 275 frame #2: 0x02c2750b CoreFoundation`___forwarding___ + 1019 frame #3: 0x02c270ee CoreFoundation`__forwarding_prep_0___ + 14 frame #4: 0x029c8bcd libobjc.A.dylib`-[NSObject copy] + 41 frame #5: 0x018317b6 UIKit`-[UILabel _setText:] + 129 frame #6: 0x0183194d UIKit`-[UILabel setText:] + 40 * frame #7: 0x000138d8 -[EditFriendsViewController tableView:cellForRowAtIndexPath:](self=0x0aca3e50, _cmd=0x01e3b31f, tableView=0x0baed600, indexPath=0x0ac92b70) + 456 at EditFriendsViewController.m:204 frame #8: 0x0176f11f UIKit`-[UITableView _createPreparedCellForGlobalRow:withIndexPath:] + 412 frame #9: 0x0176f1f3 UIKit`-[UITableView _createPreparedCellForGlobalRow:] + 69 frame #10: 0x01750ece UIKit`-[UITableView _updateVisibleCellsNow:] + 2428 frame #11: 0x017656a5 UIKit`-[UITableView layoutSubviews] + 213 frame #12: 0x016e5964 UIKit`-[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 355 frame #13: 0x029c882b libobjc.A.dylib`-[NSObject performSelector:withObject:] + 70 frame #14: 0x00aa545a QuartzCore`-[CALayer layoutSublayers] + 148 frame #15: 0x00a99244 QuartzCore`CA::Layer::layout_if_needed(CA::Transaction*) + 380 frame #16: 0x00a990b0 QuartzCore`CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 26 frame #17: 0x009ff7fa QuartzCore`CA::Context::commit_transaction(CA::Transaction*) + 294 frame #18: 0x00a00b85 QuartzCore`CA::Transaction::commit() + 393 frame #19: 0x00a01258 QuartzCore`CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) + 92 frame #20: 0x02bff36e CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 30 frame #21: 0x02bff2bf CoreFoundation`__CFRunLoopDoObservers + 399 frame #22: 0x02bdd254 CoreFoundation`__CFRunLoopRun + 1076 frame #23: 0x02bdc9d3 CoreFoundation`CFRunLoopRunSpecific + 467 frame #24: 0x02bdc7eb CoreFoundation`CFRunLoopRunInMode + 123 frame #25: 0x036135ee GraphicsServices`GSEventRunModal + 192 frame #26: 0x0361342b GraphicsServices`GSEventRun + 104 frame #27: 0x01676f9b UIKit`UIApplicationMain + 1225 frame #28: 0x000144cd `main(argc=1, argv=0xbfffee04) + 141 at main.m:16 Have no idea what is causing this.
Help will be appreciated.
Thanks
-14959037 0 type conversion can not have aggregate operand (error in modelsim)I'm novice to VHDL. I'm getting the following errors while compiling in modelsim6.5b
- type conversion(to g) cannot have aggregate operand,
- No feasible entries for infix operator "and",
- Target type ieee.std_logic_1164.std_ulogic in variable assignment is different from - expression type std.stadard.integer
any help on these and the reason behind that will be helpful.
This is the package I've written
library ieee; use ieee.std_logic_1164.all; use ieee.std_logic_unsigned.all; package enc_pkg is constant n : integer := 1; constant k : integer := 2; constant m : integer := 3; constant L_total : integer := 10; constant L_info : integer := 10; type t_g is array (1 downto 1, 3 downto 1)of std_logic; signal g:t_g; type array3_10 is array (3 downto 1, 10 downto 0) of std_logic; type array2_10 is array (2 downto 1, 10 downto 0) of std_logic; procedure rsc_encoder( x : in std_logic_vector(1 to 10); terminated : in std_logic; y : out array2_10); procedure encode_bit(input : in std_logic; state_in : in std_logic_vector(1 to 2); output : out std_logic_vector(1 to 2); state_out : out std_logic_vector(1 to 2)); procedure encoderm (infor_bit : in std_logic_vector(1 to 8); en_output : out std_logic_vector(1 to 20)); end enc_pkg; package body enc_pkg is procedure rsc_encoder( x : in std_logic_vector(1 to 10); terminated : in std_logic; y : out array2_10)is variable state : std_logic_vector(1 to 2); variable d_k : std_logic; variable a_k : std_logic; variable output_bit : std_logic_vector(1 to 2); variable state_out : std_logic_vector(1 to 2); begin for i in 1 to m loop state(i) := '0'; end loop; for i in 1 to L_total loop if(terminated = '0' or (terminated = '1' and i <= L_info)) then d_k := x(i); elsif(terminated = '1' and i > L_info)then d_k := (g(1, 2) and state(1)) xor (g(1, 3) and state(2)); end if; a_k := (g(1, 1) and d_k) xor (g(1, 2) and state(1)) xor (g(1, 3)) and state(2)); encode_bit(a_k, state, output_bit, state_out); state := state_out; output_bit(1) := d_k; y(1, i) := output_bit(1); y(2, i) := output_bit(2); end loop; end rsc_encoder; procedure encode_bit(input : in std_logic; state_in : in std_logic_vector(1 to 2); output : out std_logic_vector(1 to 2); state_out : out std_logic_vector(1 to 2))is variable temp : std_logic_vector(1 to 2); begin for i in 1 to n loop temp(i) := g(i, 1) and input; for j in 2 to k loop temp(i) := temp(i) xor (g(i, j) and state_in(j-1)); end loop; end loop; output := temp; state_out := input & state_in(m-1); end encode_bit; procedure encoderm (infor_bit : in std_logic_vector(1 to 8); en_output : out std_logic_vector(1 to 20))is --type array2_10 is array (2 downto 1, 10 downto 0) of integer; --type array3_10 is array (3 downto 1, 10 downto 0) of integer; variable interleaved : std_logic_vector(1 to 10); variable input : std_logic_vector(1 to 10); variable puncture : std_logic; variable output : array3_10; variable y : array2_10; variable en_temp : std_logic_vector(1 to 10); begin input := "0000000000"; for i in 1 to 8 loop input(i) := infor_bit(i); end loop; rsc_encoder(input, terminated 1, y); for i in 1 to 10 loop output(1, i) := y(1, i); output(2, i) := y(2, i); end loop; interleaved(1) := output(1, 1); interleaved(2) := output(1, 4); interleaved(3) := output(1, 7); interleaved(4) := output(1, 10); interleaved(5) := output(1, 2); interleaved(6) := output(1, 5); interleaved(7) := output(1, 8); interleaved(8) := output(1, 3); interleaved(9) := output(1, 6); interleaved(10) := output(1, 9); rsc_encoder(interleaved, terminated 0, y); for i in 1 to 10 loop output(3, i) := y(2, i); end loop; if puncture = '1'then for i in 1 to 10 loop for j in 1 to 3 loop en_output(3*(i-1)+j) := output(j, i); end loop; end loop; elsif puncture = '0' then for i in 1 to L_total loop en_temp(n*(i-1)+1) := output(1, i); if((i rem 2) = 1)then en_temp(n*i) := output(2, i); else en_temp(n*i) := output(3, i); end if; end loop; end if; en_output := en_temp; end encoderm; end enc_pkg;
-26302016 0 Getting the address of a statically allocated array into a pointer inside a struct The simplified version of my code is the following:
struct args { int p; int *A; }; typedef struct sort_args sort_args; void func(int A[], int p) { args new_struct = {&A, p}; args *args_ptr = &new_struct; } I'm trying to convert a statically (I think that's the term) allocated array into a pointer, but the compiler keeps throwing these warnings:
warning: initialization makes integer from pointer without a cast [enabled by default] args new_struct = {&A, p, r};
warning: (near initialization for ‘new_struct.p’) [enabled by default] warning: initialization makes pointer from integer without a cast [enabled by default] warning: (near initialization for ‘new_struct.A’) [enabled by default]
What am I doing wrong?
-12417371 0If you are inserting your rows one at a time I'd recommend changing to a multi-row insert statement if possible as in "insert into events (eventId,content) values (1,'value 1'), (2,'value 2'), ..." as there can be quite a bit of overhead transactions. Also, TokuDB has improved performance with each release, I'd recommend running on a current release.
-2638493 0With Jquery
$(document).ready(function () { $("#live").load("ajax.php"); var refreshId = setInterval(function () { $("#live").load('ajax.php?randval=' + Math.random()); }, 3000); }); it calls ajax.php in first load and every 3 seconds to #live div.
-17815000 0You can effectively name ranges using the text box in the top left of the screen (where appears the "B2" or whatever coordinate the cell has). Select entire column and insert the name there.
Then the name is valid to use in formulas.
-25304657 0It is not possible to remove anonymous lambdas event handlers. Instead put your lambda into a normal method. Than you can call proxy.GetBasicEntryCompleted -= MyMethod;.
Here is an example how it could look like:
private void OnBasicEntryCompleted(object sender, BasicEntryEventArgs e) { if (e.Result.Any()) { e.TargetComboBox.ItemsSource = e.Result.ToList(); e.TargetComboBox.DisplayMemberPath = "Description"; e.TargetComboBox.SelectedItem = "ID"; } else { e.TargetComboBox.ItemsSource = null; } var proxy = (Proxy)sender; proxy.GetBasicEntryCompleted -= OnBasicEntryCompleted; } public void Sniper(string sourceTableName, ComboBox targetComboBox) { proxy.GetBasicEntryCompleted += OnBasicEntryCompleted; proxy.GetBasicEntryAsync(sourceTableName, targetComboBox); } Also be aware that you always subscribe to an event BEFORE you invoke the method that will raise it. Otherwise it could happen, that won't be informed due to a racing condition.
And if you call this async method the question would be in which thread will the completed event be raised? If it happens in thread where the async task had run, you won't be within the gui thread and manipulating gui objects (like the combo box) is not recommended within other threads. So maybe encapsulate your accesses to the combo box within a e.TargetComboBox.Invoke() call.
I've just started going through a beginners book of C++. I have some java experience (but having said that, I've never used default arguments in java to be honest)
So, as mentioned, my issue is with default arguments..
This is the code snippet I'm using:
#include <iostream> using namespace std; //add declaration int add(int a, int b); int main (void) { int number1; cout << "Enter the first value to be summed: "; cin >> number1; cout << "\nThe sum is: " << add(number1) << endl; } int add(int a=10, int b=5) { return a+b; } The response I get from g++ compiler is: "too few arguments to function 'int add(int, int)'
Am I doing this wrong? (I've also tried it with literal arguments)
P.S. I can't seem to get the code snippet to display properly? Has the system changed?
-23905917 0As far as I know this is currently only supported for fields of a class or top level fields but not for local variables inside a method/function when reflecting at runtime. Maybe source mirrors has more capabilities (I haven't used it yet) but I think this can only be used at compile time.
-26711090 0you can use alien if you want and that's the recommended way to do it actually, but you can install it with rpm too. just install rpm:sudo apt-get install rpm then run sudo rpm -i package_name
My project stop to compile after was updated to 7.3 version. For this moment main problem is in header files when I want to return UIColor. xCode tells me Expected a type error. Is there some way to handle with this situation?
Edit: my code (nothing special)
#import <Foundation/Foundation.h> @interface NSString (Color) - (UIColor *)rgbColor; //Expected a type - (UIColor *)hexColor; //Expected a type @end
-15087397 0 Since your scheduled task is actually changing the permissions on the error log file, the only viable options I can see are:
1) Make the scheduled task not write to the error_log. Add the following to the top of the cron job:
error_reporting(E_NONE);
2) Make the scheduled task write to the system log (event viewer in windows) by issuing the following command at the start of your scheduled task (PHP file):
ini_set('error_log', 'syslog');
3) If all of the above do not suit you, you can try scheduling the task as the IIS User/Group. This would insure that the permissions are met and error 500 is no longer caused.
There is no magic fix to this, you can either change the scheduled task so it has the same UID/GID as the PHP process, or you can stop logging in the scheduled_task.
-2816240 0Dollar - $(MyProp): Allows you to reference values specified within PropertyGroups.
At Sign - @(CodeFile): Allows you to reference lists of items specified within ItemGroups.
Percent - %(CodeFile.BatchNum): Allows you to reference batched ItemGroup values using metadata. This is a bit more complicated, so definitely review the documentation for more info.
Take a look at each link for more detailed info on how these are used. Good luck -- hope this helps!
-38135976 0 How to call custom back-end methods (parsing objects) using Typescript and Angular resourcesI've been struggling for weeks now to get custom service calls to work using Typescript / Angular / C#. I can't seem to find any viable solution online, and the more I look the more I get confused.
My current solution has been structured based mostly on Pluralsight courses. I'm understanding the general connectivity from HTML => Angular (controllers/ models / services), but struggling with the Angular services => C# API controller connection.
Current structure:
app.ts
module App { var main = angular.module("Scheduler", ["ngRoute", "App.Services"]); main.config(routeConfig); routeConfig.$inject = ["$routeProvider"]; function routeConfig($routeProvider: ng.route.IRouteProvider): void { $routeProvider .when("/schedule", { templateUrl: "/app/scheduler/views/scheduler.html", controller: "ScheduleCtrl as sch" }) .otherwise("/schedule"); } } services.ts
module App.Services { angular.module("App.Services", ["ngResource"]); } controller.ts
module App.Scheduler { export interface IScheduleParams extends ng.route.IRouteParamsService { scheduleId: number; } export class ScheduleCtrl implements IScheduleModel { scheduleResource: ng.resource.IResourceClass<App.Services.IScheduleResource>; static $inject = ["$routeParams", "scheduleService", "$scope"]; constructor(private $routeParams: IScheduleParams, private scheduleService: App.Services.SchedulerService, public schedule: Schedule) { this.scheduleResource = scheduleService.getScheduleResource(); this.schedule = new Schedule(0, 0, new Array<PaymentEntry>(), 0, new Array <ScheduleEntry>()); } generateSchedule(): void { //todo: Need to call the backend service here to generate entries var returnedSchedules = this.scheduleService.generateSchedules(this.schedule); } } schedulerService.ts
module App.Services { //INTERFACES //services export interface ISchedulerService { getScheduleResource(): ng.resource.IResourceClass<IScheduleResource>; generateSchedules(schedule: App.Scheduler.Schedule): App.Scheduler.ScheduleEntry[]; //custom service call } //resources export interface IScheduleResource extends ng.resource.IResource<App.Scheduler.ISchedule> { } //CLASSES //Schedule Service export class SchedulerService implements ISchedulerService { static $inject = ["$resource"]; constructor(private $resource: ng.resource.IResourceService) { } //Read operations (single / list) -- this works fine getScheduleResource(): ng.resource.IResourceClass<IScheduleResource> { return this.$resource("api/scheduler/GetSchedules/:scheduleId"); } //custom operations -- **!! NEED HELP HERE PLEASE !!** generateSchedules(schedule: App.Scheduler.Schedule): App.Scheduler.ScheduleEntry[] { return this.$resource("api/schedule/GenerateSchedules/:schedule"); //I need to be able to pass in a Schedule object and receive an array of objects back } } angular .module("Scheduler") .service("schedulerService", SchedulerService); } models.ts
module App.Scheduler { //INTERFACES export interface ISchedule { param1: number; payments: Array<IPaymentEntry>; schedules?: Array<IScheduleEntry>; } export interface IPaymentEntry { param1: number; param2: number; } export interface IScheduleEntry { param1: number; param2: string; param3: number; } //CLASSES export class Schedule { constructor(public param1?: number, public payments?: Array<IPaymentEntry>, public schedules?: Array<IScheduleEntry>) { } } export class PaymentEntry implements IPaymentEntry { constructor(public param1?: number, public param2?: number) { } } export class ScheduleEntry implements IScheduleEntry { constructor(public param1: number, public param2: string, public param3: number) { } } } ApiController.CS
public class SchedulerController : ApiController { public IEnumerable<Schedule> GetSchedules() { //... } public Schedule GetSchedules(int id) { //... } [HttpPost] public IEnumerable<PaymentEntry> GenerateSchedules([FromBody]Schedule schedule) { //todo: add random logic here return new Schedule(); } Any guidance or a working example of how to successfully call the generateSchedules method from the schedulerService.ts to the ApiController.CS would be greatly appreciated to and from the API controller would be greatly appreciated.
-9802788 0 Call a REST API in PHPOur client had given me a REST API to which I need to make a PHP call to. But as a matter of fact the documentation given with the API is very limited, so I don't really know how to call the service.
I've tried to Google it, but the only thing that came up was an already expired Yahoo! tutorial on how to call the service. Not mentioning the headers or anything in depth information.
Is there any decent information around how to call a REST API, or some documentation about it? Because even on W3schools, they only describes the SOAP method. What are different options for making rest API in PHP?
-18164838 0How about this?
>>> re.sub('(\d+)', 'sub\g<1>', "C7H19N3") 'Csub7Hsub19Nsub3' (\d+) is a capturing group that matches 1 or more digits. \g<1> is a way of referring to the saved group in the substitute string.
Firstly I'm planning to set up an vehicle tracking system. I have my own server. There is a device which can send the data via GPRS. I can define an IP and a port number to this device. I want to connect this device to my server without and auxiliary device. What I want to ask is which format the device send the data(XML, TXT, or something like that), how I can write the data to the database. And if I have to use a computer to get the coordinates from the device, which language should I use?
*I have already read the user manual bu I couldn't find any.
-26554247 0 How to calculate indegree and outdegree for a graph in directed graph SML code?I have a tuple like (1,2),(3,4),(4,5). Edges: 1->2, 3->4 and so on.
How calculate in degree and out degree for each vertex?
-32878450 0 node.js - infinite loop during JSONStreamI've got a node.js server that is freezing in production, and it appears to be caused by an infinite loop inside of JSONStream. Here's a stack trace captured from a core dump from a frozen server:
1: toString [buffer.js:~392] (this=0x1e28fb6d25c9 <a Buffer>#1#,encoding=0x266ee104121 <undefined>,start=0x266ee104121 <undefined>,end=0x266ee104121 <undefined>) 2: arguments adaptor frame: 0->3 3: write [/home/deploy/node_modules/JSONStream/node_modules/jsonparse/jsonparse.js:136] (this=0x32cc8dd5a999 <a Parser>#2#,buffer=0x32cc8dd5aa49 <a Buffer>#3#) 4: /* anonymous */ [/home/deploy/node_modules/JSONStream/index.js:~17] (this=0x32cc8dd5ab11 <a Stream>#4#,chunk=0x32cc8dd5aa49 <a Buffer>#3#) 5: write [/home/deploy/node_modules/JSONStream/node_modules/through/index.js:~24] (this=0x32cc8dd5ab11 <a Stream>#4#,data=0x32cc8dd5aa49 <a Buffer>#3#) 6: write [_stream_readable.js:~582] (this=0x266ee106c91 <JS Global Object>#5#,dest=0x32cc8dd5ab11 <a Stream>#4#,i=0,list=0x266ee104101 <null>) 7: flow [_stream_readable.js:592] (this=0x266ee106c91 <JS Global Object>#5#,src=0x32cc8dd5ac69 <an IncomingMessage>#6#) 8: /* anonymous */ [_stream_readable.js:560] (this=0x266ee106c91 <JS Global Object>#5#) 9: _tickCallback [node.js:415] (this=0x29e7331bb2a1 <a process>#7#) How can I find the source of this infinite loop?
Unfortunately the servers are running in production and are processing many thousands of requests, so it's difficult to give any additional context. The basic function of the servers is to make outbound HTTP requests for other services.
It's worth noting that I don't believe this is caused by a memory leak. The server's memory usage remains constant (and low) during these freeze events, while the CPU spikes to 99%
Another piece of evidence towards the conclusion of an infinite loop is that the event loop itself seems to have stopped. When I put a console.log inside of a setInterval, the server will stop outputting as soon as it freezes.
We have verified that the problem is not caused by expired/corrupted socket connections, by setting the number of max connections to Infinity (which disables their reuse in node.js)
We're using JSONStream 0.7.1 (which includes a default jsonparse version of 0.0.5). We found this issue on the JSONStream repo, and tried forking JSONParse and only updating to the newest jsonparse version. It did NOT fix the issue.
-29430890 0IMHO there are three reasonable scenarios for Optional:
Your scenario falls into the last category so I would simply write:
MyDao oq = myOptional.orElseThrow(() -> new RuntimeException("Entity was not found"); if(!oq.getReferenceId().equals(objToUpdate.getId())) throw new RuntimeException("Bad Move!"); oq.setAttribute(objToUpdate.getAttribute()); Of course, it's appealing to use methods like ifPresent, filter or map, but in your case, why would you want to continue when the application is in a faulty state. Now if you wouldn't throw an exception if the entity wasn't found, then the situation would be different.
Something like oq.checkMove(objToUpdate.getId()) could make sense. That would eliminate the if and make the code more expressive.
The password wasn't encrypted; it was hashed using crypt.
$ perl -e'CORE::say crypt($ARGV[0], $ARGV[1]) eq $ARGV[1] ? 1 : 0' 123456 cb897EaMgDZy6 1 Note that use of crypt must be avoided! It is far too weak to be of any value.
I want to get packages from a network using TCP/IP as a client.
With ...
connect((TCP_IP, TCP_PORT)) ... I can change the port of the peer address. But I change the port of my local computer?
EDIT: I want to use a network card with four ports. The network card is connected to a measurement device which sends a lot of data. How can I see where the data goes? How can I distinguish between this four ports?
-28568162 0I think this is not working because the columns returned by both select must have the same names, so please try this
SELECT "dba"."Room"."ID" ID, "dba"."Room"."RoomNumName" RoomNumName from "dba"."Room" WHERE DeptID = 8225 EXCEPT SELECT "dba"."vwResultInspection_iDashboards"."roomID" ID, "dba"."vwResultInspection_iDashboards"."RoomNumName" RoomNumName FROM "dba"."vwResultInspection_iDashboards" where "dba"."vwResultInspection_iDashboards"."ClosedDate" > '2015-01-01' AND "dba"."vwResultInspection_iDashboards"."ClosedDate" < '2015-01-31 23:59:59.000' and DEPTID = 8225
-2251602 0 LINQ Stored Procedure DATETIME NULL I got this errormessage when I use Linq and and stored procedure as follow. I got this message when the DateTime parameter is NULL. How will I do to solve this?
Errormessage Serverfel i tillämpningsprogrammet. SqlDateTime-spill: Det måste vara mellan 1/1/1753 12:00:00 AM och 12/31/9999 11:59:59 PM.
Codeblock in C#
protected void ButtonSearch_Click(object sender, EventArgs e) { Postit p = new Postit(); DateTime? dt; if(TextBoxDate.Text=="") { dt=null; } else { dt=System.Convert.ToDateTime(TextBoxDate.Text); } GridView1.DataSource = p.SearchPostit(TextBoxMessage.Text, TextBoxWriter.Text, TextBoxMailto.Text, System.Convert.ToDateTime(dt)); GridView1.DataBind(); } public ISingleResult<Entities.SearchPostitResult> SearchPostit([Parameter (DbType="VarChar(1000)")] string message, [Parameter(DbType="VarChar(50)")] string writer, [Parameter(DbType="VarChar(100)")] string mailto, [Parameter(DbType="DateTime")] System.Nullable<System.DateTime> date) { IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), message, writer, mailto, date); return ((ISingleResult<Entities.SearchPostitResult>)(result.ReturnValue)); Procedure ALTER PROCEDURE [dbo].[SearchPostit] ( @message varchar(1000)='', @writer varchar(50)='', @mailto varchar(100)='', @date Datetime=null ) AS SELECT P.Message AS Postit, P.Mailto AS 'Mailad till', P.[Date] AS Datum , U.UserName AS Användare FROM PostIt P INNER JOIN [User] U ON P.UserId=U.UserId WHERE P.message LIKE '%'+@message+'%' AND P.Mailto LIKE '%'+@mailto+'%' AND ( @date IS NULL OR P.Date = @date ) AND U.UserName LIKE '%'+@writer+'%' GROUP BY P.Message, P.Mailto, P.[Date], U.UserName }
-28047424 0 Android Google Maps API v2 check land or water I'm working with Android Google Maps API v2. Is it possible to check if point (LatLng) is in water or land?
-21920302 0You can try some like this basic structure
INSERT INTO temp_table (Value1,Value2,Value3) SELECT field1, field2, field3 FROM the_table WHERE condition_value = some_value Remember have the same number of fields in your INSERT INTO and your SELECT.
So we've been using Groups for saving and retrieving some data across an extension and the main app and everything worked fine for Swift 2.3 but then we updated to Swift 3.0 and got some issues.
The current implementation that gives us issues is like following:
open class SomeClass: NSObject, NSCoding { open var someVar: Int! open func encode(with aCoder: NSCoder) { aCoder.encode(self.someVar, forKey:"someVar") } public required convenience init?(coder decoder: NSCoder) { // this is where it breaks self.someVar = decoder.decodeInteger(forKey: "someVar") } } The following error is thrown:
*** Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: '*** -[NSKeyedUnarchiver decodeInt32ForKey:]: value for key (someVar) is not an integer number' The funny thing is the old implementation for Swift 2.3 works without any issues: self.someVar = decoder.decodeObject(forKey: "someVar") as! Int (I've understood from other posts that this would not work...)
So what could I be doing wrong? It should be said that the original value is retrieved from a float and cast to an int.
-28976776 0Further to @richard-pawson's answer, I've ported the "table-of-two-halves" pattern from Entity Framework to Java (JDO/DataNucleus), with a complete example up on github.
You should be able to use it to come up with something similar back in .NET land.
-3081942 0I am exploring possiblities of https://bespin.mozillalabs.com/ for my web development. Looks quite promising. an editor and a version control system. fully online. try it for once and see if you like it.
-21919113 0I haven't been able to reproduce the behavior you describe in a similar application that I have. The only difference is that I'm not loading the byte array into a MemoryStream first, but just passing the byte array to File.
So try removing the MemoryStream from the equation. So the code would end up something like:
public ActionResult DetailsExcel(string id) { byte[] stream; // changed to byte array using (var excelPackage = new ExcelPackage()) { var ws = excelPackage.Workbook.Worksheets.Add(fileName); ws.Cells["A1"].LoadFromText(csv, this._excelTextFormat); stream = excelPackage.GetAsByteArray(); // removed MemoryStream } return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName + ".xlsx"); }
-12903066 0 You never place any content in your StringBuffer buffer, so it is empty when you write it to file:
bw.write(buffer.toString()); buffer could potentially consume a large amount of memory here.
A better approach to writing the data to file would be to write the data as you read it from the database:
while (rs.next()) { sampleIddisp = rs.getString(1); ... bw.write(....); }
-35421851 0 AWS RDS showing outdated data for Multiple AZ instance (MySQL) My RDS instance was showing outdated data temporarily.
I ran a SELECT query on my data. I then ran a query to delete data from a table and another to add new data to the table. I ran a SELECT query and it was showing the old data.
I ran the SELECT query AGAIN and THEN it finally showed me the new data.
Why would this happen? I never had these issues locally or on my normal non AZ instances. Is there a way to avoid this happening?
I am running MySQL 5.6.23
-18632968 0 MQTT Android not connecting to ActiveMqI'm trying to connect an Android application to an ActiveMQ server. I'm using ActiveMQ because my server already talks to the ActiveMQ server using JMS so it will be very beneficial for me to connect the android client to the JMS broker.
I've enabled MQTT in ActiveMQ following this page: http://activemq.apache.org/mqtt.html and I had a small problem with any of the MQTT clients (IBM MQTT client or Paho MQTT Client) I've downloaded didn't recognize "mqtt://" url prefix so I tried to use tcp instead. This is how the configuration looks like in activemq.xml:
<transportConnectors> <transportConnector name="openwire" uri="tcp://0.0.0.0:61616?maximumConnections=1000&wireformat.maxFrameSize=104857600"/> <transportConnector name="amqp" uri="amqp://0.0.0.0:5672?maximumConnections=1000&wireformat.maxFrameSize=104857600"/> <transportConnector name="mqtt" uri="tcp://0.0.0.0:1883"/> </transportConnectors> When I try to connect using any mqtt client example such as this one: http://mosquitto.org/2011/11/android-mqtt-example-project/ I'm unable to connect to the ActiveMQ and I get an error on the server side:
2013-09-05 12:34:17,550 | WARN | Transport Connection to: tcp://192.168.0.111:42148 failed: java.io.IOException: Unknown data type: 77 | org.apache.activemq.broker.TransportConnection.Transport | ActiveMQ Transport: tcp:///192.168.0.111:42148@1883 Any suggestions? Thanks!
-32471292 0Sorry for troubling those who went through the question, there was almost no problem at all. I was just too silly to miss it. I forgot the magic of Entity Framework. I implemented the add function in following way
public bool AddSpeaker(Entities.Speaker speaker, string[] selectedCertifications) { if (selectedCertifications != null) { SpeakerCertification speakerCertification = new SpeakerCertification(); speaker.Certifications = new List<SpeakerCertification>(); foreach (var certificate in selectedCertifications) { if (certificate.CompareTo("false")!=0) { var certificationToAdd = _ctx.Certifications.Find(int.Parse(certificate)); speakerCertification = new SpeakerCertification(); speakerCertification.CertificationId = certificationToAdd.Id; speaker.Certifications.Add(speakerCertification); } } } _ctx.Speakers.Add(speaker); _ctx.SaveChanges(); return true; }
-5003315 0 It seems to me, on the contrary, that neither actor has its output redirected, since withOut will have finished executing long before println("II") is called. Since this is all based on DynamicVariable, however, I'm not willing to bet on it. :-) The absence of working code precludes any testing as well.
I was struggling with same exception and found this:
When there is no protection level explicitly specified on the contract and the underlying binding supports security (whether at the transport or message level), the effective protection level for the whole contract is ProtectionLevel.EncryptAndSign. If the binding does not support security (such as BasicHttpBinding), the effective System.Net.Security.ProtectionLevel is ProtectionLevel.None for the whole contract. The result is that depending upon the endpoint binding, clients can require different message or transport level security protection even when the contract specifies ProtectionLevel.None.
So, if you don't specify ProtectionLevel in ServiceContract attribute, WCF will define ProtectionLevel based on your web.config. If you're using for example Ws2007 and BasicHttpBinding, BasicHttpBinding will fail with your exception. Then you have 3 options:
Set protection level on contract that is exposed through BasicHttpBinding as this:
[ServiceContract(ProtectionLevel = ProtectionLevel.None)]
Here is my init:
import os, sys sys.path.append(os.path.abspath("..")) from myModule import * Then in command line, same directory:
Python 2.7.4 (default, Sep 26 2013, 03:20:26) [GCC 4.7.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> c = myClass Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'myClass' is not defined
-33687723 0 Here is my solution. use unsafeBitCast to avoid cast fail warning.
extension Object { func toDictionary() -> [String:AnyObject] { let properties = self.objectSchema.properties.map { $0.name } var dicProps = [String:AnyObject]() for (key, value) in self.dictionaryWithValuesForKeys(properties) { if let value = value as? ListBase { dicProps[key] = value.toArray() } else if let value = value as? Object { dicProps[key] = value.toDictionary() } else { dicProps[key] = value } } return dicProps } } extension ListBase { func toArray() -> [AnyObject] { var _toArray = [AnyObject]() for i in 0..<self._rlmArray.count { let obj = unsafeBitCast(self._rlmArray[i], Object.self) _toArray.append(obj.toDictionary()) } return _toArray } }
-17258945 0 Using Auth with Endpoints I defined a simple API using Google Cloud Endpoints:
@Api(name = "realestate", version = "v1", clientIds = { com.google.api.server.spi.Constant.API_EXPLORER_CLIENT_ID }, scopes = { "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile" }) public class RealEstatePropertyV1 { @ApiMethod(name = "create", path = "properties", httpMethod = HttpMethod.POST) public void create(RealEstateProperty property, User user) throws UnauthorizedException { if (user == null) { throw new UnauthorizedException("Must log in"); } System.out.println(user.getEmail()); } } Then I try to test it using the API explorer. I activated OAuth 2.0. But when I execute the request, the User object is null.
Jun 23, 2013 10:21:50 AM com.google.appengine.tools.development.DevAppServerImpl start INFO: Dev App Server is now running Jun 23, 2013 10:22:42 AM com.google.api.server.spi.SystemServiceServlet init INFO: SPI restricted: true Jun 23, 2013 10:22:43 AM com.google.api.server.spi.WebApisUserService getCurrentUser WARNING: getCurrentUser: clientId not allowed Jun 23, 2013 10:22:43 AM com.google.api.server.spi.SystemService invokeServiceMethod INFO: cause={0} com.google.api.server.spi.response.UnauthorizedException: Must log in at com.realestate.api.v1.RealEstatePropertyV1.create(RealEstatePropertyV1.java:44)
-28596648 0 I was able to get this fixed by calling the createcriteria
var numbers = session.CreateCriteria<Number>().List<Number>().ToList();
-10946587 0 Debugging C++ in Eclipse:
http://www.youtube.com/watch?v=azInZkPP56Q
-21477408 0llvm-config is not adding the link option for the Terminfo library. Add
-ltinfo To link in the library and all should be well.
-16497020 0 .Net MVC binding dynamic Type to a Model at runtimeI have a slightly long conceptual question I'm wondering if somebody could help me out with.
In MVC I've built a website which builds grids using kendoui's framework.
All the grids on my website are constructed exactly the same except for the model they use and the CRUD methods that need to be implemented for each model. I set things up where each Model implement an interface for CRUD methods like below to get the logic all in one place.
//Actual interface has variables getting passed public interface IKendoModelInterface { void Save(); void Read(); void Delete(); } public class Model1: IKendoModelInterface { [Key] public int IdProperty1 { get; set; } public int SomeProperty2 { get; set; } public string SomeProperty3 { get; set; } public void Save(){ //Implement Save } public void Read(){ //Implement Read } public void Delete(){ //Implement Delete } } Then to speed up the writing of all the scaffolding Action methods needed to get the grids to work I created an abstract Controller that can call the interface methods of the Model that gets passed into it.
//Implement the AJAX methods called by the grid public abstract class KendoGridImplController<T> : Controller where T : class, IKendoModelInterface { // Method called from kendo grid public virtual ActionResult Create([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<T> createdRecords) { //Invoke Create Method for Model and return results } public virtual ActionResult Read([DataSourceRequest]DataSourceRequest request, int Id) { //Invoke read method for model and return results } //Update and Delete also implemented.. } Then I just need a Controller per model that implements the abstract controller above passing in the type of Model being used.
public class ResponsibilityMatrixController : KendoGridImplController<Model1> { //Set up the page the grid will be on public ActionResult Index(int id) { return View("SharedGridView", id); } //Can override abstract methods if needed but usually won't need to } I'm wondering if I can take this one step further or if I've reached the end of the road. To me it just seems like more repeated code if I have to create a controller per Model that does nothing but pass in the type to the abstract controller and calls the same View.
I attempted for quite a while yesterday to figure out if I could dynamically assign the type to the abstract controller. I setup something where I was sending back the type of model via strings and I could still invoke the methods needed. Where it failed, was that the mapping could no longer be done on any of the controller actions by default since the type isn't known at compile time. eg
public virtual ActionResult Create([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<T> createdRecords) createdRecords can't be bound like this if T that's passed in is an interface and not the Model itself and I've found no real way to map the form data to an instance of a type that isn't known at compile time.
I'm wondering if there's an easy way to do this mapping between an instance of the type of object getting passed in that I can figure out at runtime, if there's some other way to set this up that I'm overlooking or if both those things are going to be way too much work and I should just not attempt something like this and build a controller per model like I do now?
-34853838 0Use node.js and execute your script using Runtime.exec(). you would run node on this or you can go for Rhino scripting engine to envoke methods in .js file from within a java class. Hope that helped.
-10707425 0Found it,
The answer is no :( it's not possible...
The only work around I did, is to create new MyWishClass and pass myDynamicClass, to him, so he is basically warping him.
-32646067 0You can use this sed:
sed 's/\[[0-9]*\]=\(.*\)/+=(\1)/' file ARR+=(/var/dir1) ARR+=(/var/dir2) Or this awk:
awk -F '\\[[0-9]+\\]=' '{printf "%s+=(%s)%s", $1, $2, ORS}' file ARR+=(/var/dir1) ARR+=(/var/dir2)
-6675402 0 if data["location"] && data["location"]["country"] && data["location"]["country"]["code]
Ruby's && operator is a short circut operator, so if the first operand is false, it will stop processing the rest of the condition. In addition. Any object that is not nil, is (for boolean purposes) true, so if the key exists, then it is true
Have you tried giving the full path to the mysqldump executable?
-14949210 0 Dynamically update a table using javascriptI have a page where I send an ajax request to a server. There is a table on the page which displays some data. The server returns a json object which is a list of objects and it doesn't contain any layout for the page.
I want to update only table rows by returned json. How can I do this without using third-party libraries and only using jquery? I just want a rough idea and example.
-40788064 0 Bootstrap Datetimepicker with dynamic mirror fieldsI'm using http://www.malot.fr/bootstrap-datetimepicker/ and I have this snippet:
<div class="input-group date form_datetime"> <input type="text" class="form-control" name="startDateTime" id="startDateTime"> <input type="hidden" id="startDateTime_mirror" name="startDateTime_mirror"> <span class="input-group-btn"> <button class="btn btn-default date-set" type="button"> <i class="fa fa-calendar"></i> </button> </span> </div> Please notice that the input[type=text] and the input[type=hidden] fields have the same id, but the latter with a _mirror suffix
Since I have a couple of datepickers in a page (i.e. also endDateTime and endDateTime_mirror), I can't use a 'fixed' mirror field id as in datetimepicker's demo page
EDIT: an example of two datetimepickers
<div class="input-group date form_datetime"> <input type="text" class="form-control" name="startDateTime" id="startDateTime"> <input type="hidden" id="startDateTime_mirror" name="startDateTime_mirror"> <span class="input-group-btn"> <button class="btn btn-default date-set" type="button"> <i class="fa fa-calendar"></i> </button> </span> </div> <div class="input-group date form_datetime"> <input type="text" class="form-control" name="endDateTime" id="endDateTime"> <input type="hidden" id="endDateTime_mirror" name="endDateTime_mirror"> <span class="input-group-btn"> <button class="btn btn-default date-set" type="button"> <i class="fa fa-calendar"></i> </button> </span> </div> I tried this, but it doesn't work (even if the 'generated' name is right, startDateTime_mirror (I can see it in console.log()):
$(".form_datetime").datetimepicker({ autoclose: true, format: "dd MM yyyy hh:ii", linkField: ($(this).find('.form-control').prop('id')) + '_mirror', linkFormat: "yyyy-mm-dd hh:ii" }) Any help, please? Thanks
-28447009 0The OutOfMemoryException is almost certainly coming from the JSON serialization of your Customer object. As such, the issue isn't one of NEST or Elasticsearch functionality, but of JSON.NET functionality.
You could handle this in one of two ways:
1. Serialize the large object selectively
This article by the author of JSON.NET discusses reducing the size of objects. You might furnish properties with the JsonIgnoreAttribute property to instruct the serializer to ignore certain properties. Or an implementation of IContractResolver may be less intrusive on the definitions of your EF objects (especially given that they're database-first generated), but I'm not sure whether this can be used in conjunction with the NEST dependency on JSON.NET.
If you're out of options for dealing with NEST's dependency on JSON.NET, you could always find another way to serialize your object and "go raw" by using the Elasticsearch.NET syntax instead of NEST (which essentially builds on-top of Elasticsearch.NET). So instead of a call to ElasticClient.Index(..), make a call to ElasticClient.Raw.Index(..), where the body parameter is a JSON string representation (of your own construction) of the object you wish to index.
2. Project the large object to a smaller data transfer object
Instead of indexing a Customer object, map only the properties you want to index into a data transfer object (DTO) that targets your Elasticsearch schema / document type.
foreach (Customer c in db.Customer.Where(a => a.Active == true)) client.Index(new MyElasticsearchTypes.Customer() { CustomerId = c.CustomerId, CustomerName = c.CustomerName, Description = c.Description }); In C#, you've got a lot of options for how to handle creation of such a DTO, including:
Flat by design
Be aware that using Elasticsearch isn't a case of simply throwing your data into "the index". You need to start thinking in terms of "documents", and come to terms with what that means when you're trying to index data that has come from a relational database. The Elasticsearch guide article Data In, Data Out is a good place to start reading. Another article called Managing relations inside Elasticsearch is particularly relevant to your situation:
-7595632 0 VS11 Dev Preview Unit Test Explorer doesn’t show Unit TestsAt it's heart, Elasticsearch is a flat hierarchy and trying to force relational data into it can be very challenging. Sometimes the best solution is to judiciously choose which data to denormalize, and where a second query to retrieve children is acceptable
I wonder has anyone come across with this issue where the MSTest Unit Test doesn’t show up in the new Unit Test Explorer.
I’m running Windows 7 (32bit). I downloaded the VS11 Developer Preview from the link below. http://www.microsoft.com/download/en/details.aspx?id=27543
I created a sample C# Console App, and add the Test Library from the MSTest project template. Then I created a sample Unit Test, and rebuild the solution. When I open the Test Explorer (View->OtherWindows->UnitTest Explorer) I do not see any tests loaded.
I only see a message saying… “No test discovered. Please build your project and ensure the appropriate test framework adapter is installed”.
I assume the MSTest adapter is automatically installed. If not I’m not even sure how to install an adapter.
I could be missing something here but I cannot figure it out. Has anyone experiencing this issue?
-24671738 0To set the composer autoloader you can create a target as:
<target name="require.autoload"> <adhoc><![CDATA[ require_once 'lib/composer/autoload.php'; ]]></adhoc> </target> Then all the targets that need autoloader, has this requirement
<target name="test.coverage.html" depends="require.autoload"> Note: require once the file placed in
"config": { "vendor-dir": "lib/composer"
-13996296 0 Alternatively, if your implementation of grep supports it, you could use
grep -m 10 PATTERN FILE Partial description from: man grep on Ubuntu 12.04
-m NUM, --max-count=NUM Stop reading a file after NUM matching lines. This option was also available on my Red Hat 5.8 box where I was having a similar issue.
-20310467 0You want to
If an item is "already" in t2, but NOT in t1 then I would like to avoid executing an INSERT statement.
So insert should take place on negation of above statement i.e.
item should not be in t2 and item should be present in t1
insert into target_table( column list ) select ( column list) from source_table where item not in (select item from t2) and item in (select item from t1) what I meant was that if the article is NOT in t2, THEN I want to insert it into t1. Its pretty simple really
insert into t1 ( <column list>) select <column list> from source_table where item not in (select item from t2) You can use
IF NOT EXISTS (SELECT * FROM t2 WHERE item like '%'+@itemvalue+'%') BEGIN INSERT INTO t1 VALUES (@itemvalue) END
-31184265 0 I think you need to add a row to your query like this:
SELECT MAX(sum_date) As sum_date, MAX(sum_accname) As sum_accname, MAX(sum_description) As sum_description, SUM(credit) As credit, SUM(debit) As debit, 1 As uNo FROM sum_balance WHERE sum_accname = {?acc_name} AND sum_date < {?fromDate} UNION ALL SELECT sum_date, sum_accname, sum_description, credit, debit , 2 as uNo FROM sum_balance WHERE sum_accname = {?acc_name} AND sum_date >= {?fromDate} AND sum_date <= {?toDate} With this query your first row, or the row that uNo = 1 has the sum of older debits and credits.
So if you only need to check that a new window is open:
int oldWindowCount = driver.getWindowHandles().size(); driver.findElement(<By locator for hyperlink here>).click(); int newWindowCount = driver.getWindowHandles().size(); Assert.assertEquals(1, newWindowCount - oldWindowCount); Assuming you have no more than two windows open, if you want to switch between your current window and the new one:
String oldWindow = driver.getWindowHandle(); driver.findElement(<By locator for hyperlink here>).click(); for (String handle : driver.getWindowHandles()) { if (!handle.equals(oldWindow)) { driver.switchTo().window(handle); } }
-18985990 0 in your controller UsersController, in the update method, add the address: :id to the address permitted attributes. Like this:
params.require(:user).permit(:user_name, address_attributes: [:id, :street]))
-31104469 0 System.Runtime.InteropServices.COMException: This command is not available because no document is open I am using code below -I try to save Word document file as .htm. Can anybody solve this problem?
objWord.Documents.Open(ref FileName, ref readOnly, ref missing, ref missing, ref missing, ref missing,ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing,ref missing, ref missing); Document oDoc = objWord.ActiveDocument; oDoc.SaveAs(ref FileToSave, ref fltDocFormat, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
-16361638 0 Scala - weird behaviour with Iterator.toList I am new to Scala and I have a function as follows:
def selectSame(messages: BufferedIterator[Int]) = { val head = messages.head messages.takeWhile(_ == head) } Which is selecting from a buffered iterator only the elems matching the head. I am subsequently using this code:
val messageStream = List(1,1,1,2,2,3,3) if (!messageStream.isEmpty) { var lastTimeStamp = messageStream.head.timestamp while (!messageStream.isEmpty) { val messages = selectSame(messageStream).toList println(messages) } Upon first execution I am getting (1,1,1) as expected, but then I only get the List(2), like if I lost one element down the line... Probably I am doing sth wrong with the iterators/lists, but I am a bit lost here.
-12571696 0Probably its your own plugin that's locking the files. Try to implement a method/strategy to "release" them before attempting to delete. You can use Apache Commons IO to help you build/identifying this. Take a look at the FileDeleteStrategy. Also check the "FORCE" option.
-36429647 1 vim expandtab doesn't work after new installationlet mapleader = "," set number set textwidth=79 " lines longer than 79 columns will be broken set shiftwidth=4 " operation >> indents 4 columns; << unindents 4 columns set tabstop=4 " a hard TAB displays as 4 columns set expandtab " insert spaces when hitting TABs set softtabstop=4 " insert/delete 4 spaces when hitting a TAB/BACKSPACE set shiftround " round indent to multiple of 'shiftwidth' set cindent " align the new line indent with the previous line set nobackup set nowritebackup set noswapfile vnoremap < <gv " continue visual selecting after shiftwidh vnoremap > >gv nnoremap <C-h> <C-w>h nnoremap <C-j> <C-w>j nnoremap <C-k> <C-w>k nnoremap <C-l> <C-w>l nnoremap j gj nnoremap k gk nnoremap <Leader>r :w \| !clear && ./%<CR> command W w !sudo tee % > /dev/null noremap <silent><Leader>/ :nohls<CR> set clipboard=unnamedplus set paste set ignorecase Somehow after reinstallation of my arch linux, vim stoped work poperly. After doing the same I did couple days ago with old system - now python complains about indentation.
I have no installed plugins or whatever, why does this broke?
P.S. already viewed same quiestions, but them was about plugins, which I doesn't have. P.S. Noticed that after : vim won't start newline according cindent
Still indentation brokes after :set paste. Why this happens?
It's possible to use myMock.Verify(m => m.f(It.IsAny<string>()), ...); to assert that the method f(string s) has been called at least / at most / exactly n times.
I want to do something a bit more complicated: I want to ensure that the number of calls to f(string s) plus the number of calls to f(int i) is equal to 3.
Is there an lightweight way to do it with Moq?
More details
Actually I can think of a way to do it: I could setup a callback that would increment a counter when each of those methods is used. However it would require more set up in the test, which could hinder it's readability. (And it would be a shame to re-implement something that could already be implemented in moq).
For instance a lightweight way to do it could be to be able to retrieve the exact number of call to my method, so that I could Assert.AreEqual on it. But I haven't been able to find a way to do it so far.
If you want a composite object try something like
$results = (Invoke-RestMethod -URI "http://www.broadbandmap.gov/broadbandmap/broadband/dec2013/wireline?latitude=29.488412&longitude=-98.550208&format=json") $obj = $results.Results.wirelineServices $obj | add-member -type noteproperty -Name StateFips -Value $($results.Results.broadbandSource.stateFips) -PassThru $obj | convertto-xml -as string
-35640059 0 This should works for you:
@"-?\d+(?:\.\d+)?" Matchs only the dot only when have digits after it.
-29936664 0 Which version of oracle should I learn as a beginer?I am beginner in Oracle. I have seen there are many oracle version such as XE, Enterprises, Personal, Liet and so on. I would like to learn Oracle but I am very confuse which oracle version should I learn first?
-15144825 0Use subList(int fromIndex, int toIndex):
List<Double> arrayList = ...; int length = arrayList.size(); for(int i = 0; i < length - 1; i++) { Double db1 = arrayList.get(i); for(Double db2 : arrayList.subList(i + 1, length)) { // ... } }
-40344960 0 Post relational data, Spring JPA REST I have a relational database with a normalized form of my data, but my API will need to receive the information in a denormalized way, what is the correct way to handle this? Is it a matter of creating a new endpoint with the fields denormalized?
How would I decouple that from the database so that Spring Boot doesn't create a new table for me?
For example, here are (some of) my tables:
@Entity public class TestCase { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String name; private String description; } @Entity public class TestRun { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private Boolean result; private String username; @OneToOne private TestData testData; @ManyToOne private TestCase testCase; } @Entity public class TestData { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private int count; @ManyToOne private RecordType recordType; } I want to create an API endpoint that will create new entries in TestRun and TestData at the same time, while referencing existing entries in TestCase and RecordType.
How is this done?
A complete answer needs to show:
The "DEMO" files you're referring to are found in the "Examples" folder in that GitHub Repo.
For your own use, you will need to take those demo files and modify them for your use and then drop them into your own project.
As for your "homeViewController.m" file, I would imagine you'd replace the first line of that code with something like:
DEMONavigationController *navigationController = [[DEMONavigationController alloc] initWithRootViewController:[[homeViewController alloc] init]]; (by the way... you should name your Objective-C classes and files with capital letters. It's methods, properties and variable names that should start with lower case letters).
-18231373 0You load ckeditor and after you fill the textarea. No way, the ckeditor is loaded. An has not live update. You must change order.
<script> function BindData() { $("#input").val('This is CK Editor Demo'); } BindData(); $(document).ready(function () { $("#input").ckeditor(); }); </script>
-13030896 0 iOS Handling the UIBarButtonItem the way of Unwinding Segue In iOS 6 you have Unwinding Segue to return to previous view controller.
I am now working with storyboard, to figure that thing. And i am on iOS 5 where i dont have Unwinding Segue.
The picture explains the situation: 
In third window (i think its officially called story) there is a Done button.
How to make that button return an object with text on screen and return to window 2? There, i window 2 the table should refries, but that is out of the scope of this question.
What i did was to implement IBOutlet in ThirdWindowViewController (lets call it that), which is linked to IBAction method.
@property (nonatomic, strong) IBOutlet UITextView* textView; @property (nonatomic, strong) Note* note; @property (nonatomic, retain) IBOutlet UIBarButtonItem* doneButton; - (void) configureView; - (IBAction) doneAction:(id)sender; - (BOOL) prepareNoteForTransition; EDIT_01
As Tom wrote, you need a delegate. That is the way i actually did it, with methods i put above. I just thought that there is some more apple-specific way to do it, like that Segues. or some alternatives.
Thanks guys.
-38500580 0 when enabling errors to bigquery I do not receive the bad record numberI'm using bigquery command line tool to upload these records:
{name: "a"} {name1: "b"} {name: "c"} .
➜ ~ bq load --source_format=NEWLINE_DELIMITED_JSON my_dataset.my_table ./names.json this is the result I get:
Upload complete. Waiting on bqjob_r7fc5650eb01d5fd4_000001560878b74e_1 ... (2s) Current status: DONE BigQuery error in load operation: Error processing job 'my_dataset:bqjob...4e_1': JSON table encountered too many errors, giving up. Rows: 2; errors: 1. Failure details: - JSON parsing error in row starting at position 5819 at file: file-00000000. No such field: name1. when I use bq --format=prettyjson show -j <jobId> I get:
{ "status": { "errorResult": { "location": "file-00000000", "message": "JSON table encountered too many errors, giving up. Rows: 2; errors: 1.", "reason": "invalid" }, "errors": [ { "location": "file-00000000", "message": "JSON table encountered too many errors, giving up. Rows: 2; errors: 1.", "reason": "invalid" }, { "message": "JSON parsing error in row starting at position 5819 at file: file-00000000. No such field: name1.", "reason": "invalid" } ], "state": "DONE" } } As you can see I receive an error which tells me in what line I had an error. : Rows: 2; errors: 1
Now I'm trying to enable errors by using max_bad_errors
➜ ~ bq load --source_format=NEWLINE_DELIMITED_JSON --max_bad_records=3 my_dataset.my_table ./names.json here is what I receive:
Upload complete. Waiting on bqjob_...ce1_1 ... (4s) Current status: DONE Warning encountered during job execution: JSON parsing error in row starting at position 5819 at file: file-00000000. No such field: name1. when I use bq --format=prettyjson show -j <jobId> I get:
{ . . . "status": { "errors": [ { "message": "JSON parsing error in row starting at position 5819 at file: file-00000000. No such field: name1.", "reason": "invalid" } ], "state": "DONE" }, } when I check - it actually uploads the good records to the table and ignores the bad record,
but now I do not know in what record the error was.
Is this a big query bug? can it be fixed so I receive record number also when enabling bad records?
-7962522 0I am not sure but I have a feeling your problem is in the selector you are passing to the button.
Try to see if you are using a selector with ":" to a method with out parameters.
If you are using selector that looks like this:
@selector(method:) Then is is expected that "method" will take parameters:
-(IBAction)method:(UIButton)sender{ } if your function is not taking any parameters:
-(IBAction)method{ } then your selector should look like that:
@selector(method)
-41020613 0 How similar are boost::filesystem and std::filesystem? I believe boost::filesystem was at least one of the "source" libraries used to design std::filesystem for C++17.
How similar are they? If very similar, what are the known gotchas and incompatibilities? If not, where are they similar?
This is in the context of implementing something with std::filesystem, std::experimental::filesystem or boost::filesystem, and wanting to know the likely scope of efforts required if we switch libraries (say, if one discovers that the std library on a particular platform is inadequate).
This is not a request for an alternative library recommendation.
-28696650 0 Windows Phone 8.0 ListBox Out Of Memory ExtensionSorry for my english. I'am execute next code: in XAML ...
<Button Content="Add More" Width="160" Click="Button_Click_2"/> <ListBox x:Name="list"/> ...
in CS ...
for (int i = 0; i < 20; i++) { list.Items.Add(new Image { Source = new BitmapImage { UriSource = new Uri("http://pravda-team.ru/eng/image/photo/4/7/4/73474.jpeg") } }); } ...
This code working, but if I click on the button a few times, there is an exception "Out Of Memory Extension" I tried to use Garbage Collector and AutoCaching, but the error persists. I catch this extension on the next screen shot: 
I use jboss-IDE. so, I created a project with many EJB's in the same project. now, I need a functionality exposed by EJB A in EJB B. so, I need to call EJB A in EJB B. How do I do that ?
P.S : dealing with EJB 2.
-27848100 0 Why won't my page expand to the increasing size of an absolutely positioned div?I have a form fixed to the bottom of the page, and an absolutely positioned div above it. Output from the form correctly displays just above the form itself, but when the output fills the page, I cannot scroll up and view it. It seems that the output overflows the body element, and is ignored.
I've tried making the output div, called main, positioned relative, but the content does not appear where I want it.
My markup in Haml:
%body .title-wrapper %h1 .main .form-wrapper %form{:action => "/", :method => "post", :id => 'target'} %input{:type => "text", :name => "code", :class => "input"} my CSS:
* { font-family: Menlo, sans-serif; } .main { font-size: 14pt; position: absolute; bottom: 3em; width: 70%; } .title-wrapper { float: right; display: inline-block; height: 100%; width: 20%; } h1 { display: inherit; float: right; position: fixed; } .form-wrapper { width: 97%; position: absolute; bottom: 1em; } .input { width: 100%; height: 2em; font-size: 14pt; } Image:

sorry, can't reproduce your problem, see screenshot (HTC Desire, Android 2.2, Dolphin browser), which looks fine...

Of course. However just make sure you don't have too many.
-33361695 0page-break is not enough for internet explorer by own. If u try this, you can see the result. I have same problem but I solved by this way.
<div style="page-break-after: always;"></div> <div> </div> By HTML specifications, you cannot use a link element inside the body element. You should arrange things so that link elements appear inside the head element. In the given context, you can achieve this by omitting the div class=body markup (it should not be needed, though omitting it may require changes to your CSS code) as well as the </head> and <body> tags. There are probably smarter ways to achieve the goal, though.
I had a similar issue and this worked for me:
$ cd /usr/local/Cellar/imagemagick/6.8.0-10/lib $ ln -s libMagick++-Q16.7.dylib libMagick++.dylib $ ln -s libMagickCore-Q16.7.dylib libMagickCore.dylib $ ln -s libMagickWand-Q16.7.dylib libMagickWand.dylib Hope this helps.
Credit: https://coderwall.com/p/wnomjg
-39439049 1 how to detect that microphone is on or off in python 3Its not duplicate
I have a python code that uses speech recognition and it has a problem when microphone is off so i want to add a code that closes python if microphone is off and if its not then runs the whole script.
for example:
import speech_recognition as sr #if microphone is on : r = sr.Recognizer() with sr.Microphone() as source: audio = r.listen(source) try: said = r.recognize_google(audio) print(audio) except sr.UnknownValueError: print('google did not understand what you said') except sr.RequestError as e: print('errpr' + "; {0}".format(e)) #else print('please turn your microphone on and open again') quit() any ideas how to do that?
Its not a duplicate question and it's completely a different question
In this link : we can detect that microphone is connected to pc or not , i wanna detect that microphone button is on or off.
Actually my codes has this error that when my microphone is off and i run the code then i turn that on while code is still running , it will not recognize my voice , so i want to warn user to turn his microphone on then restart program.
-31474212 0A path always contains the core component and the complete address list required to locate the file. It is mainly significant environment variable of Java environment. In other words it represents a path that is hierarchical sequence of directory and file name elements separated by a special partition. A Path can represent a root, a root and a sequence of names .A path is considered to be an empty path if it consists solely of one name element that is empty. For more details you can move to resume writing service Indianapolis from online.
-19620703 0 How to access a textbox text from gridview to a button Onclick eventI am having textboxes and buttons in gridview. What I want is that when I click on those buttons the corresponding value in textbox is updated to database, so I need to access the textbox text in OnClick event. How can I do this?
Gridview:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" ForeColor="Black" OnRowDataBound="GridView1_RowDataBound" onselectedindexchanged="GridView1_SelectedIndexChanged"> <Columns> <asp:TemplateField HeaderText="Save 1"> <ItemTemplate> <asp:TextBox ID="TextBox1" Width="30px" runat="server"></asp:TextBox> <asp:Button ID="btnSave1" runat="server" Text="Save" OnClick="btnSave1_Click" /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Save 2"> <ItemTemplate> <asp:TextBox ID="TextBox2" Width="30px" runat="server"></asp:TextBox> <asp:Button ID="btnSave2" runat="server" Text="Save" OnClick="btnSave2_Click" /> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> Button Onclick Event:
protected void btnSave1_Click(object sender, EventArgs e) { //I want to access TextBox1 here. } Please help me out of this.
-21799388 0For types smaller than the size of a pointer (e.g. int), passing by value is more efficient.
For types bigger than the size of a pointer (e.g. most struct or class instances), passing by reference is probably more efficient (only "probably" because on top of the cost of passing the parameter, potentially constructing an object, you incur the cost of dereferencing your parameter every time you use it).
More details about passing-by-value vs. passing-by-reference can be found in this question. More details about reference vs. pointer arguments can be found in that question.
-38325316 0Starting from KitKat, you have access to a method to get that directory :
Context.getExternalFilesDirs() Note that it may return null if the SD card is not mounted or moved during the access. Also, you might need to add these permissions to your manifest file :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
-38199543 0 It looks to me as though you are having problems with understanding how to create a recursive operation for your folders. I'll try to give you an example of how I would handle this. Given my example may not be the best.
public static final String NAME = "Demo-Folder"; public static final String PARAM_ASPECT_NAME = "folder-name"; private NodeService nodeService; /** * Set the node service * * @param nodeService the node service */ public void setNodeService(NodeService nodeService) { this.nodeService = nodeService; } public void executeImpl(Action action, NodeRef actionUponNodeRef) { ChildAssociationRef childAssociationRef = nodeService.getPrimaryParent(actionUponNodeRef); System.out.println("****The folder is***** "+ childAssociationRef); iterateThroughChildren(childAssociationRef); } public void iterateThroughChildren(ChildAssociationRef childAssocRef) { System.out.println("****The folder is***** "+ childAssocRef); NodeRef childNodeRef = childAssocRef.getChildRef(); List<ChildAssociationRef> children = nodeService.getChildAssocs(childNodeRef); for (ChildAssociationRef childAssoc : children) { childAssoc.getChildRef(); // Use childNodeRef here. System.out.println("******Documents inside are******"+ childAssoc); // This call recurses the method with the new child. iterateThroughChildren(childAssoc); // If there are no children then the list will be empty and so this will be skipped. } } I used your code above, and extended it out to include a new method called iterateThroughChildren which takes the ChildAssociationRef and gets the children and iterates through them. During the iteration the children are passed back into the method to allow for their children to be iterated, and so on until there are no children (meaning you are at the end of a branch). This allows you to iterate through an entire tree structure.
actually i want to show the curve at the bottom right side of my tabs..so how can it be done..the code i have used..
Code for Xml
<?xml version="1.0" encoding="utf-8"?> <TabHost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/tabhost" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content"/> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="fill_parent"/> </LinearLayout> </TabHost> code for second xml
<?xml version="1.0" encoding="UTF-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <!-- When selected, use grey --> <item android:drawable="@drawable/ic_tab_artists_white" android:state_selected="true" android:state_pressed="false" /> <!-- When not selected, use white--> <item android:drawable="@drawable/ic_tab_artists_grey" /> </selector> code for .java file
Resources res = getResources(); final TabHost MainTabHost = getTabHost(); TabHost.TabSpec spec; Intent intent; MainTabHost.getTabWidget().setStripEnabled(false); //call calendar Activity class intent = new Intent().setClass(this, CalendarForm.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); spec = MainTabHost.newTabSpec(res.getString(R.string.text_tabHost1)).setIndicator("Calendar", res.getDrawable(R.drawable.calendar_ic)).setContent(intent); MainTabHost.addTab(spec); //call History Activity class intent = new Intent().setClass(this, HistoryForm.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); spec = MainTabHost.newTabSpec(res.getString(R.string.text_tabHost2)).setIndicator("History", res.getDrawable(R.drawable.calendar_ic)).setContent(intent); MainTabHost.addTab(spec); //call Statistic Activity class intent = new Intent().setClass(this, StatisticForm.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); spec = MainTabHost.newTabSpec(res.getString(R.string.text_tabHost3)).setIndicator("Statistic", res.getDrawable(R.drawable.calendar_ic)).setContent(intent); MainTabHost.addTab(spec); //setbackground Style of tabHost MainTabHost.setCurrentTab(0); MainTabHost.getTabWidget().setWeightSum(3); final TabWidget tabHost=getTabWidget(); MainTabHost.setBackgroundResource(R.drawable.back_image); for (int j = 0; j < MainTabHost.getTabWidget().getChildCount(); j++) { ((TextView)tabHost.getChildAt(j).findViewById(android.R.id.title)).setTextColor(Color.parseColor("#FFFFFF")); ((TextView)tabHost.getChildAt(j).findViewById(android.R.id.title)).setTextSize(16); } 
this is what i got..here tabs are square now i want my tabs curve at the bottom right side
-36431950 0There is no official example but check below link.
Very good implementation. https://github.com/roughike/BottomBar
Do you have an /app/templates/client-availibilities.hbs template with only {{outlet}} inside of it? Without this, the app is going to lose its place in the outlet tree. Ember-CLI and the Ember Starter Kit are very, very different from each other in structure, so I can see where the confusion comes from.
How I like to think of Ember's rendering style is that each handlebars file inside the templates folder (i.e. /templates/users.hbs) represents a change the overall state of the application from one subject to another (example: from newsfeed to users). The corresponding subfolders inside the templates folder change the state of the subject itself.
For example:
You can have [ /templates/users.hbs ] without having [ /templates/users/*.hbs ] and still keep track of your data; however, you cannot have [ templates/users/index.hbs ] without [ /templates/users.hbs ] and still keep track of your data. Why? Imagine if you navigate to somesite.com/users. There is currently no top-level template with an outlet into which Ember can render the [ users/index.hbs ] template. The [ /templates/users.hbs ] template bridges that gap and also serves as a container for all other pages inside the /templates/users folder as well.
For example, in the terms of your app, in order to render [ /app/templates/client-availibilities/index.hbs ] when a user visits http://www.yourwebsite.com/client-availibilities, your app will need these templates defined so that ember can drill down into them.
application.hbs // and in its outlet, it will render... --client-availibilities.hbs // and in its outlet, it will render by default... ----client-availibilities/index.hbs // then, for the client-availability (singular), you can have ember render it in ----client-availibilities/show.hbs // will render also in the client-availabilites as it is a separate state of the subject. Can also be nested inside the index route within the router so that it renders inside the index template. As it is, I would structure your app as such...
/app/router.js
... // previous code Router.map(function() { this.resource('client_availabilities', function() { this.route('show', { path: '/:client_availability_id' }); // this.route('new'); ! if needed ! // this.route('edit', { path: '/:client_availability_id/edit' ); ! if needed ! }); }); ... // code /app/templates/application.hbs
{{link-to 'Client Availabilities' 'client_availabilities'}} {{outlet}} /app/templates/client-availabilities.hbs
{{outlet}} /app/templates/client-availabilities/index.hbs
<ul> {{#each}} {{#if available}} <li> {{#link-to #link-to 'client-availabilities.show' this}} {{firstName}} {{lastName}} {{/link-to}} </li> {{/if}} {{else}} <!-- we want this to only render if the each loop returns nothing, which is why it's outside the if statement --> <li>Nobody is available</li> {{/each}} </ul> <!-- Note: you don't need to put an outlet here because you're at the end of the tree --> /app/templates/client-availabilities/show.hbs
<!-- Everything you want to show about each availability -->> <!-- Note: you don't need to put an outlet here because you're at the end of the tree --> /app/routes/client-availabilities/index.js
import Ember from 'ember'; export default Ember.Route.extend({ model: function() { return this.store.findAll('client_availability'); } }); /app/routes/client-availabilities/show.js
import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.find('client-availability', params.client_availability_id); } }); /app/models/client-availability.js
import DS from 'ember-data'; var client-availability = DS.Model.extend({ firstName: DS.attr('string'), lastname: DS.attr('string'), available: DS.attr('boolean'), available_on: DS.attr('date') }); export default client-availability; However, are you sure you want to structure your app by the availability of each client? Wouldn't it make more sense to structure it by each client and then just filter each client to show if they were available or not? Resources are supposed to be nouns, and routes are supposed to be adjectives. Therefore, it would be best to use a client as your model instead of their availability and have a either an isAvailable property on the model (as used in the example above) or a one-to-many association with an additional availability model if you want to show clients who have several availabilities (as shown below).
For example,
/app/models/client.js
import DS from 'ember-data'; var Client = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), availabilities: DS.hasMany('availability') }); export default Client; /app/models/availability.js
import DS from 'ember-data'; var Availability = DS.Model.extend({ date: DS.attr('date'), client: DS.belongsTo('client') }); export default Availability; In the long run, this latter approach would set up your app to show all availabilities at once and allow the user to filter by the client, plus it would allow the user to view a client and see all their availabilities. With the original approach (the isAvailable property on the client model), the user can only get the availabilities from the client model itself, but what if the user wants to see all clients who are available on, say, March 3rd at noon? Well, without an availability model associated with the client model, you are going to have to put a lot of code into your client controller that ember would give you by default if you go down the one-to-many path.
If you need more advice on where to go from here, let me know. I'm more than happy to add more examples of the templates, controllers, and routes that you'll need in order to pull this off.
-39003364 0The issue is in e.target.Id. It should id(lower case) since javascript is a case-sensitive language.
var list = document.querySelector("ul"); list.onclick = function(e) { if(e.target.tagName === "LI") { e.target.classList.toggle("done"); } }; var list2 = document.getElementById("list2"); list2.onclick = function(e) { if(e.target.id === "text") { e.target.classList.toggle("done"); } }; .done{ background-color:greenyellow; } <ul> <li>One</li> <li>Two</li> <li>Three</li> </ul> <div id="list2"> <p id="text">Text</p> <p id="text">Text</p> <p id="text">Text</p> </div> Ok I wasn't really sure how to word this question, but basically what I want to do is, I got a url from a RSS feed in android, and I need to put part of that url into a string, the url will look something like this: http://www.prsn.uprm.edu/Spanish/Informe_Sismo/myinfoGeneral.php?id=20161206012821' and I only want the part after id= ONLY THE ID NUMBER,Then I need the id to put it in the following url: http://shake.uprm.edu/~shake/archive/shake/**ID HERE**/download/tvmap.jpg, to load the image corresponding to the id in Glide: [Solved] This Part is solved but i have a other Problem
I have to ways to do this
First Way:
//the original String String somestring = "http://www.prsn.uprm.edu/Spanish/Informe_Sismo/myinfoGeneral.php?id=20161206012821"; //save the index of the string '=' since after that is were you find your number, remember to add one as the begin index is inclusive int beginIndex = somestring.indexOf("=") + 1; //if the number ends the string then save the length of the string as the end, you can change this index if that's not the case int endIndex = somestring.length(); //Obtain the substring using the indexes you obtained (if the number ends the string you can ignore the second index, but i leave it here so you may use it if that's not the case) String theNumber = somestring.substring(beginIndex,endIndex); //printing the number for testing purposes System.out.println("The number is: " + theNumber); //Then create a new string with the data you want (I recommend using StringBuilder) with the first part of what you want StringBuilder sb=new StringBuilder("http://shake.uprm.edu/~shake/archive/shake/"); // add the number sb.append(theNumber); //then the rest of the string sb.append("/download/tvmap.jpg"); //Saving the String in a variable String endResult = sb.toString(); //Verifying end result System.out.println("The end result is: "+endResult); Glide.with(context).load(endResult).into(holder.Thumbnail); Second Way:
String url = "http://www.prsn.uprm.edu/Spanish/Informe_Sismo/myinfoGeneral.php?id=20161206012821"; String[] array = url.split("id="); String id = array[1]; String urlToLoad = "http://shake.uprm.edu/~shake/archive/shake/"+id+"/download/tvmap.jpg" Glide.with(context).load(urlToLoad).into(holder.Thumbnail); [Problem]
My problem is, if i put the URL normally, ie http://www.prsn.uprm.edu/Spanish/Informe_Sismo/myinfoGeneral.php?id=20161206012821 the two methods work for me, but if I get the url Via getLink() does not work for me. Please help me.
I hope I explained well. Thanks in advance.
There is my Myadapter.java the method to get the link is current.getLink()
package com.example.rssreader; import android.animation.ObjectAnimator; import android.content.Context; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.daimajia.androidanimations.library.Techniques; import com.daimajia.androidanimations.library.YoYo; import com.squareup.picasso.Picasso; import java.util.ArrayList; /** * Created by Efrain on 26-02-2016. */ public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> { ArrayList<FeedItem>feedItems; Context context; public MyAdapter(Context context,ArrayList<FeedItem>feedItems){ this.feedItems=feedItems; this.context=context; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view= LayoutInflater.from(context).inflate(R.layout.custum_row_news_item,parent,false); MyViewHolder holder=new MyViewHolder(view); return holder; } @Override public void onBindViewHolder(MyViewHolder holder, int position) { YoYo.with(Techniques.FadeIn).playOn(holder.cardView); FeedItem current=feedItems.get(position); holder.Title.setText(current.getTitle()); holder.Description.setText(current.getDescription()); holder.Date.setText(current.getPubDate()); holder.Link.setText(current.getLink()); //the original String String somestring = current.getLink(); //save the index of the string '=' since after that is were you find your number, remember to add one as the begin index is inclusive int beginIndex = somestring.indexOf("=") + 1; //if the number ends the string then save the length of the string as the end, you can change this index if that's not the case int endIndex = somestring.length(); //Obtain the substring using the indexes you obtained (if the number ends the string you can ignore the second index, but i leave it here so you may use it if that's not the case) String theNumber = somestring.substring(beginIndex,endIndex); //printing the number for testing purposes System.out.println("The number is: " + theNumber); //Then create a new string with the data you want (I recommend using StringBuilder) with the first part of what you want StringBuilder sb=new StringBuilder("http://shake.uprm.edu/~shake/archive/shake/"); // add the number sb.append(theNumber); //then the rest of the string sb.append("/download/tvmap.jpg"); //Saving the String in a variable String endResult = sb.toString(); //Verifying end result System.out.println("The end result is: "+endResult); Glide.with(context).load(endResult).into(holder.Thumbnail); } @Override public int getItemCount() { return feedItems.size(); } public class MyViewHolder extends RecyclerView.ViewHolder { TextView Title,Description,Date,Link; ImageView Thumbnail; CardView cardView; public MyViewHolder(View itemView) { super(itemView); Title= (TextView) itemView.findViewById(R.id.title_text); Description= (TextView) itemView.findViewById(R.id.description_text); Date= (TextView) itemView.findViewById(R.id.date_text); Thumbnail= (ImageView) itemView.findViewById(R.id.thumb_img); cardView= (CardView) itemView.findViewById(R.id.cardview); Link= (TextView) itemView.findViewById(R.id.info); } } }
-17843882 0 php search result images show across and fill a CSS div I'm using dreamweaver and php to return a list of images based on search critiera. I have used Dreamweaver's repeat function and can get the images to repeat below each other (as below).
<table width="100" height="38" border="1"> <?php do { ?> <tr> <td width="38"> <img class='example' src="images/<?php echo $row_getresult['image_name']; ?>.png"/><br> </a></td></tr> <?php } while ($row_getamenityaccommodation = mysql_fetch_assoc($getamenityaccommodation)); ?> </table> How can I get the images to go across from each other within a CSS Div e.g. float:left; width:45%; so that if there are more images than what would fit in 45%, the images would continue onto a new line?
Would somehow 'printing' the array work?
-3827551 0 Complete flash wordpress theme is possible? (with a php pipe of course)Is possible to have the posts loaded into an swf using the wordpress framework? i mean, i want to write a post using the wordpress wp-admin interface and then see the result in a swf... I know that if i access using a php pipe the mysql server i can retrive the posts, but as i said i want to use the facebook framework... Is out there an allready made script to do this? any ideas? Thanks!
-4769380 0Because you cannot declare class properties with variable expressions. That means you cannot use any arithmetic operators + - * / or the concatenation operator ., and you can't call functions. Out of your three lines, only $test should work; the other two will give you errors.
If you need to build your strings dynamically, do it in the constructor.
class Object { public $test = "Hello"; public $var2; public function __construct() { $this->var2 = $this->test . "World"; } } By the way, . is not a "string separator". It's the concatenation operator. You use it to join strings, not separate them.
So, I have gone round and round on this issue and all I can come to is that this is an inherent flaw in jquery, but I'm posting this question here as a last resort.
Here's the 1,000 ft view of the project. I'm making a slideout feature similar to the new Google Image search results. I have a grid of boxes, some that expand for deeper content and some that do not. The way I am accomplishing this is by running the below javascript to dynamically add 'row' divs below each row of grid boxes that has expandable content.
function defineFocusRowLength() { var rowFocusBoxCount = 0; $('#isofocus .focusbox.core').each(function(){ rowFocusBoxCount++; if($(this).css('float') === 'right') { finalFocusRowBoxCount = rowFocusBoxCount; return false; } }); $('#isofocus .slidecontent').remove(); $('#isofocus .focusbox.core:nth-child('+finalFocusRowBoxCount+'n)').after('<div class="slidecontent"><div class="wrap"></div></div>'); if($('#isofocus .focusbox.core').last().css('float') === 'right') { // do nothing because it should have been caught by the previous line } else { $('#isofocus .focusbox.core').last().next('.focusbox').each(function(){ if($(this).css('float') === 'right') { if($(this).next('.focusbox').css('float') === 'right') { $(this).next('.focusbox').after('<div class="slidecontent"><div class="wrap"></div></div>'); } else { $(this).after('<div class="slidecontent"><div class="wrap"></div></div>'); } } }); } } defineFocusRowLength(); $(window).resize(function() { defineFocusRowLength(); }); In case you are wondering, I am calling this function on window.resize as well because my site is responsive, so as the grid reorganizes this function removes the old expanded rows and creates new ones in the appropriate spaces.
This part of my code all works beautifully. No problems whatsoever. However, it's when I try to target these new divs with .next() that completely fails.
Here is the code I execute when you click the in each box:
$(".focusbox a.popup").click(function(){ var expandtext = $(this).parents('.focusbox').children('.expanded-content').html(); $(this).parents('.focusbox').next('.slidecontent').html(expandtext); $(this).parents('.focusbox').next('.slidecontent').slideToggle(); }) Now, I have tried about 20 other variations of this code and they work. It is just this specific way I am needing it to work that fails. Here are some of the variations I used that worked, but were not the proper result:
$(this).parents('.focusbox').next().slideToggle(); //works, but slides up the next box, not the expanded row $(this).parents('.focusbox').siblings('.slidecontent').slideToggle(); //works but shows all expanded rows $(this).parents('#isofocus').find('.slidecontent').slideToggle(); //works but shows all expanded rows So yeah, I'm pretty much at my wits end here and believe that this is just inherintly a flaw in jquery that the .next() function is unable to access selectors of content that is generated after page load, even if the function is not called until after the page has loaded.
Here is my jsfiddle for you to take a stab at it: http://jsfiddle.net/RCVfK/1/
-25815455 0Found a workaround. I am using this method on ubuntu so paths may be different for other os.
Go to /usr/lib/node_modules/ionic/lib/ionic
Open serve.js with root user.
Find function called IonicTask.prototype.getAddress
Inside this function the value of variable isAddressCmd is false. Set it to true
self.isAddressCmd = false; save the file. Now run Ionic serve for your project. This time it will ask for localhost vs ip again.
After this remove the newly added code from serve.js otherwise ionic serve won't work.
I am finding evidence which suggests that this problem is related to MySQL version 5.5.8. What version of MySQL are you running?
-35288013 0 Recyclerview viewholder possible to change views at other adapter positions (not current position)?I have a recyclerview with mediaplayer to play a song on each row. I only have one button for play/stop which changes symbol.
Here is my problem:
Example 1 (This works fine):
(For adapter position 1) the user hits the play symbol and music plays for that adapter position and the symbol changes to a stop symbol, they then hit the stop symbol and the music stops and the symbol changes back to a play symbol ready to start the music again.
Example 2 (This is the problem)
(For adapter position 1) the user hits the play symbol and music plays for that adapter position and the symbol changes to a stop symbol. Without hitting that button again they then hit the play symbol (adapter position 3) so now they are trying to play the song on position 1 and 3 at the same time. I have fixed both songs playing at the same time so that when the the second song is pressed the media played is reset and the source song file is changed to the new song (only one will play at a time).
The problem then becomes even though the media player is behaving as it should. The mediaplayer is controlled in the mainactivity. The play/stop button (imageview) image is changed in the the adapter viewholder and I can't work out a way to change the play/stop symbol when more than one song is clicked at the same time.
This image shows the example both song 1 and song 3 have been pressed. Now only song 3 is playing but the images are still showing as if both songs are playing simultaneously.
This is my view holder where I handle changing the play/stop image and send the song clicked callback:
class AddVideoAudioViewHolder extends RecyclerView.ViewHolder{ ImageView PlayButton; Button AddAudioButton; TextView Title; public AddVideoAudioViewHolder(View itemView) { super(itemView); PlayButton = (ImageView) itemView.findViewById(R.id.PlayStopAudioDemo); PlayButton.setTag(1); PlayButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int PlayStopButtonState = (int) PlayButton.getTag(); if (PlayStopButtonState == 1) { mVideoAudioCallbacks.onClick(100 + getAdapterPosition()); PlayButton.setImageResource(R.drawable.playstop); PlayButton.setTag(2); } else { mVideoAudioCallbacks.onClick(200 + getAdapterPosition()); PlayButton.setImageResource(R.drawable.playarrow); PlayButton.setTag(1); } } }); and this is the method in the main activity where I handle the case of two songs playing:
public void PlaySong (int SongNumber, int ObjectInt){ if (mp == null) { mp = new MediaPlayer(); }else{ mp.reset(); } try { mp.setDataSource(this, Uri.parse("android.resource://com.example.nick.accountable/" + SongArray[SongNumber])); } catch (IOException e) { e.printStackTrace(); } try { mp.prepare(); } catch (IOException e) { e.printStackTrace(); } mp.start(); } So my question can I add some code in the view holder or in the main activity that can change all the other views than the current adapter position. I.e. If song number 3 is clicked to play, set the image for position 1-2 & 4-10 as not playing or is there a better way to do it.
Thanks for your help Nicholas
-24025641 0 Passing array from system verilog to VHDLI have a code in VHDL which requires an array of elements as generic. COEF_LIST : coef :=(0,0,1,1,2,-2,1,-2,1)
How do I send new set of COEF_LIST from my system verilog testbench to VHDL entity?
Generic in VHDL is same as parameter in verilog.
I declared coef as
parameter real COEFF[8:0] = '{0,0,1,1,2,-2,1,-2,1}; in system verilog.
I tried passing using (in my verilog testbench)
vhdl_entity #( .COEF_LIST(COEFF) ) I get the following error
**.COEF_LIST(COEFF) | ncelab: *E,CFIGTC (./vhdl_entity_tb.vams,41|36): VHDL generic vhdl_entity.COEF_LIST (../views/rtl/vhdl_entity.vhd: line 34, position 14) type is not compatible with Verilog. irun: E,ELBERR: Error during elaboration (status 1), exiting.*
This doesn't work. How do I make it compatible with VHDL? I am using incisiv 13.20.008 version
Could anyone please suggest what to do?
-34807138 0Avoid exit; / function exit; or die; will terminate execution, its better practice in only debugging your code.
Try like below.
public function index(){ if($xx) return TRUE; }
-20504851 0 Using xcodebuild with an iOS Project and the iOS Simulator This question is related, but does not resolve the specific issue I am having.
I am using Xcode 4.6.3 under OS X 10.7.5.
I simply created the default project for a single view iOS app and made no changes to the project settings. The project, of course, builds in Xcode for the iOS Simulator. However, when I try to use xcodebuild from the command line, xcodebuild fails.
The project name is just: temp
I tried:
xcodebuild -scheme temp -sdk iphonesimulator6.1 and that produced the results:
Build settings from command line: SDKROOT = iphonesimulator6.1 === BUILD NATIVE TARGET temp OF PROJECT temp WITH CONFIGURATION Debug === Check dependencies No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active arch=x86_64, VALID_ARCHS=i386). ** BUILD FAILED ** The following build commands failed: Check dependencies (1 failure) Based on the other SO question, I tried:
xcodebuild ARCHS="armv7 armv7s" ONLY_ACTIVE_ARCH=NO -scheme temp -sdk iphonesimulator6.1 and got similar results:
Build settings from command line: ARCHS = armv7 armv7s ONLY_ACTIVE_ARCH = NO SDKROOT = iphonesimulator6.1 === BUILD NATIVE TARGET temp OF PROJECT temp WITH CONFIGURATION Debug === Check dependencies No architectures to compile for (ARCHS=armv7 armv7s, VALID_ARCHS=i386). ** BUILD FAILED ** The following build commands failed: Check dependencies (1 failure) What xcodebuild command do I need to execute to be able to build with xcodebuild?
Thank you.
-2896608 0You would have to some how invoke a compiler (such as Suns javac), parse its output in case of errors and load the resulting classes dynamically.
There is no API-classes in the Java runtime library that will parse, compile and run Java source code.
-40414985 0 resque worker stops automatically on aws ec2My application is hosted on AWS ec2. I am using resque worker for background jobs. I am starting the worker using this command bundle exec rake resque:work QUEUE='*' this does start the worker but after sometime it automatically stops, and i have login into session and start again.
I have developed SPA using Knockout. I use Visual studio 2012 for development. My application connects to WCF services and displays the data. I make changes to my application and deploy on test server. When i type url and load application, it shows the old contents on the web page. I have to press ctrl+ F5 to get the latest changes. Why is it so and what is the way to avoid it? Cant we just press F5 and get the latest changes? Please let me know what other information you need.
-22051730 0 Not sure why I keep getting 404 error with Ruby Rest ClientI'm using the following code:
RestClient.get "https://myurl.com/apps/v1/company/apps/appname/device/#{device_uuid}", :params => {:client_id => client_id, :client_secret => client_secret} do |response, request, result, &block| if [404].include? response.code puts 'ERROR' + response.body else response.return!(request, result, &block) end end I am trying to use client_id and client_secret as query string parameters, and I know that when I manually do a get on this url in my browser that it is valid - however when I try to use this rest client get request, I only seem to be getting a 404 resource not found back.
The end result I am trying to do is to get the JSON back from this get request as well - it may need to be a separate question but I am also having issues with getting the JSON contents from the response body.
Thank you for any help
-23057306 0Here's a simple hide/show sidebar script for you to get the idea:
<div id="sidebar" style="height:600px; width:100px; right:-75px; position:absolute; background-color:black;"> //sidebar styling </div> <script> $('#sidebar').hover(function() { $('#sidebar').stop().animate({'right' : '0px'}, 250); }, function() { $('#sidebar').stop().animate({'right' : '-75px'}, 350); }); Here is a working example: http://jsfiddle.net/XTDHx/
-2143252 0SVN command line errors go to stderr, not stdout, which is why you aren't able to see them. What you want to do is redirect stderr to stdout and then print_r($output) to determine the cause of the error.
exec('svn commit <stuff> 2>&1', $output, $returnStatus); if ( $returnStatus ) { print_r($output); } Sample output:
Array ( [0] => svn: Commit failed (details follow): [1] => svn: '/path/to/<stuff>' is not under version control ) This is not ideal because it mixes stderr with stdout when it would otherwise be unnecessary, but I don't know of another way to get the desired output in this case. If someone else does, please comment.
Note: The third parameter to exec(...) is the return status, not the error message, so you need to tweak your code accordingly for that as well.
If the error output after making the 2>&1 modification doesn't help solve the root cause of your problem, please post the new output here.
Edit after new information:
Did you upload this SVN working copy to your server from somewhere else? That would explain this error.
If I check out a working copy from my local repository, upload it to my remote server, and then try to commit, I get the same error.
If that's the case, you need to execute the "svn checkout" of the working copy on the server running the PHP script in order to be able to commit to it. If that server can't communicate with the repository's server, then that's a whole other problem.
-26801162 0You can express your query as:
SELECT IdPerson FROM Person p JOIN CustomFieldXPerson cfxp on cfxp.IdPerson = p.IdPerson JOIN Filter f on f.IdField = cfxp.IdField AND (f.Criteria = '=' and f.Value = cfxp.Value or f.Criteria = '<' and f.Value < cfxp.Value or f.Criteria = '<=' and f.Value <= cfxp.Value or f.Criteria = '>' and f.Value > cfxp.Value or f.Criteria = '>=' and f.Value >= cfxp.Value ) WHERE f.GroupId = X ; EDIT:
If you want to get persons that match all filters, just use group by:
SELECT IdPerson FROM Person p JOIN CustomFieldXPerson cfxp on cfxp.IdPerson = p.IdPerson LEFT JOIN Filter f on f.IdField = cfxp.IdField AND (f.Criteria = '=' and f.Value = cfxp.Value or f.Criteria = '<' and f.Value < cfxp.Value or f.Criteria = '<=' and f.Value <= cfxp.Value or f.Criteria = '>' and f.Value > cfxp.Value or f.Criteria = '>=' and f.Value >= cfxp.Value ) AND f.GroupId = X GROUP BY idPerson HAVING COUNT(f.IdField) = COUNT(*) OR COUNT(f.IdField) = 0; In other words, all the filters that match the person, in the group, match. The additional condition in the HAVING clause is in case the filter group has no filters.
The problem
This code doesn't fire when the button is clicked.
mBtnSend = (Button) findViewById(R.id.btnSend); mBtnSend.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { mTest= (EditText) findViewById(R.id.txtText); mTest.setText("hello"); } }); The previous code is inside:
@Override public void onCreate(Bundle savedInstanceState) { In MainActivity.java after setContentView(R.layout.main);
Both variables for button and EditText are declared here:
public class MainActivity extends Activity implements IToolbarsContainer, OnTouchListener, IDownloadEventsListener { private Button mBotonEnviar; private EditText mCampoPrueba; And i have:
import android.view.View.OnClickListener; This is the complete layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context="org.cade.codigos.ui.activities.RequestData"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="Titulo" android:id="@+id/txtTitiulo" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="Nombre" android:id="@+id/lblNombre" android:layout_marginTop="40dp" android:layout_below="@+id/txtTitiulo" android:layout_alignParentRight="true" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="textPersonName" android:text="Nombre" android:ems="10" android:id="@+id/txtNombre" android:layout_below="@+id/lblNombre" android:layout_alignParentLeft="true" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="Apellido" android:id="@+id/lblApellido" android:layout_below="@+id/txtText" android:layout_alignParentLeft="true" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPersonName" android:text="Apellido" android:ems="10" android:id="@+id/txtApellido" android:layout_below="@+id/lblApellido" android:layout_alignParentLeft="true" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Send" android:id="@+id/btnSend" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" /> Long.. onCreate method for request
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); INSTANCE = this; Constants.initializeConstantsFromResources(this); Controller.getInstance().setPreferences(PreferenceManager.getDefaultSharedPreferences(this)); if (Controller.getInstance().getPreferences().getBoolean(Constants.PREFERENCES_SHOW_FULL_SCREEN, false)) { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (Controller.getInstance().getPreferences().getBoolean(Constants.PREFERENCES_GENERAL_HIDE_TITLE_BARS, true)) { requestWindowFeature(Window.FEATURE_NO_TITLE); } setProgressBarVisibility(true); //setContentView(R.layout.main); setContentView(R.layout.activity_request_data); mBotonEnviar = (Button) findViewById(R.id.btnEnviar); mBotonEnviar.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { mCampoPrueba = (EditText) findViewById(R.id.txtApellido); mCampoPrueba.setText("hola"); } }); mCircularProgress = getResources().getDrawable(R.drawable.spinner); EventController.getInstance().addDownloadListener(this); mHideToolbarsRunnable = null; mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); buildComponents(); mViewFlipper.removeAllViews(); updateSwitchTabsMethod(); updateBookmarksDatabaseSource(); registerPreferenceChangeListener(); Intent i = getIntent(); if (i.getData() != null) { // App first launch from another app. addTab(false); navigateToUrl(i.getDataString()); } else { // Normal start. int currentVersionCode = ApplicationUtils.getApplicationVersionCode(this); int savedVersionCode = PreferenceManager.getDefaultSharedPreferences(this).getInt(Constants.PREFERENCES_LAST_VERSION_CODE, -1); // If currentVersionCode and savedVersionCode are different, the application has been updated. if (currentVersionCode != savedVersionCode) { // Save current version code. Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit(); editor.putInt(Constants.PREFERENCES_LAST_VERSION_CODE, currentVersionCode); editor.commit(); // Display changelog dialog. Intent changelogIntent = new Intent(this, ChangelogActivity.class); startActivity(changelogIntent); } /* if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Constants.PREFERENCES_BROWSER_RESTORE_LAST_PAGE, false)) { if (savedInstanceState != null) { String savedUrl = savedInstanceState.getString(Constants.EXTRA_SAVED_URL); if (savedUrl != null) { addTab(false); navigateToUrl(savedUrl); lastPageRestored = true; } } }*/ boolean lastPageRestored = false; // gaf - comienzo con la pagina inicial String savedUrl = "file:///android_asset/startpage/index.html"; //String savedUrl = "http://servidor-cade.com"; //String savedUrl = "http://192.168.1.18:3636"; addTab(false); navigateToUrl(savedUrl); lastPageRestored = false; //if (!lastPageRestored) { // addTab(true); //} } initializeWebIconDatabase(); startToolbarsHideRunnable(); }
-29398451 0 The general strategy here is that you want to maintain a context as you traverse the list, and at each step, you use that piece of context to answer the question of whether the current item should be kept or thrown out. In pseudo-code:
public static <A> List<A> removeDuplicates(List<? extends A> original) { List<A> result = new ArrayList<A>(); /* initialize context */ for (A item : original) { if ( /* context says item is not a duplicate */ ) { result.add(item); } /* update context to incorporate the current `item` */ } return result; } Some people have brought up the question of whether you mean consecutive duplicates or non-consecutive ones. In reality, the difference in the solutions is small:
Set<A> of all items seen up to that point.I'll let you fill in the pattern for those cases.
-13084293 0The problem is that facebook like will extract meta info but I don't know how to assign the meta with ajax.
I tried use append to head int FB.init but it seems not work.
Of course this does not work, because Facebook’s scraper requests your URLs from your server – and does not care about what the DOM might currently look like in any user’s browser.
You can not add Open Graph meta data client-side.
-41014111 0First: bare variables are not supported since Ansible 2.2
Second: files is a list in your example
- debug: msg="{{ item.files[0].path }}" with_items: "{{ foundFiles.results }}" If you have multiple entries under in files list, you should consider to map it.
If i had a list of list of integers say:
[['12' '-4' '66' '0'], ['23' '4' '-5' '0'], ['23' '77' '89' '-1' '0']]
I wanted to convert the numbers to their absolute values and then to a single number, so the output would be:
-16141778 0 c# Many Unmanaged Memory in WinForm Application1246602345023778910
I've a c# winform application. Now after startup when the mainscreen is shown, I've a huge amount of unmanaged memory about 110MB, the whole managed ram is about 20 MB.
Here some things that could be uncommon:
When I load all assemblies with Assembly.Load in a console app they only cost 1 MB of unmanaged ram.
Where can this unmanaged memory come from ? Can someone give me a hint on what kind of elements could be involved?
-26027594 0You do the math before you read the input. You need to do it the other way around.
Also, there's no reason to pass a meaningless and uninitialized value to the celsius function.
Lastly, 180/100 is 1 remainder 80 because when you divide two integers, you get integer division. You can use 180.0/100.0.
Basically, you need to learn C.
-8650087 0Unicode character U+25BC is a solid triangle pointing down: ▼. You can also finagle html block elements to look like triangles by giving them a width and height of zero and applying special border properties to three of the element's sides. This technique is known as the CSS triangle hack.
Instead of using MODIFY, use a field symbol:
DATA: lt_materials TYPE TABLE OF zzllog. FIELD-SYMBOLS: <ls_line> TYPE zzllog. * other code with strange comments :-) LOOP AT lt_materials ASSIGNING <ls_line> WHERE matnr IS INITIAL. SELECT SINGLE MATNR FROM zlldet INTO <ls_line>-matnr WHERE palet = <ls_line>-palet. ENDLOOP. This is just an example for the correct syntax. It's not a good idea to do this in a real program because there's a fair chance thtat you'll be hitting the database with thousands of requests, and potentially draw quite a bit of performance. It'd be better to preselect the PALET numbers that have no MATNR into a separate table and then use FOR ALL ENTRIES IN to read all the MATNRs in a single query.
EDIT: Added type names. BTW, your way of declaring the internal table is somewhat outdated...
-40353985 0Ok i got it ! try this
angular.module('myApp', []) .controller('myController', function($scope, $interval) { var count = 0; var addPerson = function() { count++ $scope.person = { name: 'person' + count, age: 20 + count }; }; var timer = $interval(addPerson, 1000); }) .directive('myDirective', function($compile) { return { restrict: "A", transclude: true, scope: "=", link: function(scope, element, attrs) { scope.handleClick = function(event) { console.log(event.target.innerText) } scope.$watch(function() { return scope.person; }, function(obj) { var elementToRender = angular.element('<div ng-click="handleClick($event)">' + obj.name + '</div>'); function renderDiv() { return elementToRender } element.append(renderDiv()); $compile(elementToRender)(scope); }, false); } }; }); template
<div ng-app="myApp" ng-controller="myController"> <div my-directive data="{{person}}"></div> </div>
-11119158 0 custom font wingding is not working in my application EveryBody i am trying to use custom font such as wingding in my ios application i have followed all those steps for adding custom font like adding the custom font file in my application resource and added the key fontsprovidedbytheapplication in plist and make it as array and below i have mentioned my custom font file name but, still those(wingding) are not working .when i try with other custom fonts they are working properly.
This is the code i have used so offer
- (void)viewDidLoad { mine = [[UILabel alloc] initWithFrame:CGRectMake(10, 30, 240, 40)]; [mine setFont:[UIFont fontWithName:@"wingding" size:20]]; [mine setText:@"Where i am doing wrong"]; [self.view addSubview:mine]; [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } where i am missing ant suggestion will be a great help.
-26547595 0ngModel does not create a new isolated scope for itself so it can $watch without having to hardcode a $parent in it's internal code. But then you add another directive on the same DOM node that creates an isolated scope for itself. Couple this with the fact that you can only have a single isolated scope on a DOM node and you basically force ngModel to use/work with the same scope cmPopover created.
So when writing ng-model="currentEditItem.strFirstName" you are actually addressing the $scope inside the cmPopover directive, no the one in the (parent) controller. You can check this is the case by using ng-model="$parent.currentEditItem.strFirstName" - and it will work.
There's quite a lengthy conversation here with a lot of possible workarounds and solutions that leads to an actual fix in release 1.2.0.
So long story short: update to at least AngularJS 1.2.0 and this will work.
-33950310 0You have missed name in select and input:
<select id="tdarea" name="tdarea"> <option value="a" selected="selected">Area A</option> <option value="b">Area B</option> <option value="c">Area C</option> </select> <input required type="text" id="name" name="name"/>
-9253991 0 how to pass dynamic theme from swf to swc? I have one swf file which takes theme from network during runtime. Now I conerted that swf to swc, and created another container swf to point to that swc. Seems the new swf file has the theme information, which the swc does not take the theme.
How do I enable swc to take the same theme as its parent container swf file?
Thanks.
-40736909 0I do have created a subclass of UITextField, it is easy to implement and use. Here is the GitHub link:
Visit https://github.com/subhajitregor/SHPickerFieldExample
Please see the example to see how to use. The Readme file is also updated now.
-11500055 0 How can we implement drag and drop feature in html5Hello everyone please suggest me how to implement drag and drop feature inside CANVAS of html5 using kineticJS it drag and dropped object should be able to display the id of the object.
-18380923 0I'm quite new on that and I don't know if I am understanding your question, but why you don't use "backticks" instead of "system"? It would let you store the output in a variable and then you can do with this variable whatever you want.
About backticks: What's the difference between Perl's backticks, system, and exec?
-34678213 0It can also be caused by this bug, if you're having Eclipse 4.5/4.6, an Eclipse Xtext plugin version older than v2.9.0, and a particular workspace configuration.
The workaround would be to create a new workspace and import the existing projects.
-2893587 0I set up objects to handle my downloads (and other asynchronous or long running tasks) in the AppDelegate, then trigger them as required from various controllers. That way they are owned and have persistence through the life of the application.
The best way to do this is to pass them to the viewControllers that will need them (rather than the viewController "expecting" the appDelegate to have such and such an object ready and waiting) - dependency injection.
These objects update my model in some way when they finish and if I need to, I use NSNotifications to announce they are done. This isolates me from the mess I used to get into trying to cancel or swap delegates in viewWillDisappear etc to avoid the kind of issues you are running into.
-25640956 0 tooltip inside popover stays after popover is closed - ZeroClipboardI'm trying to add buttons to popover that will allow user to copy content.
I managed to build prototype: http://jsfiddle.net/Misiu/VUZhL/890/ but I have weird error when using tipsy inside popover:

After clicking on Click for action button I get popover with 2 buttons, they both have tooltips, sometimes after clicking on button tooltip stays visible.
My code:
$(function () { $('#example').tipsy({ title: 'data-tipsy-title', gravity: function () { return this.getAttribute('data-tipsy-gravity') || 'n'; } }); $(document).on('click', '#example, .tip', function (event) { $(this).tipsy("hide"); }); $('#example').popover({ placement: 'top', title: '', html: true, template: '<div class="popover" role="tooltip"><div class="arrow"></div><div class="popover-content no-padding"></div></div>', content: '<div class="btn-group">' + '<button type="button" title="link" class="btn btn-default tip number"><span class="fa fa-link"></span></button>' + '<button type="button" class="btn btn-default tip" title="something else"><span class="fa fa-copy"></span></button>' + '</div>' }); $('#example').on('shown.bs.popover', function () { //tipsy $('.tip').tipsy({ gravity: 's' }); //zero clipboard var clip = new ZeroClipboard($(".tip")); clip.on("copy", function (event) { var clipboard = event.clipboardData; var data = ""; if ($(event.target).hasClass("number")) { data = "1st button"+new Date() } else { data = "second"; } clipboard.setData("text/plain", data); ZeroClipboard.deactivate(); }); }) //zero clipboard ZeroClipboard.config({ hoverClass: "hover" }); }); My questions:
1. How can this be fixed?
2. Is ZeroClipboard initialized in right place? I can't do that before, because buttons are added when popover is shown for first time.
I'm drawing a map of a real world floor with dimensions roughly 100,000mm x 200,000mm.
My initial code contained a function that converted any millimeter based position to screen positioning using the window size of my pygame map, but after digging through some of the pygame functions, I realized that the pygame transformation functions are quite powerful.
Instead, I'd like to create a surface that is 1:1 scale of real world and then scale it right before i blit it to the screen.
Is this the right way to be doing this? I get an error that says Width or Height too large. Is this a limit of pygame?
-36543115 0//Your example json results = [{"type":"fruit", "name":"orange"},{"type":"flower","name":"rose"},{"type":"fruit", "name":"apple"}] First you need to turn your json into an array of dictionaries to get the above object you think it will be:
if let results = try NSJSONSerialization.JSONObjectWithData(data,options: NSJSONReadingOptions.MutableContainers) as? [[String : AnyObject]] { //parse into form you want.} // Your example desired result of dictionary with key:array of dictionaries updatedResult[String:[AnyObject]]() = {"fruit":[{"name":"orange"},{"name":"apple"}],"flower":[{"name":"rose"}]} Then you want to loop through the json result and grab out the values into the above format you want:
// Swift representation of your provided example let results = [["type":"fruit", "name":"orange"],["type":"flower","name":"rose"],["type":"fruit", "name":"apple"]] // Desired dictionary of key:array of dictionaries var updatedResult = [String:[[String:String]]]() for item in results { if let name = item["name"], type = item["type"] { if updatedResult.keys.contains(type) { updatedResult[type]!.append(["name":name]) } else { updatedResult[type] = [["name":name]] } } }
-585538 0 Multiple inheritance can be used if the language allows it. I don't know much about it however.
Otherwise, you can build a StockItemNode : GraphicNode from a StockItem:
class ItemNodeFactory { ... StockItemNode create(StockItem); ... } You can transfer properties from StockItem into an instance of StockItemNode (set-get) which would completely decouple the two types. Or you can have StockItemNode wrap an instance of StockItem (composition).
Doing it the other way around (having NodeStockItem : StockItem and/or wrapping a GraphicNode in a StockItem) would result in a particular bad design because you don't want to hardwire a coupling to a specific presentation (GraphicNode) inside a domain/business/data entity (StockItem).
I'm trying to build a database for video spots. The main page is a list of spots and you can check them and modify them. What i want to do is build a cart system, where the checked spots' id's are automatically added to the cart and stored as a cookie. That way the use can browse multiple pages while still having everything stay checked.
So far, I have a checkbox on every spot that when checked calls a function that adds the id of the checkbox to an array and stores it as a cookie.
I'm able to retrieve the cookie through jquery. What I need to do is while looping through the spots and printing them, is to check if that spot id is in the cookie, so I can set it as checked or not through php. Is this possible? Is there a better way to accomplish this?
Here is what i have so far.
$(document).ready(function(){ var checkedItems = []; $('.spotCheck').click(function(){ var currentID = this.id; checkedItems.push(currentID); updateCookie(); }); function updateCookie(){ $.cookie('itemList',checkedItems); } $('#mainContainer').click(function(){ $('#textInCenter').html($.cookie('itemList') ); }); }); Clicking the checkbox adds the ID to the array checkedItems, and click the mainContainer makes it visible so I can see which items are currently in the array. I can browse through pages and the cookies stay in the array (there's no way to remove them now but I'm not worried about that right now).
So how can I check the array to see if an id is in there when I print the list of spots?
-23520464 0The Same Origin Policy prevents you from manipulating the content of an Iframe from an different domain. This was put in place to prevent Iframed content from hijacking your privacy.
What you want cannot be done.
-22225288 0 Performance of $rootScope.$new vs. $scope.$newMy current Controllers $scope is kind of thick with: $watch and event handlers.
On one point I need to create a new scope for a modal, which does not have its own controller, because its quite simple. Still it needs a property of the current $scope. I was wondering which of the following solutions is better, and why?
a)
var modalScope = $rootScope.$new(); modalScope.neededValue = $scope.neededValue; b)
var modalScope = $scope.$new(); // modalScope.neededValue already there Should I be worried that the created modalScope will watch also those expressions and events? Any other aspects I should be aware of?
I want to Display news and events in a html page such that automatically they are rotating but on mouseover they stop? Please give me any article link related this?
-1382932 0I prefer to keep them in a separate config file, located somewhere outside the web server's document root.
While this doesn't protect against an attacker subverting my code in such a way that it can be coerced into telling them the password, it does still have an advantage over putting the passwords directly into the code (or any other web-accessible file) in that it eliminates concern over a web server misconfiguration (or bug/exploit) allowing an attacker to download the password-containing file directly.
-28098477 0I'm sure there is a probably a clever way to do this in one line using Linq, but everything I could come up with was quite ugly so I went with something a bit more readable.
var results = items.GroupBy(x => x.TransactionType) .ToDictionary(x => x.Key, x => x.Sum(y => y.TransactionValue)); var totals = new Totals { TotalIncoming = results["Income"], TotalOutgoing = results["Outgoing"] };
-38711033 0 How to group items in array by summary each item <?php $quantity = array(1,2,3,4,5,6,7,8,9,10,11,12,1,14,2,16); // Create a new array $output_array = array(); $sum_quantity = 0; $i = 0; foreach ($quantity as $value) { if($sum_quantity >= 35) { $output_array[$i][] = $value; } $sum_quantity = $sum_quantity + $value; } print_r($output_array); When summmary each item >= 35 will auto create child array
array( [0] => array(1, 2, 3, 4, 5, 6, 7), [1] => array(8, 9, 10), [2] => array(11, 12, 1), [3] => array(14, 2, 16) )
-24641573 0 How to Install SSL certificate in Linux Servers I am trying to access https wcf web service from my application using monodevelop in Linux. The web service call is throwing the following exception
SendFailure (Error writing headers) at System.Net.HttpWebRequest.EndGetRequestStream (IAsyncResult asyncResult) [0x00043] in /home/abuild/rpmbuild/BUILD/mono-3.4.0/mcs/class/System/System.Net/HttpWebRequest.cs:845 at System.ServiceModel.Channels.HttpRequestChannel+c__AnonStorey1.<>m__0 (IAsyncResult r) [0x0001d] in /home/abuild/rpmbuild/BUILD/mono-3.4.0/mcs/class/System.ServiceModel/System.ServiceModel.Channels/HttpRequestChannel.cs:219.
when I try to load the web service url using https, the Firefox browser is giving a warning:
"This connection is Untrusted"
The certificate(.cer) is generated using Visual Studio 2008 makecert utility.I tried to install certificate using the below commands
But it looks like the certificates are not configured properly. In some of the forums it saying that move the certificate to /etc/httpd/conf . But there is no such folder in my system
Please let me know what I am missing?
-17066573 0Are you plotting one point at a time?
Can you do something like this?
plot(x_coord, y_coord, 'k.', 'markersize', 20) This provides a circle of points:
my_vector=0:0.1:2*pi; for ii = 1:length(my_vector) x = cos(ii); y = sin(ii); plot(x,y, 'k.', 'markersize', 10) hold on end
-22260913 0 Is a real-time system sdhedulable? There is a question in my operating systems book about scheduling a system.
The question is: A real-time system needs to handle two voice calls that each run every 5 msec and consumes 1 msec of CPU time per burst, plus one video at 25 frames/sec, with each frame requiring 20 msec of CPU time. Is the system schedulable?
The solution manual has this answer: Each voice call runs 200 times/second and uses up 1 msec per burst, so each voice call needs 200 msec per second or 400 msec for the two of them. The video runs 25 times a second and uses up 20 msec each time, for a total of 500 msec per second. Together they consume 900
The book does not explain how to come to this conclusion, or gives an algorithm. So I was hoping someone could explain how this answer is worked out?
Thank you.
-10160305 0For a project I did once, we used a ruby script to generate an AS file containing references to all classes in a certain package (ensuring that they were included in the compilation). It's really easy considering that flash only allows classes with the same name as the file it's in, so no parsing of actual code needed.
It would be trivial to also make that add an entry to a dictionary (or something similar), for a factory class to use later.
I believe it's possible to have a program execute before compilation (at least in flashdevelop), so it would not add any manual work.
Edit: I added a basic FlashDevelop project to demonstrate. It requires that you have ruby installed. http://dl.dropbox.com/u/340238/share/AutoGen.zip
-6699569 0If you can get it to run in a browser then something as simple as this would work
var webRequest = WebRequest.Create(@"http://webservi.se/year/getCurrentYear"); using (var response = webRequest.GetResponse()) { using (var rd = new StreamReader(response.GetResponseStream())) { var soapResult = rd.ReadToEnd(); } }
-15392859 0 I must say, NO. The compiler will produce the same IL code, so you don't have to worry about that.
-34346888 0 XML parsing "not well-formed"I received in the console a lot of not well-formed with :
language="en"; $.ajax({ url: 'translate.xml', dataType: "xml", success: function(xml) { $(xml).find('translation').each(function(){ var id = $(this).attr('id'); var text = $(this).find(language).text(); $("." + id).append(text); }); } }); My XML file "translate.xml" have this format :
<?xml version="1.0" encoding="UTF-8"?> <translations> <translation id="t_house"> <en>house</en> <fr>maison</fr> </translation> <translation id="t_boat"> <en>boat</en> <fr>bateau</fr> </translation> </translations> I don't understand where these warnings come from ?
-12748760 0To get just those records that ARE in Encounter and NOT in EnctrAPR, then just use left outer join instead of full outer join, and add a clause excluding null values for EnctrAPR.EncounterNumber.
i.e.
SELECT Encounter.EncounterNumber, substring(Encounter.EncounterNumber,4,9) as Acct, ... EnctrAPR.APRDRG, Age18, Age18To64, Age65 from Encounter left outer join EnctrAPR on substring(Encounter.EncounterNumber,4,9) = EnctrAPR.EncounterNumber where EnctrAPR.EncounterNumber is null and HSP# = 1 and InOutCode = 'I' and ActualTotalCharge >0 and AdmitSubService <> 'SIG' and [DischargeDate - CCYYMMDD] between @StartDate and @EndDate and Encounter.Age >= 18 Note though that the value for EnctrAPR.APRDRG will always be null, as EnctrAPR doesn't have a matching row.
I'm developing an Android application sending files from one device to another. Establishing the connection between both devices works perfectly, but there is something going wrong while transferring the file. On the receiving device, the file gets created but unfortunately it's empty.
This is my code for handling the incoming file:
try { byte[] buffer = new byte[1024]; int bytes = 0; boolean eof = false; File file = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), "test.jpg"); OutputStream os = null; try { os = new BufferedOutputStream(new FileOutputStream(file)); } catch (FileNotFoundException e) { e.printStackTrace(); } while (!eof) { bytes = mmInStream.read(buffer); int offset = bytes - 11; byte[] eofByte = new byte[11]; eofByte = Arrays.copyOfRange(buffer, offset, bytes); String message = new String(eofByte, 0, 11); if(message.equals("end of file")) { os.flush(); os.close(); eof = true; } else { os.write (buffer); } } } catch (IOException e) { e.printStackTrace(); }
-21701309 0 Improve your question , but see below answer for your question
NSString *string = @"This is the main stringsss which needs to be searched for some text the texts can be any big. let us see"; if ([string rangeOfString:@"."].location == NSNotFound) { NSLog(@"string does not contains"); } else { NSLog(@"string contains !"); }
-38776050 1 Regex to strip only start of string I am trying to match phone number using regex by stripping unwanted prefixes like 0, *, # and +
e.g.
+*#+0#01231340010 should produce,
1231340010 I am using python re module
I tried following,
re.sub(r'[0*#+]', '', '+*#+0#01231340010') but it is removing later 0s too.
I tried to use regex groups, but still it's not working ( or I am doing something wrong for sure ).
Any help will be appreciated.
Thanks in advance.
-19396021 0 How to get number FDs occupied by a processes without using losf?I am trying to get number of FDs occupied by my processes , i tried with lsof , unfortunately it is taking too much of time . If there any other way to get this number , i also tried looking at /proc//fd , but didn't find what i am looking for.
-14520237 0 Does declaring an unnecessary variable in PHP consumes memory?I usually do this in PHP for better readability but I don't know if it consumes memory or has any other issues? Let's say I have this code:
$user = getUser(); // getUser() will return an array I could do:
$email = $user["email"]; sendEmail($email); Without declaring the variable $email I could do:
sendEmail($user["email"]); Which one is better? Consider that this is just a very simple example.
-13156208 0 jqGrid multiplesearch - How do I add and/or column for each row?I have a jqGrid multiple search dialog as below:
(Note the first empty td in each row).

What I want is a search grid like this (below), where:

The empty td is there by default, so I assume that this is a standard jqGrid feature that I can turn on, but I can't seem to find it in the docs.
My code looks like this:
<script type="text/javascript"> $(document).ready(function () { var lastSel; var pageSize = 10; // the initial pageSize $("#grid").jqGrid({ url: '/Ajax/GetJqGridActivities', editurl: '/Ajax/UpdateJqGridActivities', datatype: "json", colNames: [ 'Id', 'Description', 'Progress', 'Actual Start', 'Actual End', 'Status', 'Scheduled Start', 'Scheduled End' ], colModel: [ { name: 'Id', index: 'Id', searchoptions: { sopt: ['eq', 'ne']} }, { name: 'Description', index: 'Description', searchoptions: { sopt: ['eq', 'ne']} }, { name: 'Progress', index: 'Progress', editable: true, searchoptions: { sopt: ['eq', 'ne', "gt", "ge", "lt", "le"]} }, { name: 'ActualStart', index: 'ActualStart', editable: true, searchoptions: { sopt: ['eq', 'ne', "gt", "ge", "lt", "le"]} }, { name: 'ActualEnd', index: 'ActualEnd', editable: true, searchoptions: { sopt: ['eq', 'ne', "gt", "ge", "lt", "le"]} }, { name: 'Status', index: 'Status.Name', editable: true, searchoptions: { sopt: ['eq', 'ne']} }, { name: 'ScheduledStart', index: 'ScheduledStart', searchoptions: { sopt: ['eq', 'ne', "gt", "ge", "lt", "le"]} }, { name: 'ScheduledEnd', index: 'ScheduledEnd', searchoptions: { sopt: ['eq', 'ne', "gt", "ge", "lt", "le"]} } ], jsonReader: { root: 'rows', id: 'Id', repeatitems: false }, rowNum: pageSize, // this is the pageSize rowList: [pageSize, 50, 100], pager: '#pager', sortname: 'Id', autowidth: true, shrinkToFit: false, viewrecords: true, sortorder: "desc", caption: "JSON Example", onSelectRow: function (id) { if (id && id !== lastSel) { $('#grid').jqGrid('restoreRow', lastSel); $('#grid').jqGrid('editRow', id, true); lastSel = id; } } }); // change the options (called via searchoptions) var updateGroupOpText = function ($form) { $('select.opsel option[value="AND"]', $form[0]).text('and'); $('select.opsel option[value="OR"]', $form[0]).text('or'); $('select.opsel', $form[0]).trigger('change'); }; // $(window).bind('resize', function() { // ("#grid").setGridWidth($(window).width()); //}).trigger('resize'); // paging bar settings (inc. buttons) // and advanced search $("#grid").jqGrid('navGrid', '#pager', { edit: true, add: false, del: false }, // buttons {}, // edit option - these are ordered params! {}, // add options {}, // del options {closeOnEscape: true, multipleSearch: true, closeAfterSearch: true, onInitializeSearch: updateGroupOpText, afterRedraw: updateGroupOpText}, // search options {} ); // TODO: work out how to use global $.ajaxSetup instead $('#grid').ajaxError(function (e, jqxhr, settings, exception) { var str = "Ajax Error!\n\n"; if (jqxhr.status === 0) { str += 'Not connect.\n Verify Network.'; } else if (jqxhr.status == 404) { str += 'Requested page not found. [404]'; } else if (jqxhr.status == 500) { str += 'Internal Server Error [500].'; } else if (exception === 'parsererror') { str += 'Requested JSON parse failed.'; } else if (exception === 'timeout') { str += 'Time out error.'; } else if (exception === 'abort') { str += 'Ajax request aborted.'; } else { str += 'Uncaught Error.\n' + jqxhr.responseText; } alert(str); }); $("#grid").jqGrid('bindKeys'); $("#grid").jqGrid('inlineNav', "#grid"); }); </script> <table id="grid"/> <div id="pager"/>
-7840894 0 Q_MONKEY_EXPORT is most likely a #define somewhere. Defines like that are sometimes required, for example when the class is in a library and needs to be exported when the header file is included from somewhere else. In that case, the define resolves to something like __declspec(dllexport) (the exact syntax will depend on the tools you are using).
It seems better to use HashMap's boolean containsKey(Object key) method instead of the direct invocation of equalsIgnore..() in main(). If necessary, you may create your own class implement interface Map, and make it a delegator of its HashMap-typed field for customized management of key comparisons.(You may override equals() and hashCode() for keys. Item 8 and Item 9 in Effective Java 2nd ed. by Josh Bloch will give you detailed guide.)
-19527990 0Try this. I am sure you can do this via a couple JOINs (or at least part of it) but you did not request what your return columns should be
SELECT v.visitID FROM Visits AS v WHERE EXISTS(SELECT * FROM VisitDocs AS d WHERE d.VisitID = v.VisitID AND d.docType = 3) AND NOT EXISTS(SELECT * FROM VisitDocs AS d WHERE d.VisitID = v.VisitID AND d.docType Not IN (1,2))
-34602213 0 iOS Facebook Authentication PhoneGap on TestFlight I'm currently testing my app on my iPhone that I built using Phonegap's Adobe Build with Apple's TestFlight application. My app contains Facebook authentication and when I click the authentication button I am presented with the following error:
Given URL is not allowed by the Application configuration: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains.
I did a bit of research online and I added the iOS Platform along with my Bundle ID in the respective field on facebook's developer panel but that did not appear to fix things.
-31712185 0 How to get correct summaries with analytics?I want to get summary numbers from the cust_detail table if a specific invoice_code appears in invoice_detail.
In this example, I'd like to report cust_detail summaries only for batches 10 and 20 because they are the ones with invoice_code='9999'. But the duplication in the invoice_detail table is skewing my numbers.
with invoice_detail as ( select '10' as invoice_batch, '9999' as invoice_code from dual union all select '10' as invoice_batch, '9999' as invoice_code from dual union all select '20' as invoice_batch, '1111' as invoice_code from dual union all select '30' as invoice_batch, '9999' as invoice_code from dual ), cust_detail as ( select '1' as cust_id, '10' as invoice_batch, 40 as points_paid, 30 as points_earned, 30 as points_delivered from dual union all select '1' as cust_id, '20' as invoice_batch, 10 as points_paid, 10 as points_earned, 10 as points_delivered from dual union all select '1' as cust_id, '30' as invoice_batch, 20 as points_paid, 15 as points_earned, 5 as points_delivered from dual ) select cust_id, sum(points_paid) over (partition by c.invoice_batch order by cust_id) batch_total from cust_detail c inner join invoice_detail i on c.invoice_batch=i.invoice_batch where i.invoice_code = '9999'; Desired results:
CUST_ID PAID EARNED DELIVERED TOT_PAID TOT_EARNED TOT_DELIVERED --------- ------ -------- ----------- ---------- ------------ --------------- 1 40 30 30 60 45 40 1 20 15 5 60 45 40
-20995086 0 I've finally found a workaround.
In netbeans, I've set the background property of the button to some value (different from the one I want, but different from the default 240,240,240 too).
When I run the applet, now I always get what I expect, that is the color set in the code with Nimbus.
-34784338 0You can use include_once or include at your index.php
Try this code for index.php :
<?php global $v_username; $v_username="demo"; $v_value="asd"; include_once('function.php') ?> <th><a href="" onclick= <?php setting_my_first_cookie(); ?> >Set Cookie</a></th>
-33903463 0 Problem is presence of ! in your character class that is doing history expansion.
I suggest declaring your regex beforehand like this:
re="^[0-9][0-9a-zA-Z\!#$%^&/*'+-]+$" Then use it as:
s='1/' [[ $s =~ $re ]] && echo "good" || echo "bad" good
-36782266 0 I found the solution: Because I was using a auto generated pom.xml, I added the maven-s3-wagon extension to publish the library to a Maven repo on a AWS S3 server. So, the pom.xml file had other plugins for Maven. I think that mvn was calling both processes: the regular Maven deployment and the Maven S3 Wagon, and that would be the reason why the deployment process was doing an "extra step" and generating two names: artifact-id-xxxx.142230-1 and artifact-id-xxxx.142243-2
I removed all the plugins into <build> section and leave only the maven-s3-wagon extension. It worked like a charm.
<build> <extensions> <extension> <groupId>org.kuali.maven.wagons</groupId> <artifactId>maven-s3-wagon</artifactId> <version>1.2.1</version> </extension> </extensions> </build>
-5079540 0 VB.Net - Cannot create field "password" in Access 'Create field in table Public Sub createField(ByVal tableName As String, ByVal fieldName As String, ByVal fieldType As String) If Not isConnected() Then XGUI.consolePrint("XAccessDatabase.createField() Warning - Database not connected. Create field canceled") Exit Function End If Dim myOleDbCommand As OleDbCommand myOleDbCommand = New OleDbCommand("ALTER TABLE " & tableName & " ADD COLUMN " & fieldName & " " & fieldType, connection) myOleDbCommand.ExecuteNonQuery() End Function createField("users", "password", "TEXT(60)") 'Password I get: Syntax error in field definition, when I try to create "password" field. In all other cases (other field names) it works fine.
When trying to create it manually with MS-Access, I have no problem either. What is going on???
-15215355 0 Consistently subset matrix to a vector and avoid colnames?I would like to know if there is R syntax to extract a column from a matrix and always have no name attribute on the returned vector (I wish to rely on this behaviour).
My problem is the following inconsistency:
myMatrix[, 1] I will get the first column of myMatrix with no name attribute. This is what I want.myMatrix[, 1], I will get the first column of myMatrix but it has the first colname as its name.I would like to be able to do myMatrix[, 1] and consistently get something with no name.
An example to demonstrate this:
# make a matrix with more than one row, x <- matrix(1:2, nrow=2) colnames(x) <- 'foo' # foo # [1,] 1 # [2,] 2 # extract first column. Note no 'foo' name is attached. x[, 1] # [1] 1 2 # now suppose x has just one row (and is a matrix) x <- x[1, , drop=F] # extract first column x[, 1] # foo # <-- we keep the name!! # 1 Now, the documentation for [ (?'[') mentions this behaviour, so it's not a bug or anything (although, why?! why this inconsistency?!):
A vector obtained by matrix indexing will be unnamed unless ‘x’ is one-dimensional when the row names (if any) will be indexed to provide names for the result.
My question is, is there a way to do x[, 1] such that the result is always unnamed, where x is a matrix?
Is my only hope unname(x[, 1]) or is there something analogous to ['s drop argument? Or is there an option I can set to say "always unname"? Some trick I can use (somehow override ['s behaviour when the extracted result is a vector?)
There are a number of ways to archive this. One easy way is to submit all data to the server, where the whole form gets rebuild. Doing this on javascript-side could be done with templating (I assume you use jquery).
The serverside-solution (as the final submitting) requires, that your input-names are formed wisly.
Example:
data[members][{$memberId}][name] If you want to determine, if the form was submitted in its final form, or just to add a member, you can form the submit-buttons like this:
<input type="submit" name="btn[submit]" value="submit booking" /> <input type="submit" name="btn[add]" value="submit booking" /> On php-side this could be determined by:
$btnType = isset($_REQUEST['btn']) && is_array($_REQUEST['btn']) ? array_shift(array_keys($_REQUEST['btn'])) : 'submit'; There are still improvements to apply!
-31565847 0 Multiplying one matrix with a set of scalarsI have an R script that systematically perform changes to a 3x3 matrix by scalar multiplication as follows
R <- matrix(rexp(9, rate=.1), ncol=3); for (i in 1:360) { K = i*R; ... } and use the modified matrix for further calculations within the loop. However, the loop itself is nested inside two other for loops, making the script very slow. So my question is, how can I vectorize this innermost loop such that the result instead is a three-dimensional array A of size 3x3x360 where
A[,,i] = i*R; for all i ranging from 1 to 360?
-35581815 0 Select rows from data frame which have at least three negative values?How to filter rows which have atleast 3 negative values?
df1 <- Name flex flex2 flex3 flex4 Set1 -1.19045139 -1.25005615 -1.053900875 -1.15142391 Set2 -2.22129212 1.54901305 0.003462145 1.06170243 Set3 -2.08952248 -1.95241584 -1.206060696 -1.65450460 Set4 -1.20091116 0.50700470 -0.098793884 1.50406054 Set5 -1.11771409 0.01175919 -3.056481406 -1.09328262 Set7 -9.01648659 0.07707638 0.198978232 1.18125182 expected output
df2 <- Name flex flex2 flex3 flex4 Set1 -1.19045139 -1.25005615 -1.053900875 -1.15142391 Set3 -2.08952248 -1.95241584 -1.206060696 -1.65450460 Set5 -1.11771409 0.01175919 -3.056481406 -1.09328262 i tried the code given below, but it doesn't work
Index= as.vector(which(apply(df1,1,function(x){sum(x < -1)/length(x)})>=0.75)) df1[Index,]
-2051728 0 I solved a similar issue with
Invoke-Expression '&.\myProg.exe `-u:IMP `-p: `-s:"my path with spaces"' Hope this helps.
-40849009 0 Not serializable class with strings onlyI have a class called Libro which contains strings only:
public class Libro { private String titolo; private String autore; private String editore; private String sottotitolo; private String genere; private String dpubb; private String lpubb; private String soggetto; private String isbn; private String note; private String prezzo; private String npag; //getters, setters, constructors... } Then I created an object called a belonging to the Libro class, and I tried to write it to a coso.dat file
try{ ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("C:\\Users\\Workbench\\Documents\\NetBeansProjects\\coso.dat")); out.writeObject(a); out.close(); }catch(Exception e) {System.out.println("Damn");} Then I opened the file with NotePad and it seems that I tried to serialize an unserializable class:
¬í {sr java.io.NotSerializableException(Vx ç†5 xr java.io.ObjectStreamExceptiondÃäk9ûß xr java.io.IOExceptionl€sde%ð« xr java.lang.ExceptionÐý>;Ä xr java.lang.ThrowableÕÆ5'9w¸Ë L causet Ljava/lang/Throwable;L detailMessaget Ljava/lang/String;[ stackTracet [Ljava/lang/StackTraceElement;L suppressedExceptionst Ljava/util/List;xpq ~ t ginobook.classi.Librour [Ljava.lang.StackTraceElement;F*<<ý"9 xp )sr java.lang.StackTraceElementa Åš&6Ý… I lineNumberL declaringClassq ~ L fileNameq ~ L methodNameq ~ xp t java.io.ObjectOutputStreamt ObjectOutputStream.javat writeObject0sq ~ \q ~ q ~ t writeObjectsq ~ ôt ginobook.forms.FormNuovot FormNuovo.javat btnCreaActionPerformedsq ~ q ~ q ~ t access$1500sq ~ Œt ginobook.forms.FormNuovo$15q ~ t actionPerformedsq ~ æt javax.swing.AbstractButtont AbstractButton.javat fireActionPerformedsq ~ ,t "javax.swing.AbstractButton$Handlerq ~ q ~ sq ~ ’t javax.swing.DefaultButtonModelt DefaultButtonModel.javaq ~ sq ~ q ~ $q ~ %t setPressedsq ~ üt *javax.swing.plaf.basic.BasicButtonListenert BasicButtonListener.javat mouseReleasedsq ~ …t java.awt.Componentt Component.javat processMouseEventsq ~ üt javax.swing.JComponentt JComponent.javaq ~ /sq ~ šq ~ -q ~ .t processEventsq ~ ¼t java.awt.Containert Container.javaq ~ 4sq ~ q ~ -q ~ .t dispatchEventImplsq ~ öq ~ 6q ~ 7q ~ 9sq ~ gq ~ -q ~ .t dispatchEventsq ~ t java.awt.LightweightDispatcherq ~ 7t retargetMouseEventsq ~ q ~ >q ~ 7q ~ /sq ~ rq ~ >q ~ 7q ~ <sq ~ èq ~ 6q ~ 7q ~ 9sq ~ ºt java.awt.Windowt Window.javaq ~ 9sq ~ gq ~ -q ~ .q ~ <sq ~ öt java.awt.EventQueuet EventQueue.javaq ~ 9sq ~ aq ~ Hq ~ It access$500sq ~ Åt java.awt.EventQueue$3q ~ It runsq ~ ¿q ~ Mq ~ Iq ~ Nsq ~ ÿÿÿþt java.security.AccessControllert AccessController.javat doPrivilegedsq ~ Lt 5java.security.ProtectionDomain$JavaSecurityAccessImplt ProtectionDomain.javat doIntersectionPrivilegesq ~ Vq ~ Uq ~ Vq ~ Wsq ~ Ût java.awt.EventQueue$4q ~ Iq ~ Nsq ~ Ùq ~ Zq ~ Iq ~ Nsq ~ ÿÿÿþq ~ Qq ~ Rq ~ Ssq ~ Lq ~ Uq ~ Vq ~ Wsq ~ Øq ~ Hq ~ Iq ~ <sq ~ Ét java.awt.EventDispatchThreadt EventDispatchThread.javat pumpOneEventForFilterssq ~ tq ~ `q ~ at pumpEventsForFiltersq ~ iq ~ `q ~ at pumpEventsForHierarchysq ~ eq ~ `q ~ at pumpEventssq ~ ]q ~ `q ~ aq ~ hsq ~ Rq ~ `q ~ aq ~ Nsr &java.util.Collections$UnmodifiableListü%1µìŽ L listq ~ xr ,java.util.Collections$UnmodifiableCollectionB €Ë^÷ L ct Ljava/util/Collection;xpsr java.util.ArrayListxÒ™Ça I sizexp w xq ~ px What did I do wrong..? I'm sorry if the question may seem stupid, but I just couldn't find any answer to it
-17917761 0Set the field not only to hidden as also to disabled, that will solve this. Or as mentioned in the comment if you just use a custom validation return true.
Since OS X 10.10, NSStatusItem has button property, which is a regular NSView-based control that conforms to NSAccessibility protocol and which allows to change accessibilityTitle property directly.
On earlier versions of OS X, you can implement a custom button that looks and behaves exactly like vanilla NSStatusItem and assign it to the item via -[NSStatusItem setView:] method, then use -[NSView accessibilitySetOverrideValue:... forAttribute:NSAccessibilityTitleAttribute] on your custom control to provide a voiceover title.
I have my home.html.haml page rendering 3 partials:
%h1 Foo #foo1 = render partial: 'foo/foo', locals: {items: @foo1_items} #foo2 = render partial: 'foo/foo', locals: {items: @foo2_items} #foo3 = render partial: 'foo/foo', locals: {items: @foo3_items} Currently, I have some remote links that refresh these parts individually firing an ajax call to to the home page:
= link_to 'refresh', home_path(mode: 'foo1'), remote:true = link_to 'refresh', home_path(mode: 'foo2'), remote:true = link_to 'refresh', home_path(mode: 'foo3'), remote:true and I have a home.js.erb that contains something like this:
<% if params[:mode] == 'foo1'%> $('#foo1').html('<%= j(render partial: 'foo/foo', locals: {items: @foo1_items}) %>') <% elsif params[:mode] == 'foo2'%> $('#foo2').html('<%= j(render partial: 'foo/foo', locals: {items: @foo2_items}) %>') <% else %> $('#foo3').html('<%= j(render partial: 'foo/foo', locals: {items: @foo3_items}) %>') <% end %> I am wondering:
I would say that the real reason is that try-with-resources isn't so much new JVM feature as it is a compile-time language feature. In this way, it is very much analogous to the "enhanced for statement" which requires a class that has implemented the Iterable interface (you have to name an instance of the implenting class there, too). Try-with-resources requires that the resource implements the AutoCloseable interface. It is not wrong to regard the block as "syntactic sugar, introduced in 1.7". It just prevents you from having to deal with calls to the interface method yourself.
Because the feature requires an object whose class has implemented the interface, you must give the try-with-resources block the name of that object.
-32224358 0Try using @Body annotation instead of @Field and passing a single ReviewBody object.
class ReviewBody { public Review review; public ReviewBody(int placeId, float rating, String content, List<String> tagList) { review = new Review(placeId, rating, content, tagList); } public class Review { @SerializedName("place_id") public int placeId; public float rating; public String content; @SerializedName("tag_list") public List<String> tagList; public Review(int placeId, float rating, String content, List<String> tagList) { this.placeId = placeId; this.rating = rating; this.content = content; this.tagList = tagList; } } } @POST("/") void addReview(@Body ReviewBody body, Callback<ReviewEntity> callback); (without @FormUrlEncoded)
If H:i:s is always two-digit, i.e. 14:05:15 then it will be ordered correctly.
If it can contain one-digit in any part, i.e. 14:5:15, then it will not be ordered correctly.
I found the solution here http://www.jamesnetherton.com/blog/2008/05/04/Converting-Unix-timestamp-values-in-ColdFusion/. I needed to convert the start and end time in order to use in my sql query.
-21510461 0 Image files under src root folder not present in android build (Codename ONE)It is similar to this question, however my problem is that the images are there in Codename ONE simulator (image can be loaded and shows correctly), but when I do an android build and try it on my phone, I get a java.io.FileNotFoundException. According to the comment given by Shai Almog to the question mentioned above, it should work.
What is wrong here? Could it be filenames have to be all lower case or all upper case?
(I am omitting the source here because it seems to be a problem with packaging rather than the code itself.)
UPDATE: I tried changing all filenames to lowercase but to no avail.
-15826385 0 Can we query and fetch data from LIST between different subsites using CAML Query.?Have LIST created under one site, can the same LIST be used to fetch data from other site using CAML Query.?
eg:
Consider a LIST "xxx" created under SitePages/AAA/Lists/
Can i access the LIST "xxx" from other site i.e SitePages/BBB/
To Summarize, Is it possible to access the LIST across parent and child sites, vice-versa.
Thanks in advance
-40497521 0Maybe the Path of the file is located is erroneus.
if not, try with fs.unlinkSync()
-28410479 0Here is something similar with good code example.
// Set cursor as hourglass Cursor.Current = Cursors.WaitCursor;
// Execute your time-intensive hashing code here...
// Set cursor as default arrow Cursor.Current = Cursors.Default;
How can I make the cursor turn to the wait cursor?
-34355813 0Is there any way to get a response without the target namespace?
I hope not. A SOAP web service should have a well-defined, published interface and every response that it sends should conform to that interface. Usually, the interface is described by a WSDL document.
And would like to get it without the target namespace
<MyItem> <class>myClass</class> <name>MyItemName</name> </MyItem> Being pedantic, but the absence of a namespace prefix does not mean that there is no namespace. There might be a default namespace in force. So you could achieve XML that looks exactly like the above and the MyItem, class and name tags might still have a non-empty namespace.
I know its purpose and that it's actually quite useful.
The purpose of a namespace in an XML document ( whether a web service response, or any other XML ) is to avoid polluting the global namespace. Do you really want 'name' and 'class' to have exactly one meaning in your applications? Or would it be better if each schema could define its own version of those?
But it happened that it can't be processed any further by another tool with this target namespace and looks like this:
<MyItem xmlns="http://spring.io/guides/gs-producing-web-service"> ... That looks like valid XML, so what's the problem? Is that output produced by the 'other tool'? Or is it something that the 'other tool' cannot handle?
-34014074 0Found how to get it:
from openerp.http import request ua = request.httprequest.environ.get('HTTP_USER_AGENT', '') Note. httprequest seems to be deprecated. But for now I din't find another way to get user agent.
Being from a SQL Server background, I've always created a trigger on the table to basically emulate IDENTITY functionality. Once the trigger is on, the SK is automatically generated from the sequence just like identity and you don't have to worry about it.
-3471880 0 JSF: How to refresh a page after downloadI have a commandButton that will invoke a function to download a file (standard stuffs like InputStream, BufferedOutputStream ...) After download success, at the end of the function, I change some values of the current object and persist it into database. All of these work correctly. Now when file is done downloading, the content of the page is not updated. I have to hit refresh for me to see updated content. Please help. Below are the basic structure of my code
document: Managed Bean
getDrawings(): method return a list of Drawing (entity class)
CheckedOutBy: attribute of Entity Drawing
<p:dataTable id="drawing_table" value="#{document.drawings}" var="item" > <p:column> <f:facet name="header"> <h:outputText value="CheckedOutBy"/> </f:facet> <h:outputText value="#{item.checkedOutBy}"/> ... </p:dataTable> <p:commandButton ajax="false" action="#{document.Download}" value="Download" /> Inside my Managed Bean
public void Download(){ Drawing drawing = getCurrentDrawing(); //Download drawing drawing.setCheckedOutBy("Some Text"); sBean.merge(drawing); //Update "Some Text" into CheckedOutBy field }
-3482879 0 Where are the functional gui users? There has been a lot of research into ways of creating guis in a functional language. There is libraries for push/pull frp, arrow based frp and probably other superior research too. Many people seem to agree this is the more native way yet just about everyone seems to be using imperative binding libraries such as gtk2hs and wxhaskell. Even places recommended as good tutorials teach binding to these plain imperative libraries. Why not guis based on FRP research?
-14380143 0 Matching binary patterns in CI'm currently developing a C program that needs to parse some bespoke data structures, fortunately I know how they are structured, however I'm not sure of how to implement my parser in C.
Each of the structures are 32-bits in length, and each structure can be identified by it's binary signature.
As an example, there are two particular structures that I'm interested in, and they have the following binary patterns (x means either 0 or 1)
0000-00xx-xxxx-xxx0 0000-10xx-10xx-xxx0 Within these structures the 'x' bits contain the actual data I need, so essentially I need a way of identifying each structure based on how the bits are written within each structure.
So as an example in pseudo-code:
if (binaryPattern = 000010xxxxxxxxx0) { do something with it; } I'm guessing that reading them as ints, and then performing some kind of bitmasking would be the way to go, but my knowledge of C isn't great, and maybe a simple logical OR operation would do it, but I just wanted some advice on doing this before I start.
Thanks
Thanks very much to everyone that has answered, very helpful!!
-28369745 0How do you parse JSON data? If you are using Gson, you can use GsonBuilder.disableHtmlEscaping() method in order to display proper characters instead of their code.
-28225138 0 Not fully understanding how this closure worksI have an excerpt from How do JavaScript closures work?
I am having a difficult time understanding closures.
<button type="button" id="bid">Click Me!</button> <script> var element = document.getElementById('bid'); element.onclick = (function() { // init the count to 0 var count = 0; return function(e) { // <- This function becomes the onclick handler count++; // and will retain access to the above `count` if (count === 3) { // Do something every third time alert("Third time's the charm!"); //Reset counter count = 0; } }; })(); How is the 'count' value saved between invocations? Should not it be reset every invocation by var = 0?
-5452751 0You can't do this, it's up to the user.
-30110401 0An iOS application doesn't receive any callbacks when it is about to be uninstalled, so it's not possible to do what you want.
See this question Detect iOS application about to delete?
-21911043 0 Accessing file in Pig through Distributed CacheI went through many pages on Stackoverflow regarding this. But still I am confused. Even if this is a duplicate question or a similar one, Please answer
I want to compare one file against another in Pig and I want one of the files to be in distributed cache so that every mapper has it locally. How to implement it in Pig.
-19775676 0The problem is because of this:
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout); This is happening because your service has not stopped within your timeout. You should either set your timeout higher, or don't set a timeout at all.
Warning: I may be totally misunderstanding you, but if all you want is a log file, why sweat?
Put this in a bat file (change the path to your tools directory, and yourappname is of course your app's name):
cd "C:\devAndroid\Software\android-sdk-windows-1.6_r1\android-sdk-windows-1.6_r1\tools" adb logcat -v time ActivityManager:W yourappname:D *:W >"C:\devAndroid\log\yourappname.log" Then in your code just do something similar to this:
Log.d("yourappname", "Your message"); To create the log, connect the USB cable and run your bat file.
Regards
-10630061 0Without having to increase the asset size of your app, you could create a simple UIView.
UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow]; UIView *fullscreenShadow = [[UIView alloc] initWithFrame:keyWindow.bounds]; fullscreenShadow.backgroundColor = [UIColor blackColor]; fullscreenShadow.alpha = 0.3; [keyWindow addSubview:fullscreenShadow]; Adding it to the keyWindow will make it cover everything, except the UIStatusBar of course. I believe this will achieve your intended result. Combine it with a UIViewAnimation and bring the alpha up.
-29311039 0 how can I select the other departments from this querySo I have the following query
SELECT deptno, COUNT(deptno) number_of_jobs FROM emp WHERE job = 'SALESMAN' GROUP BY deptno ORDER BY number_of_jobs ASC; What this does is to return me just department 30, while I want departments 10 and 20 aswell.
Like this
deptno number_of_jobs 10 (here it can be null or 0 doesn't really matter) 20 (same like dept 10) 30 4 I know this is fairly easy and I believe it's done using a join condition, but I just can't get my head around it.
Thanks guys!
-32201889 0Your input is incorrect, it should be in the MathML namespace:
<math xmlns="http://www.w3.org/1998/Math/MathML"> <apply><power></power><ci>x</ci><cn>2</cn></apply> </math> Not directly related to your problem but there is a newer, maintained, version of the ctop.xsl stylesheet here
https://github.com/davidcarlisle/web-xslt/tree/master/ctop
-24564499 0 Trouble creating array of JSON objectsWell! I have to create an array of JSON objects something like:
[object, object, object...] and for that I take all selected rows in my jtable of jquery, creating a single object with all parameters for each row and at end of record reading I add that object to a previous array, this:
var myObject = new Array(); $selectedRows.each(function () { var record = $(this).data('record'); var id = record.id; var proyecto = record.proyecto; var tarea = record.tarea; var fase = record.fase; var name = record.name; var timeStart = record.timeStart; var timeEnd = record.timeEnd; var duracion = record.duracion; var facturada = record.facturada; var activa = record.deleted; var actividad = [{id:id,proyecto:proyecto, tarea:tarea,tarea:tarea,fase:fase,name:name,timeStart:timeStart,timeEnd:timeEnd,duracion:duracion,facturada:facturada,activa:activa }]; myObject.push(actividad); }); Chrome console sais that I created an Array that have Arrays that have each one its correlative object, something like: [Array[1], Array[1], Array[1] ... ] My objects are inside that arrays Can I convert it to:
[object, object, object...] ???
-7127980 0To skip lines that do not match those strings add a check:
if any(bool(x) for x in d, HD, HA, M): print ... output.write Try running the script in a debugger:
$ python -m pdb your_script.py and see what variables are there and what's wrong. Since PDB is not convenient, you might want to install ipdb or pudb.
Keep it simple, son.
declare @date1 datetime declare @date2 datetime select @date1 = GETDATE(); select @date2 = '2013-02-02 14:05' select DATEDIFF(hh, @date2, @date1) Results ----------- 71 (1 row(s) affected)
-11862172 0 Use UIDevice Macros - http://d3signerd.com/tag/uidevice/
Then you can write code like;
if ([DEVICE_TYPE isEqualToString:DEVICE_IPAD]) { } or
if (IS_SIMULATOR && IS_RETINA) { }
-29984885 0 Its better to make use of DRUPAL for your development.
-25685544 0Try replacing the categories route, as create me be taken as a category
Route::get('projects/{cat}', ['as' => 'projects.category', 'uses' => 'ProjectsController@category']); Route::get('projects/{cat}', ['as' => 'projects.category', 'uses' => 'ProjectsController@category', 'except' => ['create']]);
-36813005 0 You can try something like this:
yourJSonObject.getJSONObject("cover").getJSONObject("content").getJSONObject("article");
-11868768 0 Use a running total.
Have a single variable int "calories"
Whenever you add a food item add them to calories and display
whenever you remove a food item remove them from calories and display
-5404906 0illegalstate exception means am thinking that thread you are using is not correctly handling.. can you post your code..so can find where the exact exception happens
-13892367 0You can change the log in the y axis with the following:
plt.gca().set_yscale('linear') Or press the L key when the figure is in focus.
However, your hist() with log=True does not plot a logarithmic x axis. From the docs:
matplotlib.pyplot.hist(x, bins=10, ...)
bins: Either an integer number of bins or a sequence giving the bins. If bins is an integer, bins + 1 bin edges will be returned, consistent with numpy.histogram() for numpy version >= 1.3, and with the new = True argument in earlier versions. Unequally spaced bins are supported if bins is a sequence.
So if you just set bins=10 they will be equally spaced, which is why when you set the xscale to log they have decreasing widths. To get equally spaced bins in a log xscale you need something like:
plt.hist(x, bins=10**np.linspace(0, 1, 10))
-16860338 0 I had a similar problem and the solution that I found was to replace the startActivityForResult functionality by storing the result into the shared preferences and loading them later in onResume. Check the full discussion here.
-18134031 0Maybe you are confused by the fact, that the class Ordering is declared as Ordering<T>, but the return value of the onResultOf method is Ordering<F>.
The first type argument of the Function, you are providing to onResultOf is the type argument of the result.
That also means, that Value is not forced to be a subtype of Map.Entry.
It doesn't matter how you pass the arguments to below,
while ((i = getopt_long(argc, argv, "MCFA:acdegphinNorstuVv?wxl", longopts, &lop)) != EOF) switch (i) { ... case 'a': flag_all++; break; case 'n': flag_not |= FLAG_NUM; break; ... Just the cases a & n are enabled which is processed later with the respective flags set.
You cannot find socat libraries because there are none. socat is implemented as a monolithic executable (it does link to the standard system libraries though). You can download socat sources and copy-paste required functionality.
-13427097 0Give your text box a id for example "txtInput" give your iframe a id for example "myIframe" on the button give it no navigation so it stays on current page and use the onclick="myFunction()"
in the function you can use this (excuse me if this is slightly wrong its been a while since I have used HTML
function myFunction() { var iframe = document.getElementById("myIframe"); var input = document.getElementById("txtInput").text; //check to see if there is a valid url in the text box be carefull if there are multiple links in the text box it will put them all in and the iframe will go to 127.0.0.1 or search engine due to incorrect URL var isURL=new RegExp(/(((f|ht)(tp|tps):\/\/)[\w\d\S]+)/,g); iframe.src = input.match(isURL); } If you do not want to mess with regular expresions you can just simply use the following.
function myFunction() { var iframe = document.getElementById("myIframe"); var input = document.getElementById("txtInput").text; iframe.src = isURL; }
-40858469 0 As per you are not using AsyncTask, you can't get the opportunity of onProgressUpdate feature. So, you have to update your progress bar status manually like using own thread and you have already do. But, I solved my problem using below source code, you can check it:
private void createThread(){ Runnable runable = new updateProgressStatus(); progressUpdateThread = new Thread(runnable); progressUpdateThread.start(); } public class updateProgressStatus implements Runnable { public void run() { while(Thread.currentThread()==progressUpdateThread) try { Thread.sleep(1000); progressHandler.sendMessage(YOUR MESSAGE ); } catch (InterruptedException e) { // Interrupt problem Thread.currentThread().interrupt(); } catch (Exception e) { e.printStackTrace(); } } } private Handler progressHandler = new Handler(){ @Override public void handleMessage(Message message) { // Now, update your progress bar status progress.setProgress(message.what); } };
-11655044 0 Lazy list items are not clicking per item only per row I have been breaking my head trying to get this working but I can't to save my life, I was hoping one of you guys knew how to do it. Basically, I have a list of nature pictures that are loading in a lazy ListView, but my problem is that I can only make the row clickable. I need to make the the individual images clickable. Everything else works like a charm, I really appreciate the help.
Activity:
public class AmainActivityNature extends Activity { ListView list; LazyAdapter adapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); list=(ListView)findViewById(R.id.list); adapter=new LazyAdapter(this, mStrings, mphotos); list.setAdapter(adapter); Button bLeft = (Button) findViewById(R.id.buttonLeft); bLeft.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent mainIntentOne = new Intent(AmainActivityNature.this, AmainActivityNature.class); AmainActivityNature.this.startActivity(mainIntentOne); /* Finish splash activity so user cant go back to it. */ AmainActivityNature.this.finish(); /* Apply our splash exit (fade out) and main entry (fade in) animation transitions. */ overridePendingTransition(R.anim.animation_enterl, R.anim.animation_leaver); } }); Button bRight = (Button) findViewById(R.id.buttonRight); bRight.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { startActivity(new Intent("com.testing.image.AMAINACTIVITYNATURE")); finish(); } }); list.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { switch (arg2) { case 0: Intent newActivity0 = new Intent(AmainActivityNature.this,NatureTwoOne.class); startActivity(newActivity0); break; case 1: Intent newActivity1 = new Intent(AmainActivityNature.this,NatureTwoTwo.class); startActivity(newActivity1); break; case 2: Intent newActivity2 = new Intent(AmainActivityNature.this,NatureTwoThree.class); startActivity(newActivity2); break; case 3: Intent newActivity3 = new Intent(AmainActivityNature.this,NatureTwoFour.class); startActivity(newActivity3); break; case 4: Intent newActivity4 = new Intent(AmainActivityNature.this,NatureTwoFive.class); startActivity(newActivity4); break; case 5: Intent newActivity5 = new Intent(AmainActivityNature.this,NatureTwoSix.class); startActivity(newActivity5); break; case 6: Intent newActivity6 = new Intent(AmainActivityNature.this,NatureTwoSeven.class); startActivity(newActivity6); break; case 7: Intent newActivity7 = new Intent(AmainActivityNature.this,NatureTwoEight.class); startActivity(newActivity7); break; case 8: Intent newActivity8 = new Intent(AmainActivityNature.this,NatureTwoNine.class); startActivity(newActivity8); break; case 9: Intent newActivity9 = new Intent(AmainActivityNature.this,NatureTwoTen.class); startActivity(newActivity9); break; case 10: Intent newActivity10 = new Intent(AmainActivityNature.this,NatureTwoEleven.class); startActivity(newActivity10); break; case 11: Intent newActivity11 = new Intent(AmainActivityNature.this,NatureTwoTwoelve.class); startActivity(newActivity11); break; case 12: Intent newActivity12 = new Intent(AmainActivityNature.this,NatureTwoThirteen.class); startActivity(newActivity12); break; case 13: Intent newActivity13 = new Intent(AmainActivityNature.this,NatureTwoFourteen.class); startActivity(newActivity13); break; case 14: Intent newActivity14 = new Intent(AmainActivityNature.this,NatureTwoFifteen.class); startActivity(newActivity14); break; case 15: Intent newActivity15 = new Intent(AmainActivityNature.this,NatureTwoSixteen.class); startActivity(newActivity15); break; case 16: Intent newActivity16 = new Intent(AmainActivityNature.this,NatureTwoSeventeen.class); startActivity(newActivity16); break; case 17: Intent newActivity17 = new Intent(AmainActivityNature.this,NatureTwoEighteen.class); startActivity(newActivity17); break; case 18: Intent newActivity18 = new Intent(AmainActivityNature.this,NatureTwoNineteen.class); startActivity(newActivity18); break; case 19: Intent newActivity19 = new Intent(AmainActivityNature.this,NatureTwoTwoenty.class); startActivity(newActivity19); break; case 20: Intent newActivity20 = new Intent(AmainActivityNature.this,NatureTwoTwoentyone.class); startActivity(newActivity20); break; case 21: Intent newActivity21 = new Intent(AmainActivityNature.this,NatureTwoTwoentytwo.class); startActivity(newActivity21); break; case 22: Intent newActivity22 = new Intent(AmainActivityNature.this,NatureTwoTwoentythree.class); startActivity(newActivity22); break; case 23: Intent newActivity23 = new Intent(AmainActivityNature.this,NatureTwoTwoentyfour.class); startActivity(newActivity23); break; case 24: Intent newActivity24 = new Intent(AmainActivityNature.this,NatureTwoTwoentyfive.class); startActivity(newActivity24); break; default: // Nothing do! } } }); Button b=(Button)findViewById(R.id.button1); b.setOnClickListener(listener); } @Override public void onDestroy() { list.setAdapter(null); super.onDestroy(); } public OnClickListener listener=new OnClickListener(){ @Override public void onClick(View arg0) { adapter.imageLoader.clearCache(); adapter.notifyDataSetChanged(); } }; private String[] mphotos={ "http:testingsite.com/naturemain/2.jpg", "http:testingsite.com/naturemain/4.jpg", "http:testingsite.com/naturemain/6.jpg", "http:testingsite.com/naturemain/8.jpg", "http:testingsite.com/naturemain/10.jpg", "http:testingsite.com/naturemain/12.jpg", "http:testingsite.com/naturemain/14.jpg", "http:testingsite.com/naturemain/16.jpg", "http:testingsite.com/naturemain/18.jpg", "http:testingsite.com/naturemain/20.jpg", "http:testingsite.com/naturemain/22.jpg", "http:testingsite.com/naturemain/24.jpg", "http:testingsite.com/naturemain/26.jpg", "http:testingsite.com/naturemain/28.jpg", "http:testingsite.com/naturemain/30.jpg", "http:testingsite.com/naturemain/32.jpg", "http:testingsite.com/naturemain/34.jpg", "http:testingsite.com/naturemain/36.jpg", "http:testingsite.com/naturemain/38.jpg", "http:testingsite.com/naturemain/40.jpg", "http:testingsite.com/naturemain/42.jpg", "http:testingsite.com/naturemain/44.jpg", "http:testingsite.com/naturemain/46.jpg", "http:testingsite.com/naturemain/48.jpg", "http:testingsite.com/naturemain/50.jpg" }; private String[] mStrings={ "http:testingsite.com/naturemain/1.jpg", "http:testingsite.com/naturemain/3.jpg", "http:testingsite.com/naturemain/5.jpg", "http:testingsite.com/naturemain/7.jpg", "http:testingsite.com/naturemain/9.jpg", "http:testingsite.com/naturemain/11.jpg", "http:testingsite.com/naturemain/13.jpg", "http:testingsite.com/naturemain/15.jpg", "http:testingsite.com/naturemain/17.jpg", "http:testingsite.com/naturemain/19.jpg", "http:testingsite.com/naturemain/21.jpg", "http:testingsite.com/naturemain/23.jpg", "http:testingsite.com/naturemain/25.jpg", "http:testingsite.com/naturemain/27.jpg", "http:testingsite.com/naturemain/29.jpg", "http:testingsite.com/naturemain/31.jpg", "http:testingsite.com/naturemain/33.jpg", "http:testingsite.com/naturemain/35.jpg", "http:testingsite.com/naturemain/37.jpg", "http:testingsite.com/naturemain/39.jpg", "http:testingsite.com/naturemain/41.jpg", "http:testingsite.com/naturemain/43.jpg", "http:testingsite.com/naturemain/45.jpg", "http:testingsite.com/naturemain/47.jpg", "http:testingsite.com/naturemain/49.jpg" }; @Override public boolean onCreateOptionsMenu(Menu menu){ super.onCreateOptionsMenu(menu); MenuInflater menuinflater = getMenuInflater(); menuinflater.inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item){ switch(item.getItemId()){ case R.id.inflate: startActivity(new Intent("com.testing.image.ABOUTUS")); return true; } return false; } } Row XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" > <ImageView android:id="@+id/image" android:layout_width="150dip" android:layout_height="120dip" android:scaleType="centerCrop" android:src="@drawable/backgroundimage" /> <TextView android:layout_width="20dip" android:layout_height="1dip" /> <TextView android:layout_width="1dip" android:layout_height="150dip" /> <ImageView android:id="@+id/photo" android:layout_width="150dip" android:layout_height="120dip" android:scaleType="centerCrop" android:src="@drawable/stub" /> <TextView android:id="@+id/text" android:layout_width="1dip" android:layout_height="1dip" /> </LinearLayout> Main XML:
<ListView android:id="@+id/list" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" /> Sub-Activity:
public class NatureTwoOne extends Activity { ImageView image; private class BackgroundTask extends AsyncTask<String, Void, Bitmap> { protected Bitmap doInBackground(String...url) { //--- download an image --- Bitmap bitmap = DownloadImage(url[0]); return bitmap; } protected void onPostExecute(Bitmap bitmap) { ImageView image = (ImageView) findViewById(R.id.imageView1); bitmaptwo=bitmap; image.setImageBitmap(bitmap); } } private InputStream OpenHttpConnection(String urlString) throws IOException { InputStream in = null; int response= -1; URL url = new URL(urlString); URLConnection conn = url.openConnection(); if (!(conn instanceof HttpURLConnection )) throw new IOException("Not an HTTP connection"); try { HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setAllowUserInteraction(false); httpConn.setInstanceFollowRedirects(true); httpConn.setRequestMethod("GET"); httpConn.connect(); response = httpConn.getResponseCode(); if (response == HttpURLConnection.HTTP_OK){ in = httpConn.getInputStream(); } } catch (Exception ex) { throw new IOException("Error connecting"); } return in; } private Bitmap DownloadImage(String URL) { Bitmap bitmap = null; InputStream in = null; try { in = OpenHttpConnection(URL); bitmap = BitmapFactory.decodeStream(in); in.close(); } catch (IOException e1){ Toast.makeText(this,e1.getLocalizedMessage(), Toast.LENGTH_LONG).show(); e1.printStackTrace(); } return bitmap; } public static Bitmap bitmaptwo; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.wallpaper); new BackgroundTask().execute("http:testingsite.com/natureone/1.jpg"); Button setWallpaper = (Button) findViewById(R.id.button3); setWallpaper.setOnClickListener(new OnClickListener() { public void onClick(View view) { WallpaperManager wManager; Toast noSong = Toast.makeText(NatureTwoOne.this, "Background Set", Toast.LENGTH_SHORT); noSong.show(); try { // bitmap = BitmapFactory.decodeFile(null); wManager = WallpaperManager.getInstance(getApplicationContext()); wManager.setBitmap(bitmaptwo); } catch (IOException e) { e.printStackTrace(); } } }); Button bLeft = (Button) findViewById(R.id.buttonLeft); bLeft.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent mainIntentOne = new Intent(NatureTwoOne.this, NatureTwoFifty.class); NatureOneOne.this.startActivity(mainIntentOne); if(bitmaptwo != null){ bitmaptwo.recycle(); } /* Finish splash activity so user cant go back to it. */ NatureOneOne.this.finish(); /* Apply our splash exit (fade out) and main entry (fade in) animation transitions. */ overridePendingTransition(R.anim.animation_enterl, R.anim.animation_leaver); } }); Button bRight = (Button) findViewById(R.id.buttonRight); bRight.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { startActivity(new Intent("com.testing.image.NATURETWOTWO")); if(bitmaptwo != null){ bitmaptwo.recycle(); } finish(); } }); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if(bitmaptwo != null){ bitmaptwo.recycle(); } finish(); } return super.onKeyDown(keyCode, event); } @Override public boolean onCreateOptionsMenu(Menu menu){ super.onCreateOptionsMenu(menu); MenuInflater menuinflater = getMenuInflater(); menuinflater.inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item){ switch(item.getItemId()){ case R.id.inflate: startActivity(new Intent("com.testing.image.ABOUTUS")); return true; } return false; } } Adapter:
public class LazyAdapter extends BaseAdapter { private Activity activity; private String[] data; private String[] dataone; private static LayoutInflater inflater=null; public ImageLoader imageLoader; public LazyAdapter(Activity a, String[] d, String[] mphotos) { activity = a; data=d; dataone = mphotos; inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); imageLoader=new ImageLoader(activity.getApplicationContext()); } public int getCount() { return data.length; } public int getCountOne() { return dataone.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { View vi=convertView; if(convertView==null) vi = inflater.inflate(R.layout.item, null); TextView text=(TextView)vi.findViewById(R.id.text);; ImageView image=(ImageView)vi.findViewById(R.id.image); ImageView photos=(ImageView)vi.findViewById(R.id.photo); text.setText("item "+position); imageLoader.DisplayImage(data[position], image); imageLoader.DisplayImage(dataone[position], photos); return vi; } }
-26433580 0 So your "Work" is a company?
I would do:
(:Person)-[:WORKS_IN]->(:Employment) (:Employment)-[:HAS_CATEGORY]->(:Category)-[:NEEDS_SKILLS]->(:Skill) (:Person)-[:HAS_SKILLS]->(:Skill) (:Employment)-[:IN_COMPANY]->(:Company) 
There is no problem in your code, but the problem in client request, because Content-Type should be like below if you want to upload image,
multipart/form-data; boundary="123123" try to remove the Content-Type header and test, i will put one example for server code and client request
Server code:
@RequestMapping(method = RequestMethod.POST, value = "/users/profile") public ResponseEntity<?> handleFileUpload(@RequestParam("name") String name, @RequestParam(name="file", required=false) MultipartFile file) { log.info(" name : {}", name); if(file!=null) { log.info("image : {}", file.getOriginalFilename()); log.info("image content type : {}", file.getContentType()); } return new ResponseEntity<String>("Uploaded",HttpStatus.OK); } Client Request using Postman
without image
Curl example:
without image, with Content-Type
curl -X POST -H "Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW" -F "name=test" "http://localhost:8080/api/users/profile" without image, without Content-Type
curl -X POST -F "name=test" "http://localhost:8080/api/users/profile"
-29531583 0 You can just do this:
echo $memus[0]['name']; Or if you want all of them
foreach ($memus as $memu) { echo $memu['name']; }
-19966306 0 Two potential sources of the problem, you shouldn't store your files with spaces in their names and you haven't specified a type for your video.
The SRC should contain a valid URL and therefore you should have %20 or + in your PHP string in stead of the spaces.
Note: As mentioned by Fisk, your php tags are wrong due to the spacing. You use the PHP echo short-form by replacing
< ?php echo $vid; ? > by <?= $vid; ?>
-8946877 0 grails not using cache I've noticed a slow down on my site and after turning on debug 'org.hibernate.SQL' I see where the troubles are. I've set a domain class to be cached using....
class Foo{ ... static mapping ={ cache 'read-only' } String name //<-- simple data type, no associations String description //<-- simple data type, no associations } My hibernate config looks like this...
hibernate { cache.use_second_level_cache=true cache.use_query_cache=true cache.provider_class='net.sf.ehcache.hibernate.EhCacheProvider' } my query looks like this (in a web flow)...
def wizardFlow = { ... def flow.foos = Foo.list([sort:"name", order:"asc", cache:true]) // def flow.foos = Foo.findAll([cache:true]) <--- same result, no caching } I would think that either the query cache or second level cache would stop the database from being hit but my log is loaded with...
select ... from thing thing0_ where thing0_.id=? select ... from thing thing0_ where thing0_.id=? select ... from thing thing0_ where thing0_.id=? select ... from thing thing0_ where thing0_.id=? Can anyone shed some light on what might be happening? Other queries are acting as they should!
I'm using Grails 1.3.7
Lastly, here is my ehcache.xml...
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" > <diskStore path="java.io.tmpdir"/> <cacheManagerEventListenerFactory class="" properties=""/> <defaultCache maxElementsInMemory="1000000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="7200" overflowToDisk="true" diskPersistent="false" /> <cache name="org.hibernate.cache.UpdateTimestampsCache" maxElementsInMemory="10000" timeToIdleSeconds="300" /> <cache name="org.hibernate.cache.StandardQueryCache" maxElementsInMemory="10000" timeToIdleSeconds="300" /> </ehcache>
-6578891 0 Spring Interview Questions required I am looking for an extensive list of Spring Interview questions? I have searched developerBooks and some others too, but havent found an extensive list.
Any Help?
-37680251 0your intent has a null value. use this code instead:
if (intent != null) { String action = intent.getAction(); if (ACTION_LOAD_MY_DATA.equals(action)) { super.loadMyData(); return ; } }
-2624593 0 If your button is inside an UpdatePanel, you should place your BulletedList control inside an UpdatePanel too.
You can place an UpdatePanel surrounding the BulletedList in the MasterPage file. Set "UpdateMode" to "Conditional" then call the Update method of the UpdatePanel to refresh only when needed ('save button' click for example).
-31186636 0After digging on cxf forums, I found the answer.
Map<String, String> nsMap = new HashMap<>(); nsMap.put("prefix1", "url1"); nsMap.put("prefix2", "url2"); nsMap.put("prefix3", "url3"); nsMap.put("prefix4", "url4"); nsMap.put("prefix5", "http://www.w3.org/2001/04/xmlenc#"); Client client = ClientProxy.getClient(port); client.getRequestContext().put("soap.env.ns.map", nsMap); I would be appreciated if anyone know on how to do the same for <soap:Header>
I've also had great success using Aptana's Jaxer + jQuery to parse pages. It's not as fast or 'script-like' in nature, but jQuery selectors + real JavaScript/DOM is a lifesaver on more complicated (or malformed) pages.
-40009117 0I suggest that you use child_process.spawnSync which is a blocking call and returns ONLY after the process is complete. In addition, the object returned includes an error property that contains the code.
But in all cases - spawn or spawnSync, etc, I believe the result object always includes an error object if the sub-process fails for any reason. So checking for the existence of this object is probably enough.
-27075452 0Simply put, put an ampersand and then amp; as shown below.
-17478465 0&amp;
This should work (without a double replace):
<? echo preg_replace("#(http|ftp|https):/([^/])#", "$1://$2", 'http://www.google.com'); echo "<br>"; echo preg_replace("#(http|ftp|https):/([^/])#", "$1://$2", 'http:/www.google.com'); ?> This will only do the replace if there is no double slash.
-7227142 0 How to enable a menu in Eclipse depending on the EXE fileI want to disable a context menu item in Eclipse plugin bases on the EXE file. I mean, I want to enable the menu only when my EXE file is installed in the user's system. Otherwise it should be in disable mode. What is the way to do it?
-10866319 0String * means a pointer to a String, if you want to do anything with the String itself you have to dereference it with *moj. What you can do instead is this:
String moj = String("Alice has a cat"); // note lack of * and new cout << moj[2]; Also note that anything you allocate with new needs to be deleted after:
String *x = new String("foo"); // code delete x;
-27820436 0 Do not mix sub-query and join logic. Use only one of them. I prefer sub-select.
SELECT tblForumSubGroups_1.id, tblForumSubGroups_1.GroupID, tblForumSubGroups_1.SubGroupTitle, tblForumSubGroups_1.SubGroupDesc, (SELECT COUNT(*) FROM dbo.tblForumPosts WHERE dbo.tblForumSubGroups.id = dbo.tblForumPosts.SubGroupID) AS Expr1 FROM dbo.tblForumSubGroups AS tblForumSubGroups_1
-29248553 0 It sounds like you were trying to used nested loops, but you in fact had one loop at the beginning which closed out and then you loop through the rest. You need to move your closing curly brace marked below:
for($i=0; $i<count($_FILES['upload']['name']); $i++) { $filut = basename($_FILES['upload']['name'][$i]); } <<<<<<<<<=========== This curly brace closes the "for loop" if(isset($_POST['subi'])) { $data1 = $_POST['answers']; foreach($data1) as $postValues) { $sql4 = 'INSERT INTO db_image (text, image) VALUES("'.$postValues.'","'.$filut.'")'; $my->query($sql4); } } ??? <<<<<======== For a nested loop you should close it here or perhaps you were trying to assign $filut as an array in which case the starting for... loop needs to look like this:
for($i=0; $i<count($_FILES['upload']['name']); $i++) { $filut[] = basename($_FILES['upload']['name'][$i]); } (Note the addition of [] after $filut.)
However, if this is what you were intending (to make $filut into an array) then you need to do something different down below in order to access just one element of the array. This is where a nested foreach would solve the problem - maybe this is how you intended to finish it off:
if(isset($_POST['subi'])) { $data1 = $_POST['answers']; foreach($data1 as $postValues) { foreach ($filut as $f) { $sql4 = 'INSERT INTO db_image (text, image) VALUES("'.$postValues.'","'.$f.'")'; $my->query($sql4); } } } This will insert a row for every value in $filut for every value in $_POST['answers']. Is that what you wanted? Or are $filut and $_POST['answers'] in parallel and you want a 1-1 correlation on the insert?
Finally I'm going to suggest that you use prepare and bind since you are getting your data from the user. This example copied/modified from here:
<?php $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } /* Prepare an insert statement */ $query = "INSERT INTO db_image (text, image) VALUES (?,?)"; $stmt = $my->prepare($query); #### NOTE THE USE OF YOUR VARIABLES HERE IN THE BIND - the "ss" means they are strings $stmt->bind_param("ss", $postValues, $f); #### HERE IS WHERE YOUR CODE IS GETTING INSERTED foreach($data1 as $postValues) { foreach ($filut as $f) { /* Execute the statement */ $stmt->execute(); } } /* close statement */ $stmt->close(); /* close connection */ $my->close(); ?> I can't guarantee that I got all the variables changed to match your code, but hopefully it's close enough to give you an idea. This solution (1) protects you from SQL Injection (which is a serious flaw in your code otherwise) and (2) will be much faster by means of the prepare/execute cycle.
Do note the careful indentation in my examples where everything lines up perfectly with 3 or more spaces per indent - I can't tell you how many times I have seen sloppy (or too little) indentation make people miss problems which would be otherwise obvious.
-38696106 0There is a typo in the docs, they actually meant "in favor of the superclass, org.springframework.boot.web.servlet.ErrorPage", which is located in the same artifact, org.springframework.boot:spring-boot.
We have an app to launch on App Store. This App is for a company users(free to download) not for publicly use. Our client has purchased the iOS developer program instead of Enterprise account. So is there any way to launch the App on AppStore using developer program. (like Custom B2B).
Please suggest your ideas. So I can proceed to right way.
Thanks in Advance.
-5800357 0Adjust QToolBar::setMinimumHeight() or QToolBar::setMinimumSize() to your needs.
And don't forget to use appropriate icon sizes then.
-11045515 0 How to Implement shared preference concept in tabhost on android eclipseI am self- learner to android,
Assume an android program is going to display some result on a textview.can any one tell me how to show that answer on first tab of the tab host's on the next screen.How to achieve this?
As per my knowledge i googled and found "Shared preference" concept will be helpful to this problem. Was i right?
And i found some samples but they are not making me clear,can any one give me some examples with screen images.
Thanks for your precious time!.
-31853096 0First of all you should check your route work in browser and after that you should ask this question,
just change the render line to this and every thing works fine :
res.render('index',{ data : my_json });
Not sure if it's causing the problem, but head and body should be inside the html tag.
!!! = surround '<!--[if !IE]> -->'.html_safe, '<!-- <![endif]-->'.html_safe do %html.no-js{:lang => 'en'} %head %body Could be confusing the surround method by having multiple tags appended instead of nested... Worth a try!
I've computed 4 different similarity matrices for same items but in different time periods and I'd like to compare how similarity between items changes over time. The problem is that order of items i.e. matrix columns is different for every matrix. How can I reorder columns in matrices so all my matrices become comparable?
-24241335 0 WAITING at sun.misc.Unsafe.park(Native Method)One of my applications hangs under some period of running under load, does anyone know what could cause such output in jstack:
"scheduler-5" prio=10 tid=0x00007f49481d0000 nid=0x2061 waiting on condition [0x00007f494e8d0000] java.lang.Thread.State: WAITING (parking) at sun.misc.Unsafe.park(Native Method) - parking to wait for <0x00000006ee117310> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject) at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186) at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2043) at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:1085) at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:807) at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1043) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1103) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) at java.lang.Thread.run(Thread.java:722) I am seeing this a lot in jstack output when it hangs.
I heavily using Spring @Async & maps, synchronized maps & ehcache.
What is interesting this only happens on one of app instances. Two others are running perfectly fine. What else I could investigate to get more details in such case?
I found this post - parking to wait for <0xd8cf0070> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject) but it is not very useful in my case.
-14384546 0 Download windows phone sdk 8 offlineI just installed Visual Studio 2012 express edition on my Windows 8 machine.
Now I wanted to install the Windows 8 Phone's SDK, I know it can be downloaded from here : http://dev.windowsphone.com/en-us/downloadsdk
But this link only download a setup which in turns downloads the files, I wanted to know if there is any full sdk download available which I can download and use.
I am planning to use my office connection to download these files and then install it on my home PC.
Any thoughts ?
-20413844 0Note, it's not just silly or visually nice. It helps for example to exit a program without activating the end handlers which might mess up when doing multi threading or forked programs. Like in perl:
#!/usr/bin/env perl exec "/bin/true"; END { print "This wont get printed .. would have if I just 'exit' or 'die'\n"; }
-24832447 0 After discussing with Peter, the problem lay with the path being case-sensitive.
-20302303 0As I see it, you ned to verify two things for that builder:
Checking instance is the easy part. Verifying values needs a bit of trickery.
The simples way to do this would be altering the autoloader. You need to make sure that whenMyClassis requested for autoloader to fetch, instead of/src/app/myclass.phpfile it loads/test/app/myclass.php, which actually contains a "transparent" mock (where you with simple getters can verify the values).bad idea
Update:
Also, if you do not want to mess with autoloader, you can just at th top of your myBuilderTest.php file include the mock class file, which contains definition for MyClass.
... this actually seems like a cleaner way.
namespace Foo\Bar; use PHPUnit_Framework_TestCase; require TEST_ROOT . '/mocks/myclass.php' class MyBuilderTest extends PHPUnit_Framework_TestCase { public function MyBuilder_verify_injected_params_test() { $target = new MyBuilder; $instance = $target->build('a', 'b'); $this->assertEquals('a', $instance->getFirstConstructorParam(); } }
-16754017 0 Why not just avoid the iterator all together as this code seems to work just fine for your implementation of putAll:
for(String s: m.keySet()){ put(s.toLowerCase(), m.get(s)); } As to why you can't seem to work around that error, I have no idea. I tried multiple variants and nothing seemed to work.
-22427058 0 C: Segmentation fault, doubly linked listi am fairly new to C and i have a Problem. Everytime i run the programm i get a "Segmentation fault" and i don't know why. I am pretty sure i know were the problem comes from, so i maked the line in the code. I hope you can help me. Thanks in advance.
struct node { struct node *next; struct node *previous; char data[255]; }; void insert(char *value, struct node **anf, struct node **end) { struct node *var,*temp; var=(struct node *)malloc(sizeof(struct node)); strcpy(var->data, value); if(*anf==NULL) { *anf=var; (*anf)->previous=NULL; (*anf)->next=NULL; *end=*anf; } else { temp=var; temp->next=NULL; temp->previous=*end; (*end)->next=temp; *end=temp; } } int einlesen(char *quelldatei, struct node **anf, struct node **end) { FILE *datei; if ((datei=fopen(quelldatei,"r")) == NULL) { return 1; } else { char string[255]; while(fgets (string, 255, datei)!=NULL) { if (string[strlen(string)-1]=='\n') { char newstring[strlen(string)-1]; int i; for(i = 0; i < sizeof(newstring); i++) { newstring[i]=string[i]; } newstring[sizeof(newstring)]= '\0'; insert(newstring, anf, end); //NOT WORKING } else { insert(string, anf, end); //NOT WORKING } } fclose(datei); return 0; } } int main(int argc, char * argv[]) { struct node *anf,*end; int a = einlese(##FILENAME##,&anf,&end); //##FILENAME## stands for a local file return 0; }
-28477999 0 var currentRows = $('.table tbody tr'); $.each(currentRows, function () { $(this).find(':checkbox').each(function () { if ($(this).is(':checked')) { console.log($(currentRows).eq(1).val()); } }); });
-15508349 0 TFM:
CAIRO_FORMAT_RGB24 each pixel is a 32-bit quantity, with the upper 8 bits unused TFM:
stride = cairo_format_stride_for_width (format, width); data = malloc (stride * height); Hence, the correct index calculation is
data[y * stride + x * 4 + 0] = blue; data[y * stride + x * 4 + 1] = green; data[y * stride + x * 4 + 2] = red; /* yes, in this order */ Also, masks are taken from the image and shifts are hard-coded, which makes absolutely no sense. Calculate the shifts from the masks.
-21939411 0can you check in the xib of your ViewController, select your tableView and click "size inspecto" in the right menu and you change in "iOS 6/7 Deltas": you can tape -20 in height
i think the problem is in adaptation with ios7 and 6
-3430188 0NSString has an instance method intValue that might make this more straightforward.
NSNumber *value = [NSNumber numerWithInt:[[params objectAtIndex:i] intValue]]; Now insert that value into the array. If the string is always this simple, you really don't a number formatter.
I am trying to get a dynamic count to print out but it is telling me @totalCAUUpdates needs a scalar value. Any thoughts?
declare @totalCAUUpdates as int = 0; declare @realTableName as varchar(100) = '[_TEMP_SubscriptionTransactionsForMosoPay09022014]' declare @updateSQL as varchar(1000) = 'select @totalCAUUpdates = count(*) from ' + @realTableName + ' where len(accountNumberUpdated) > 0 OR len(accountAccessoryUpdated) > 0;'; raiserror (@updateSQL, 0,1) with nowait; EXEC (@updateSQL);
-37582816 0 OK for some reason this slipped my mind, im actually doing it in the same SP :)
INSERT INTO [tblMyTable]([Field1]) SELECT [DataField] FROM [tblDataTable] very easy :)
-20323330 0 Error while registering node in selenium gridI am getting below error while starting node for selenium grid-
Default driver org.openqa.selenium.ie.InternetExplorerDriver registration is skipped: [{platform=WINDOWS, ensureCleanSession=true, browserName=internet explorer, version=}] does not match with current platform: MAC
My local system that is hub contains MAC and FIREFOX
Below the configuration of my node(VM).My scripts are on my local machine that is hub-
{ "class": "org.openqa.grid.common.RegistrationRequest", "capabilities": [ { "seleniumProtocol": "WebDriver", "browserName": "firefox", "version": "25.0.1", "maxInstances": 1, "platform" : "LINUX" } ], } Please suggest needful.
-36389339 0In PHP 5.6+ you could do something like this:
function foo(Abc ...$args) { } foo(...$arr); foo() takes a variable amount of arguments of type Abc, and by calling foo(...$arr) you unpack $arr into a list of arguments. If $arr contains anything other than instances of Abc an error will be thrown.
This is a little 'hacky', but it's the only way to get type hinting for an array in PHP, without putting down some extra code.
-17090094 0 LINQ Left Outer Join with conditionsI have the below tables that are coming from my SQL Database with Entity Framework 5.
What I want to do is select all users where tblUserBusiness.BUID equals a passed in value OR where the Users.IsSysAdmin equals True. If the Users.IsSysAdmin equals True there will be no relating tblUserBusiness records hence the Left Outer Join.

I started with the below LINQ query that filtered correctly but did not allow for the Outer Join
businessUsers = (From u In db.Users From bu In db.tblUserBusinesses Where bu.BUID.Equals(buID) Or u.IsSysAdmin.Equals(True) Select New Users With {.ID = u.ID, .Name = u.Name, .UserName = u.UserName}).ToList Then I moved onto the below query which allows for the Outer Join but I have no idea how to implement the Where bu.BUID.Equals(buID) Or u.IsSysAdmin.Equals(True)
businessUsers = (From u In db.Users Group Join bu In db.tblUserBusinesses On u Equals bu.User Into userList = Group Select New Users With {.ID = u.ID, .Name = u.Name, .UserName = u.UserName}).ToList Basically what I am after is the LINQ equivalent to the below TSQL
SELECT Users.ID, Users.UserName, Users.Name FROM Users LEFT OUTER JOIN tblUserBusiness ON Users.ID = tblUserBusiness.UserID WHERE (Users.IsSysAdmin = 1) OR (tblUserBusiness.BUID = 5)
-11225165 0 Setting it to nil will work, assuming that no other object is holding on to (has strong reference to) the NSDictionary.
Update your selector to element+element selector as follows:
#wrapper button:active+#test { width: 0px; }
-25383596 0 The Hough Transform is the most commonly used algorithm to find lines in an image. Once you run the transform and find lines, it's just a matter of sorting them by length and then crawling along the lines to check for the constraints your application might have.
RANSAC is also a very quick and reliable solution for finding lines once you have the edge image.
Both these algorithms are fairly easy to implement on your own if you don't want to use an external library.
-262392 0 Is there a way to find the name of the calling function in actionscript2?In an actionscript function (method) I have access to arguments.caller which returns a Function object but I can't find out the name of the function represented by this Function object. Its toString() simply returns [Function] and I can't find any other useful accessors that give me that... Help :-/
-36069145 0 How to be sure that files are saved in gallery for all Android devices?According to user reviews, my app dosn't save on their phones (LG4, oneplus phones, android 5.1, Android 6.0)
For Android 6.0 I have solved the problem by using the new permission system. But how can I be sure that the code actually works 100% on all devices? Is there any improvment that can be made?
This is the onClick method that is run, when the user clicks the save button But also ask for permission for Android 6 devices
public void saveQuote(View v) { if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { //check if we have permissoin to WRITE_EXTERNAL_STORAGE if (PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { //This method just create a bitmap of my edittext saveBitmap(); } else { //if permission is not granted, then we ask for it ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_EXTERNAL_STORAGE); } } } This is the code that makes the saving operation:
private void saveImageToExternalStorage(Bitmap finalBitmap) { String filename = "#" + pref_fileID.getInt(SAVE_ID, 0) + " Quote.JPEG"; //The directory in the gallery where the bitmaps are saved File myDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString() + "/QuoteCreator"); //The directory in the gallery where the bitmaps are saved File myDir = new File(root + "/QuoteCreator"); //creates the directory myDir. myDir.mkdirs(); File file = new File(myDir, filename); try { FileOutputStream out = new FileOutputStream(file); finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); out.flush(); out.close(); Toast.makeText(getApplicationContext(), R.string.savedToast, Toast.LENGTH_LONG).show(); } catch (Exception e) { e.printStackTrace(); } /* Tell the media scanner about the new file so that it is immediately available to the user. */ MediaScannerConnection.scanFile(this, new String[]{file.toString()}, null, new MediaScannerConnection.OnScanCompletedListener() { public void onScanCompleted(String path, Uri uri) { Log.i("ExternalStorage", "Scanned " + path + ":"); Log.i("ExternalStorage", "-> uri=" + uri); } }); }
-2994053 0 Netbeans render unrecognized files as html I am using Netbeans and very happy with it. Unfortunately I am having a little problem with it that I cant seem to figure out. I am using Silverstripe CMS and it uses a templating system that syntactically is basically just a mix of php and html. These files however end in .ss and therefore netbeans doesnt format and highlight them at all. How do I make netbeans format and highlight all .ss files just as if they where normal html files?
Kind Regards Nick
-20187194 0You have two problems in getting your DIVIDE to work.
In order of occurrence:
You ACCEPT your AMOUNT. Your AMOUNT has an implied decimal place (the V in the PICture string), yet ACCEPT is going to, for your purpose, ignore this implied decimal. There will be no alignment with what the user types at the screen. There is more than one way to deal with this, perhaps the simplest for your purpose it to look at the Intrinsic FUNCTION NUMVAL.
You, as @Magoo indicated, do not use decimal points in your literals, so they are treated as whole numbers, so effectively the figures you expect to be used for the currency conversion are multiplied by 10,000 and left-truncated.
When reporting a problem it is a good idea to show the input data which gave you the problem, the result you actually achieved, and the expected result. If you can work out what is happening but are unsure how to correct it, that is a bonus.
You have tagged Coding-Style. I think you might want to remove that by editing your question. The people interested in the Coding-Style tag are probably not too aware of COBOL. If you have a future Career as a COBOL programmer, your style is going to be more or less dictated by the site standards of where you work, and will change from site to site. You can, of course, develop your own style, but it develops, it isn't just given to you. Knowing the messes you can get into helps you develop style (technique) in avoiding getting there. You'll still need to know how things happen, because not all programmers take the time to develop anything in the way of style.
Read through some of the questions here, and see if you get some ideas about common problems.
-33113171 0I think you are confusing assigning variables with aliases. assigning a variable means you store the result of the command in a variable what this command does
b=`pwd` is running pwd and stores the answer in a variable b.
and alias means giving some command a different name. so running alias b pwd will make it so whenever you run b, you will actually run pwd
recently, when using display:flex and flex-grow, i find a problem:
i write a demo about this question: demo
i run the demo using mac chrome(emulate screen resolution: 320*480)
and ios (lastest) safari,
the result of chrome is what i expected
the screen shot of results below:
the result of safari:

the result of chrome:
-webit-),text-overflow:ellipse,You should be using the Google Places API:
This request
returns the following json for me:
{ "html_attributions" : [], "results" : [ { "formatted_address" : "1054 E Commerce Blvd, Slinger, WI 53086, USA", "geometry" : { "location" : { "lat" : 43.32459619999999, "lng" : -88.2700943 } }, "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png", "id" : "fff40888c14fb49758a87b06cfb567dc700f9c2f", "name" : "1054 E Commerce Blvd", "place_id" : "EiwxMDU0IEUgQ29tbWVyY2UgQmx2ZCwgU2xpbmdlciwgV0kgNTMwODYsIFVTQQ", "reference" : "CpQBigAAAJ9o9UeX-dpZYNA7UMTjNzdGfo2-hKh63_7FFlwohjIlTLw-SW9T55YvvaKqLek9w1wTTW1ruwUhZfDfsbMoC4n1Rk0oYbnyKEAsEPgtwuVf-vNgtYqBrHKpRxT5kECSh4O75_GmZzUaypjQqEAKut-ZCz0eMg5fKzgkCXQrUX2o-kLqlj22_hGGKGdApXJ80xIQtvry7J5ah_DxHh0Hv1SwpBoULWCqMnCH34vJY8WzMRD3pVjNS5o", "types" : [ "street_address" ] } ], "status" : "OK" }
-26947543 0 Yes, this is correct. In your example %PATH% will be expanded to the current value of the PATH variable, so this command is effectively adding a new entry to the beginning of the PATH.
Note that calling set PATH will only affect the current shell. If you want to make this change permanent for all shells, the simplest option is to set it as a user variable using the Environment Variables dialog box.
On Windows 8 you can open this dialog by hitting Win+s and searching for 'environment variables'. On earlier versions of Windows you can right-click 'My Computer', choose Properties, then Advanced system settings, then Environment variables. You can create (or update) a PATH variable in the user variables section and add whatever entries you need. These will be appended to the existing system path. If you take this approach you will need to open a new cmd shell after updating the variables.
-17570042 0If you just do br.title() it will give you the unicode string of the special character.
print attempts to display the non-ASCII character by encoding the Unicode string.
Here's a low-tech technique that keeps all the script in your page template: add a $(document).ready() function to the page that executes conditionally based on a page-level variable, like this ...
// In your button's click handler, set this.UserHasClicked to true var userHasClicked = '<%= this.UserHasClicked %>' == 'True'; $(document).ready(function() { if(userHasClicked) { $(labelSelector).delay(2000).fadeOut(1000); } });
-38956600 0 This error message was introduced with SubGit version 3.2.1 and SVN Mirror add-on version 3.3.0.
SubGit/SVN Mirror rejects push operation that would result into branch replacement in Subversion repository. There are basically two cases when Git changes may lead to replacements on SVN side:
Force push.
When one forcefully pushes non-fast-forward update, SubGit/SVN Mirror has nothing to do but delete current version of the branch and re-create it from some older revision, because this is exactly what non-fast-forward update does: continuing branch history from a commit other than the branch tip.
Fast-forward merge from one branch into another.
When one creates a new branch foo from master:
$ git checkout -b foo $ git commit -am 'fix foo' [foo ca3caf9] fix foo then pushes that branch to SubGit mirror:
$ git push origin foo ... Sending commits to SVN repository: remote: ca3caf9 => r10 branches/foo which gets ca3caf9 mapped to branches/foo@10.
Finally, one merges branch foo back to master:
$ git checkout master $ git merge foo Updating 0e39ad2..ca3caf9 Fast-forward Noticed that Updating ... Fast-forward message? It means git merge found no new commits on master, hence there was no need to create a merge commit, i.e. git merge just moved the master pointer from older commit 0e39ad2 to a newer one ca3caf9.
Now what happens when one pushes master to SubGit mirror:
$ git push origin master SubGit finds out that master was updated from 0e39ad2 mapped to trunk@9 to ca3caf9 mapped to branches/foo@10. There's nothing SubGit can do but delete trunk and re-create it from branches/foo@10 which obviously leads to replacement of trunk.
And so we made sure that SubGit does not replace branches in these two scenarios unless SubGit administrator explicitly sets the following configuration option:
$ edit REPO/subgit/config ... [svn] allowBranchReplacement = true ... $ subgit install REPO However, I'd recommend to keep svn.allowBranchReplacement set to false and follow these best practices to avoid the error message reported in the original question:
Never force push anything; prefer to merge, revert of branch out changes rather than overwrite them.
When merging one branch into another add --no-ff option: it forces git merge to create a merge commit when it would rather do a fast-forward update otherwise:
$ git merge --no-ff foo I'm using the latest version of VMware Workstation (11.1.0) on Windows 7 x64 and I want to be able to do a keystroke of "Ctrl + 1" to go to VM #1, "Ctrl + 2" to go to VM #2, and "Ctrl + 3" to go to VM #3.
Sounds simple right? It isn't.
On Mac OS X, achieving this functionality is trivial with VMware Fusion in combination with Spaces / Mission Control - you can simply put each VM on a separate space and then define whatever space hotkeys you want. I'm migrating from OS X and want this same functionality.
For reference, here are some potential solutions that I've tried and can verify that they don't work:
1) AutoHotkey
AutoHotkey can be used to make hotkeys like so:
^1::WinActivate, Win7(1) - VMware Workstation ^2::WinActivate, Win7(2) - VMware Workstation ^3::WinActivate, Win7(3) - VMware Workstation These work to enter the VMs, but not to exit; Workstation will feed the "Ctrl + 1" to the VM and AutoHotkey does not take precedence, even if AutoHotkey is run as an administrator.
2) Suspend/Unsuspend with AutoHotkey
This promising post suggests that suspending and that unsuspending AutoHotkey while the VMware window is active will fix the problem:
http://superuser.com/questions/232762/autohotkey-script-to-exit-vmware-window
However, even after copying the exact code and making the necessary string modifications, I can't get it to work with Workstation.
3) Remote Desktop and/or VNC
One possible solution, if all 3 of the VMs in question were running Windows, would be to use Microsoft's Remote Desktop feature. However, one or more of the VMs that I intend to use will be running Linux.
On Linux, it is possible to just use VNC. However, VNC has considerable drawbacks when compared to the native VMware Workstation console window: there is no sound, the resolution won't automatically scale, the performance will be bad, and so forth.
Lastly, the VMs will be on 1) networks that won't be connected to the host via a bridged NIC (with the NIC disabled on the host) and 2) using a VPN without any split tunnel. So there will be no connectivity for either remote desktop or VNC in the first place.
3) A Windows Keyboard Hook
Liuk explains how to use a Windows hook to intercept keystrokes using C++:
http://polytimenerd.blogspot.com/2011/02/intercepting-keystrokes-in-any.html
However, after testing with the demo program, it seems that this method does not intercept keystrokes sent to VMware Workstation.
4) FullScreenSwitch.directKey
It seems that in VMware Workstation used to have this kind of functionality built in, as documented in this SuperUser thread:
http://superuser.com/questions/71901/vmware-workstation-keyboard-shortcut
However, VMware's documentations states that this is for VMware Workstation 5.0. I tried adding these strings to my VMX file and they had no effect, so the functionality must have been depreciated somewhere along the lines between Workstation 5 and 11.
5) PSExec
Wade Hatler mentions that he accomplishes this using PSExec to activate the appropriate AutoHotkey script on the host machine:
http://www.autohotkey.com/board/topic/64359-sending-keystrokes-to-vmware-player/
This solution is questionable in that you have to keep the password of your host machine in plaintext in order to pass it to PSExec.
Regardless, this solution will not work for the reasons also described in #2 above: the VMs in question will be on 1) networks that won't be connected to the host via a bridged NIC (with the NIC disabled on the host) and 2) using a VPN without any split tunnel. So there will not be guaranteed connectivity between the host and the guest.
6) Execute a "Host" keystroke between every "Ctrl + #" keystroke
This is problematic in that it doubles the amount of keystrokes involved and makes it impossible to "flip" through all of my VMs by holding down control and hitting 1 + 2 + 3 + 4 + 5, and so forth.
7) Use the "Host + Left/Right Arrow" hotkey and/or VMware-KVM.exe for cycling functionality
This is problematic in that when I have 10 or more VMs open at a time, rotating through all of them becomes incredibly cumbersome and inefficient.
-5786421 0Call multiple functions in an other function
<script type="text/javascript"> function CallMultipleFunctions() { Function1(); Function2(); Function3(); Function4(); } </script> <img onclick= "CallMultipleFunctions()"/> EDIT:
Check this link
-22160482 0Yes there are plugins that offers this functionality, I think most of the drag and drop jQuery plugins has their own callback function that triggers once the dragging and dropping has finished. jQuery List DragSort is a plugin I've used in my project before, it's lightweight and easy to use.
$("menu").dragsort({dragEnd: showHiddenCells }); function showHiddenCells() { //triggers after the user drops the element }
-23067893 0 Since you've posted no logcat, I can't correct your code, but I can give you a working example:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.belfast_map); ImageButton ib1,ib2,ib3,ib4,ib5; //change your image ID's here ib1= (ImageButton) findViewById(R.id.go_to_lagan_screen); ib2= (ImageButton) findViewById(R.id.go_to_city); ib3= (ImageButton) findViewById(R.id.go_to_university); ib4= (ImageButton) findViewById(R.id.go_to_icon_screen); ib5= (ImageButton) findViewById(R.id.map_to_home_screen); ib1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //change the action here, a toast in your example Toast.makeText(MainActivity.this, MainActivity.this.getResources().getString(R.string.my_resource_string), Toast.LENGTH_LONG); } } ); ib2.setOnClickListener((new View.OnClickListener() { @Override public void onClick(View v) { Intent intent1= new Intent (MapScreen.this, CityCentre.class); startActivity(intent1); //To change body of implemented methods use File | Settings | File Templates. } })); ib3.setOnClickListener((new View.OnClickListener() { @Override public void onClick(View v) { Intent intent2= new Intent (MapScreen.this, UniversityArea.class); startActivity(intent2); //To change body of implemented methods use File | Settings | File Templates. } })); ib4.setOnClickListener((new View.OnClickListener() { @Override public void onClick(View v) { Intent intent3= new Intent (MapScreen.this, TheIcons.class); startActivity(intent3); //To change body of implemented methods use File | Settings | File Templates. } })); ib5.setOnClickListener((new View.OnClickListener() { @Override public void onClick(View v) { Intent intent4= new Intent (MapScreen.this, MyActivity.class); startActivity(intent4); //To change body of implemented methods use File | Settings | File Templates. } })); }
-2083329 0 How to track a download page with google-analytics and php? I have a download page in php that after performing some checks returns a file, without displaying any html:
header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=xyz.exe'); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . filesize(LOCAL_FILE)); readfile(LOCAL_FILE); Now I'd like to track this page with google-analytics. What's the best way to achieve this without displaying html?
-1764353 0I've looked at the MSDN page... it said NtQuerySystemInformation() is an OS internal proc, and that we're not recommended to use it:
-19736891 0The NtQuerySystemInformation function and the structures that it returns are internal to the operating system and subject to change from one release of Windows to another. To maintain the compatibility of your application, it is better to use the alternate functions previously mentioned instead.
The problem is exactly what the Traceback log says: Could not convert string to float
The way most people would approach this problem is with a try/except (see here), or using the isdigit() function (see here).
Try/Except
try: miles = float(input("How many miles can you walk?: ")) except: print("Please type in a number!") Isdigit()
miles = input("How many miles can you walk?: ") if not miles.isdigit(): print("Please type a number!") Note that the latter will still return false if there are decimal points in the string
Okay, I won't be able to get back to you for a while, so I'll post the answer just in case.
while True: try: miles = float(input("How many miles can you walk?: ")) break except: print("Please type in a number!") #All of the ifs and stuff The code's really simple:
You can do this in a single redirect rule:
RewriteEngine On RewriteCond %{HTTPS} off [OR] RewriteCond %{HTTP_HOST} !=www.ourwebsite.co.uk RewriteRule ^ https://www.ourwebsite.co.uk%{REQUEST_URI} [R=301,L,NE] # rest of rules go below this Make sure to clear your browser cache before testing this change.
-29189745 0 In XSLT using XPathif I have number like $999,999 I want to use a function to give me just 999999 without any other symbol.I tried substring(value,2) but that take of the $ how about the , Is there any idea to do that,
-17336268 0 How to get text from a textbox using javascripti have developed a web application using mvc4.
in this case i need to get a text box value(actually the text entered in the text box) using javascript.
here is the code i am using
@model PortalModels.WholeSaleModelUser @using (Html.BeginForm("uploadFile", "WholeSaleTrade", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.ValidationSummary(true) <fieldset> <legend>WholeSaleModelUser</legend> <table> <tr> <td> <div class="editor-label"> @Html.LabelFor(model => model.Name) </div> </td> <td> <div class="editor-field"> @Html.TextBoxFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) </div> </td> </tr> </table> <div id="partial"> <table> <tr> <td> <img id="blah" src="../../Images/no_image.jpg" alt="your image" height="200px" width="170px" /> </td> </tr> </table> <script type="text/javascript"> function loadUserImage() { var userImg = document.getElementById("blah"); var imgNm = $("#Name").value; userImg.src = "D:/FEISPortal/FortalApplication/Img/" + imgNm + ".png"; alert(imgNm); alert(userImg.src); } </script> in that case alert gives the value as "undefined" and if do the following modification alert gives nothing.
var imgNm = document.getElementById("Name").value; for
var imgNm = $("#Name").value; how to get the text entered in the text box?
-10499446 0 Make a border to the areas in the image mapsI am trying to add a border around an Image Map Areas.
Here is an example of an Image map with 3 sectors.
<body> <img src="trees.gif" usemap="#green" border="0"> <map name="green"> <area shape="polygon" coords="19,44,45,11,87,37,82,76,49,98" href="http://www.trees.com/save.html"> <area shape="rect" coords="128,132,241,179" href="http://www.trees.com/furniture.html"> <area shape="circle" coords="68,211,35" href="http://www.trees.com/plantations.html"> </map> </body> If somehow i could place a border with 2 pixel with around the area's it would be great.
-13150472 0 Need to assign multiple tables to the parameter "log-output = TABLE" in MySQL 5.5.25Is there is a way to assign multiple tables to the parameter "log-output = TABLE" in my.cnf? I would like to keep rotating the tables, take the backup and truncate the table after rotation.
-28346721 0I was able to figure out why it wasn't working. I was running Windows 10 in a VM (using Parallels on a mac), and the created project was saved in a shared drive with the path something like this,
\psf\Home\Documents\Visual Studio 2015\Projects...
And I guess the file watcher wasn't able to detect file changes and therefore the auto compile wasn't working. I have now created a new project and saved it on c: and the auto compile is working!
-23713099 0The only side effect to keep using .NET 2.0 is that you will not have access to features of newer .NET, such as LINQ, Task Parallel Library, etc.
See this Wikipedia Article for a full comparison of framework features by version.
Windows 7 already comes with .NET 3.5 built in, so if that is really the earliest OS you intend to target, there is really no need to taget .NET 2.0.
If you target .NET 3.5, Windows 7 users can run it with no prerequisite to install .NET 4.0 or higher, but Windows 8 users will need to enable .NET 3.5 (see Scott Chamberlain's answer). So either way, there is a tradeoff.
-6875127 0Based on Walker Hale IV's answer to a similar (but distinct! ;) ) question, there are two keys to doing this:
So the workflow is:
Notes:
I've written a bash script that does the basics in Ubuntu:
#! /bin/bash # Script to create a python virtual environment # independently of the system version of virtualenv # # Ideally this would be a cross-platform Python # script with more validation and fewer TODOs, # but you know how it is. # = PARAMETERS = # $1 is the python executable to use # examples: python, python2.6, /path/to/python # $2 is the new environment folder # example: /path/to/env_folder/name ## TODO: should be just a name ## but I can't concatenate strings in bash # $3 is a pip requirements file # example: /path/to/req_folder/name.txt # you must uncomment the relevant code below to use $3 ## TODO: should be just a name ## but I can't concatenate strings in bash # other parameters are hard-coded below # and you must change them before first use # = EXAMPLES OF USE = # . env_create python2.5 /home/env/legacy ## creates environment "legacy" using python 2.5 # . env_create python /home/env/default ## creates environment "default" using whatever version of python is installed # . env_create python3.2 /home/env/bleeding /home/req/testing.txt ## creates environment "bleeding" using python 3.2 and installs packages from testing.txt using pip # = SET UP VARIABLES = # Required version of virtualenv package VERSION=1.6.4 # Folder to store your virtual environments VE_FOLDER='/media/work/environments' ## TODO: not used because I can't concatenate strings in bash # Folder to store bootstrap (source) versions of virtualenv BOOTSTRAP_FOLDER='/media/work/environments/bootstrap' ## TODO: not used because I can't concatenate strings in bash # Folder to store pip requirements files REQUIREMENTS_FOLDER='/media/work/environments/requirements' ## TODO: not used because I can't concatenate strings in bash # Base URL for downloading virtualenv source URL_BASE=http://pypi.python.org/packages/source/v/virtualenv # Universal environment options ENV_OPTS='--no-site-packages --distribute' # $1 is the python interpreter PYTHON=$1 # $2 is the target folder of the new virtual environment VE_TARGET=$2 # $3 is the pip requirements file REQ_TARGET=$3 ## = DOWNLOAD VIRTUALENV SOURCE = ## I work offline so I already have this downloaded ## and I leave this bit commented out # cd $BOOTSTRAP_DIR # curl -O $URL_BASE/virtualenv-$VERSION.tar.gz ## or use wget # = CREATE NEW ENV USING VIRTUALENV SOURCE = cd $BOOTSTRAP_FOLDER tar xzf virtualenv-$VERSION.tar.gz # Create the environment $PYTHON virtualenv-$VERSION/virtualenv.py $ENV_OPTS $VE_TARGET # Don't need extracted version anymore rm -rf virtualenv-$VERSION # Activate new environment cd $VE_TARGET . bin/activate # = INSTALL A PIP REQUIREMENTS FILE = ## uncomment this if you want to automatically install a file # pip install -r $REQ_TARGET # = REPORT ON THE NEW ENVIRONMENT = python --version pip freeze # deactivate ## uncomment this if you don't want to start in your environment immediately Output looks something like this (with downloading switched off and deactivation switched on):
user@computer:/home/user$ . env_create python3 /media/work/environments/test New python executable in /media/work/environments/test/bin/python3 Also creating executable in /media/work/environments/test/bin/python Installing distribute...............done. Installing pip...............done. Python 3.2 distribute==0.6.19 wsgiref==0.1.2 user@computer:/media/work/environments/test$-12404646 0
You can try this, It will work for both example.
$('h1').each(function(){ var self = $(this); var p = self.text().split(' '); var html = self.html().replace(p[0], '<span>'+ p[0] +'</span>'); self.html(html); }); Check this Demo
-13961384 0 requestNextPage() not a function in Backbone.PaginateI am writing a backbone collection which requires pagination. So this is my code
define([ 'underscore', 'backbone', 'models/object', 'backbone_paginate' ], function(_, Backbone, Object){ "use strict"; var myCollection= Backbone.Paginator.clientPager.extend({ model: Object, paginator_core: { // the type of the request (GET by default) type: 'GET', // the type of reply (jsonp by default) dataType: 'json', // the URL (or base URL) for the service url: location.protocol + '//' + location.host+'/address' }, paginator_ui: { // the lowest page index your API allows to be accessed firstPage: 1, // which page should the paginator start from // (also, the actual page the paginator is on) currentPage: 1, // how many items per page should be shown perPage: 3, // a default number of total pages to query in case the API or // service you are using does not support providing the total // number of pages for us. // 10 as a default in case your service doesn't return the total totalPages: 10, pagesInRange: 3 }, server_api: { '$top': function() { return this.totalPages * this.perPage; }, }, parse:function(dat){ return dat.items; } }); return new myCollection(); }); My view looks like this:
define([ 'jquery', 'underscore', 'backbone', 'collections/addressLists', 'models/object', 'views/shared_object_item', ], function($, _, Backbone, AddressLists,Address,Shared_object_item){ "use strict"; var AppView = Backbone.View.extend({ events: { }, initialize: function() { _.bindAll(this,'render','updateData','showMoreData','showAllData'); this.collection=AddressLists; this.collection.bind('reset',this.render); this.collection.fetch(); }, el:$('div')[0], render: function() { var that=this; $('.innerContainer').bind('scroll',function(){ if($(this)[0].scrollHeight-$(this).scrollTop()==$(this).outerHeight()){ that.showMoreData(); } }); this.updateData(); }, updateData:function(){ var that=this,collection; $('.innerItem').empty(); _.each(this.collection.models,function(model){ $('.innerItem').append(new Shared_object_item({parent:that,collection:that.collection,model:model}).render().el); }); }, showMoreData:function(){ this.collection.requestNextPage(); }, }); return AppView; }); now in my view I am calling : fetch();
and on success of the fetch I am trying to call this.collection.requestNextPage();
It works fine till fetch(), but as soon as it hits the requestNextPage function(which resides in the showMoreData() function ), it throws an error stating that requestNextPage() is not a function.
I dont know wheere am I going wrong here..
-23088033 0 Logging response and request to OAuth providerIs there a way to capture the response from requests served by OAuth? Specifically, I need to log the request and response from OAuthAuthorizationServerProvider.GrantResourceOwnerCredentials().
I've tried extending OwinMiddleware and overriding Invoke as shown in this post, but I'm unable to read the response body. I'd like to use a message handler as this post demonstrates, but I don't have UseHttpMessageHandler on my AppBuilder object.
Any help would be greatly appreciated. Thank you!
Update
Modifying the example provided in Brock's excellent video, here's what I need to do:
public class Startup { public void Configuration(IAppBuilder app) { app.Use(typeof(MW1)); app.Map("/api", fooApp => { fooApp.Use<MW2>(); }); } } public class MW1 { Func<IDictionary<string, object>, Task> next; public MW1(Func<IDictionary<string, object>, Task> next) { this.next = next; } public async Task Invoke(IDictionary<string, object> env) { var ctx = new OwinContext(env); await next(env); // I need to be able to read: <h1>MW2 called</h1> written by MW2 var body = ctx.Response.Body; // body.CanRead = False } } public class MW2 { Func<IDictionary<string, object>, Task> next; public MW2(Func<IDictionary<string, object>, Task> next) { this.next = next; } public async Task Invoke(IDictionary<string, object> env) { var ctx = new OwinContext(env); await ctx.Response.WriteAsync("<h1>MW2 called</h1>"); await next(env); } } I actually need to read the response sent from the OAuth provider, but I assume it would be the same process.
-21696873 0The initial problem stems from the restriction that contracts cannot modify the object they belong to (otherwise, the program might behave differently in debug and release mode). The way the language enforces that restriction is by making the this pointer const.
A const this means is that you can't modify the this object's fields, and as for calling methods - those methods themselves must be annotated as const, and the same restrictions apply to the code of those methods. This explains the first error: the contract, which was const, was trying to call a non-const (mutable) method. Since mutable methods are allowed to modify this, and contracts are forbidden to do so, the compiler forbids the call.
Because of the transitive nature of D's constness, everything that's accessed through the this pointer becomes const. And, if any of the class fields are reference types, the target of their indirections becomes const too. This is how the type system will forbid modifying anything that can be reached through the this pointer.
The implication of this is that if a const method is trying to return a class field (with indirections, such as a class type like Node), the returned type must also be const. This is the source of the second error message: the return expression attempted to convert the const Node value, obtained through the const this, to a mutable Node. Currently, the syntax @property const Node sub() indicates that the method itself is const (and has as const this), not the return type.
Now, generally, in C++, an object with proper constness support will usually have multiple overloads for the methods which return a class field: const, and non-const. The const versions will return a const reference; the non-const will return a non-const reference. The two versions are needed to allow obtaining a mutable field reference when we have access to a mutable object, but still allow getting a const reference if we only have const access to the object. Most of the time, the code of the two methods will be identical - only the function signature will differ.
This is where D's inout comes in. Specifying it on the method and some of its arguments or return value means that those arguments or return value will have the same constness as that of this (the object being referred to). This avoids code duplication for the simple cases where returning const and mutable values uses the same code.
The syntax I used is @property inout(Node) sub() inout. I think it can be written in more than one way, but this syntax is unambiguous. Here, the parens in inout(Node) make it explicit that we apply the attribute on the return value, and not the function, and placing the method (this) inout attribute after the parameter list, like const in C++, unambigously specifies that it applies to the function itself.
First things first, the CoffeeScript compiler already has a join command:
-j, --join [FILE]Before compiling, concatenate all scripts together in the order they were passed, and write them into the specified file. Useful for building large projects.
Secondly, instead of using $(document).ready(function () { ...} ), you can just pass the function directly to the $() - $(function () { ... });
For your actual problem, there are a few ways you could do it.
Compile the .coffee files using the -b / --bare option, and then manually concatenate a file containing $(function() { and the start and }); at the end (but that's pretty gross).
Use something like exports = window ? this to get the global object, and assign the functionality you wish to run in the jQuery load function to that global object, eg:
FooModule = do -> class Foo constructor: (@blah) -> init = -> blah = new Foo('bar') init: init exports = window ? this exports.Foo = FooModule You could then have another file that contains something like the following:
$(-> Foo.init() ) Hope one of those options is good?
-16738910 0In addition to cellEditor it is necessary to do the cellRenderer to paint the combobox in the cell, look at this:
public void example(){ TableColumn tmpColum =table.getColumnModel().getColumn(1); String[] DATA = { "Data 1", "Data 2", "Data 3", "Data 4" }; JComboBox comboBox = new JComboBox(DATA); DefaultCellEditor defaultCellEditor=new DefaultCellEditor(comboBox); tmpColum.setCellEditor(defaultCellEditor); tmpColum.setCellRenderer(new CheckBoxCellRenderer(comboBox)); table.repaint(); } /** Custom class for adding elements in the JComboBox. */ class CheckBoxCellRenderer implements TableCellRenderer { JComboBox combo; public CheckBoxCellRenderer(JComboBox comboBox) { this.combo = new JComboBox(); for (int i=0; i<comboBox.getItemCount(); i++){ combo.addItem(comboBox.getItemAt(i)); } } public Component getTableCellRendererComponent(JTable jtable, Object value, boolean isSelected, boolean hasFocus, int row, int column) { combo.setSelectedItem(value); return combo; } }
-17020545 0 Doctrine 2 Postgresql stock procedure mapping i 'd like to associate to a doctrine entity a postgresql stock procedure (which returns a table as result) instead of a table
Ex : the procedure Get_Uuser(sexe, age) search all the users for the selected parameters et returns a collection of user_id (names user_id_rech for exemple).
In pgsql, I can use this stock procedure as a table :
select user_name from User left join Get_User('H', 45) where User.user_id = user_id_rech
The stock procedure is used like a table here.
I don't think that doctrine 2 allows to map a stock procedure, but I'd like that someone can confirm that to me.
Thanks
-14319708 0Implementing the control is exactly the same as implementing it in pure ASP.NET - no difference.
To include it in Sitefinity, you have to register it in the toolbox. Here is the documentation for this: http://www.sitefinity.com/documentation/documentationarticles/adding-controls-to-the-toolbox
Once that's done, you can create a page in Sitefinity and put your custom control on it using drag and drop. Here's a video showing how: http://www.youtube.com/watch?v=LZ4VHGKQsrg
-18720145 0 Permutation Parser to vectorI have the following rule, inside my boost::spirit grammar;
rule = (qi::token(ABSTRACT) ^ qi::token(STATIC) ^ qi::token(FINAL)) This construct has the type of;
boost::fusion::vector3<boost::optional<boost::iterator_range<std::string::iterator>>, boost::optional<boost::iterator_range<std::string::iterator>>, boost::optional<boost::iterator_range<std::string::iterator>>> However, what I would rather have is;
boost::fusion::vector3<bool, bool, bool> Where each bool have the value of the corresponding boost::optional<...> operator bool() const, with a single case, I'd use qi::matches, as suggested here. However applying this approach yields;
(qi::matches[qi::raw_token(ABSTRACT)] ^ qi::matches[qi::raw_token(STATIC)] ^ qi::matches[qi::raw_token(FINAL)]) Which has the type;
boost::fusion::vector3<boost::optional<bool>, boost::optional<bool>, boost::optional<bool>> Which is indeed not what I wanted, so how would I go about, matching these three tokens in random order, and getting whether they were matched as booleans?
-30978896 0please try closing the classloader before you 'unload' it.
public void unloadJarAndClass() throws IOException { dukeClassLoader.close(); /* all object must be collected in order to reload jar */ jarFile = null; dukeClassLoader = null; classToLoad = null; // System.gc(); don't do this unless you're really // sure you have to ! } I would recommend not calling System.gc() explicitly ! (see Why is it bad practice to call System.gc()? for example)
-26158808 0This error is caused by a product without ID. Check that all your *.product files specify an ID on the Overview tab of the Product Configuration Editor.
-9883244 0 Android Widget inflate layout Performance and MemoryI have problem with my widget related to performance and memory:
Issue: My widget has a very complex, nested layout (Bitmap, layout ...), so to avoid inflating each time update, I plan to use SoftReference to hold the reference object of RemoteViews for the next update.
Question: So, I'm concerned about Performance(battery-usage) vs Memory in this scenario
Does anyone have experience with this situation?
I'd appreciate any advice that can be provided.
Thanks for your help.
P.S. I've also read the following, but it did not provide enough information: Performance RemoteViews in Android
-22905119 0 create image of application and store to databaseI have create a application in c#. What my problem was when user try to edit something new to database via this application, it will not save to main table in database directly, but will store on another table, and waiting for another user to approve it.
In this case, if user try to edit, I wish to save the application image and store to the table, and when another user come and approve it, it can show different before edit and after edit, this is much convenience for user to view and make decision.
I have search through internet, but I can not find a good solution to solve this problem, anyone can help please.
-2161403 0Looking at the documentation for MediaRecorder.AudioSource I would say that this should be possible using the VOICE_DOWNLINK source.
MediaRecorder recorder = new MediaRecorder(); recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_DOWNLINK);
-22568824 0 You are targeting a class called div instead of the tag. Remove the leading dot and you should be fine.
-11159314 0If the response is between 199 and 300 ( >= 200 and < 300 ) or equal to 304 and the responseText can be successfully converted to the dataType that you provide (text by default), it is considered a successful request.
For example, if you return JSON and you get a 200 response status but it fails, it is more than likely a JSON parser problem meaning your JSON is not valid.
If you are returning HTML or XML and it fails with a 200 response status, the responsetext couldn't be converted to HTML or XML respectively (commonly happens in IE with invalid html/xml)
-22245393 0O.K. so I have a solution. I am not sure if it's good enough (since it's a little bit complicated) but whatever...
(If you have other solutions, they will be welcomed :-) )
Steps:
I have trouble querying an association table using sequelize. I have 3 tables: User, Roles and UserRoles. A user can have many roles.
I am trying to query in UserRoles (which stores userID and roleID ).
var User = sequelize.define('User', { // }, { classMethods: { associate: function(models) { User.belongsToMany(models.Role, { through: 'UserRole' }); var Role = sequelize.define('Role', { // }, { classMethods: { associate: function(models) { Role.belongsToMany(models.User, { through: 'UserRole' }); } } }); I suspect the problem is with UserRole Model defition.
var UserRole = sequelize.define('UserRole', { // }, { associate: function(models) { UserRole.belongsTo(models.User, { foreignKey: 'UserId', foreignKeyConstraint: true, targetKey: 'id' }); UserRole.belongsTo(models.Role, { foreignKey: 'RoleId', foreignKeyConstraint: true, targetKey: 'id' }); } db.UserRole.findAll({ //Returns empty })
-15416342 0 Unknown extern method T System.Nullable`1::get_Value() I've run into a problem with my dot42 C# project:
Unknown extern method T System.Nullable`1::get_Value() at System.Void NokiaStyleProfiles.AddDialogue::btnAdd_Click(System.Object,System.EventArgs) (c:\Users\STO\Documents\Visual Studio 2012\Projects\NokiaStyleProfiles\NokiaStyleProfiles\AddDialogue.cs, position 86,13) Code that's causing that problem:
int hourStart = timePickerStart.CurrentHour.Value; (timePicker.CurrentHour is an int?) (int), .Value and .GetValueOrDefault(), as expected, produce the same result : this error.
How can i fix it?
-6214666 0(sourceDirectories in Test) := Seq(new File("src/test/scala/unit"), new File("src/test/scala/functional")) SBT 0.7.x:
override def testSourceRoots = ("src" / "test") +++ "scala" +++ ("unit" / "functional")
-23783033 0 Try this,
if(!"".equals(your string) { // do something }
-39377873 0 static void PrintReport() { int count; fileOut.WriteLine(); fileOut.WriteLine("Score Score Score Score Score"); fileOut.WriteLine("----- ----- ----- ----- -----"); for (int row = 1; row <= numOfRows; row++) { for (int col = 1; col <= numOfCols; col++) { count = row + numOfRows * (col - 1); if (count <= numOfValues) fileOut.Write("{0,5:N2} ", valueArray[count]); } fileOut.WriteLine(); } } this solved my issue
-15213955 0 What is the intersection of two languages with different alphabets?I did some googling on this and nothing really definitive popped up.
Let's say I have two languages A and B.
A = { w is a subset of {a,b,c}* such that the second to the last character of w is b }
B = { w is a subset of {b,d}* such that the last character is b }
How would one define this? I think the alphabet would be the union of both, making it {a,b,c,d} but aside from that, I wouldn't know how to make a DFA of this.
If anyone could shed some light on this, that would be great.
-30041096 0 c++ pass by reference safely and compile time checking on sizeSpiDeviceDriver::SPI_Error SpiDeviceDriver::SPI_ReadBytes( quint32 size_, QVector<quint8>& rxData_ ) { //Get data and fill QVector<quint8> with data } I'm trying to call a class function (from another class) and pass in a QVector, then fill it with data.
I prefer to just pass in the QVector alone (without the quint32 size parameter) and then figure out the size from that and fill it with data according to its size. However, if the passed in QVector is size 0, I'd either have to assume it is meant to be size 1, creating a new spot for the data, or throw/handle the error at run-time, which i'd rather not do. Compile time error checking would be much better. Is there a better way to do this?
I guess you could pass in a quint32 size_ parameter, then forget what the size of the QVector is and force the resizing to be that size. This seems awkward as well
Note: I've been instructed by my boss to make every function return an enum error code, so just using a size_ and creating a vector, then returning that data is not an option.
This is a LONG shot, but maybe someone out here is a super-genius.
I want to combine 4 jpgs in a grid
1 2 3 4 I want to do this client side, without SVG (because IE blows).
I'm looking at manipulating the code inside the jpg files to produce a single, new image. I will get them as all same-sized jpgs, and I can output them to another format (like bitmap) if necessary. I'm also wiling to accept solutions using any special IE "features" like VML. IE8 is the target audience.
I realize I can do this with SVG. I realize I can do this server-side. I realize I can css them next to each other. I need a single image from the 4 originals, as a string is fine (even preferable) because I can base64 encode it and throw it in an image element.
Thanks!
-33296848 0You can try to override:
- (void) setSelectedSegmentIndex:(NSInteger)toValue
-39873396 0 In my opinion, the best way to do this is to simply use the Firebase Realtime Database:
1) Add Firebase support to your app
2) Select 'Anonymous authentication' so that the user doesn't have to signup or even know what you're doing. This is guaranteed to link to the currently authenticated user account and so will work across devices.
3) Use the Realtime Database API to set a value for 'installed_date'. At launch time, simply retrieve this value and use this.
I've done the same and it works great. I was able to test this across uninstall / re-installs and the value in the realtime database remains the same. This way your trial period works across multiple user devices. You can even version your install_date so that the app 'resets' the Trial date for each new major release.
-2063352 0 Caliburn and datatemplates in Silverlight 3Does anyone know if the same functionality for displaying views depending on object/viewmodel is applicable to Silverlight 3?
Like this:
<Application.Resources> <DataTemplate DataType="{x:Type vm:CustomerViewModel}"> <view:CustomerView /> </DataTemplate> <ContentControl Content="{Binding Path=CurrentView}"/> public class RootViewModel : BaseViewModel {
private BaseViewModel _currentView; public BaseViewModel CurrentView { get { return _currentView; } set { _currentView = value; RaisePropertyChanged("CurrentView"); } } public void ShowCustomer() { CurrentView = IoC.Resolve<Customerviewmodel>(); } }
Sorry about the formatting. Can't seem to get it right...
/Johan
-7613396 0In Visual Studio 2010, you now can apply a transformation to your web.config depending on the build configuration.
When creating a web.config, you can expand the file in the solution explorer, and you will see two files:
They contains transformation code that can be used to:
My apologies, I am able to set user metadata through SoftLayer API Client for Java, here a java script, try this and let me know if you continue having issues please. Make sure to use master branch from the client.
Script:
package com.softlayer.api.VirtualGuest; import com.softlayer.api.ApiClient; import com.softlayer.api.RestApiClient; import com.softlayer.api.service.virtual.Guest; import java.util.ArrayList; import java.util.List; /** * This script sets the data that will be written to the configuration drive. * * Important Manual Page: * http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest/setUserMetadata * * @license <http://sldn.softlayer.com/article/License> * @authon SoftLayer Technologies, Inc. <sldn@softlayer.com> * @version 0.2.2 (master branch) */ public class SetUserMetadata { /** * This is the constructor, is used to set user metadata */ public SetUserMetadata() { // Declare your SoftLayer username and apiKey String username = "set me"; String apiKey = "set me"; // Create client ApiClient client = new RestApiClient().withCredentials(username, apiKey); Guest.Service guestService = Guest.service(client, new Long(206659875)); // Setting the medatada String metadataTest = "test1RcvRcv"; List<String> metadata = new ArrayList<String>(); metadata.add(metadataTest); try { boolean result = guestService.setUserMetadata(metadata); } catch (Exception e) { System.out.println("Error: " + e); } } /** * This is the main method which makes use of SetUserMetadata method. * * @param args * @return Nothing */ public static void main(String[] args) { new SetUserMetadata(); } } References:
-7649802 0is_numeric checks more:
-30289858 0 Is it possible to pull/push my local MYSQL db to the heroku postgresql db?Finds whether the given variable is numeric. Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part. Thus +0123.45e6 is a valid numeric value. Hexadecimal notation (0xFF) is allowed too but only without sign, decimal and exponential part.
I need to pull the heroku db to my local and also push my db to the heroku remote. Locally I have MYSQL and in heroku it is Postgresql. I found lot ways suggested in internet but none seems to be working and most of them are very old and things have changed.
Things tried:
heroku db:push - didnt work
$ heroku db:push ! `db:push` is not a heroku command. ! Perhaps you meant `pg:push`. ! See `heroku help` for a list of available commands. heroku pg:push : Here am not sure how to mention the source database (and i dont have a local db password)
$ heroku pg:push mysql://root:@localhost/app_development --app myapp Usage: heroku pg:push <SOURCE_DATABASE> <REMOTE_TARGET_DATABASE> push from SOURCE_DATABASE to REMOTE_TARGET_DATABASE REMOTE_TARGET_DATABASE must be empty. SOURCE_DATABASE must be either the name of a database existing on your localhost or the fully qualified URL of a remote database. Info:
$ heroku version heroku-toolbelt/3.37.0 (x86_64-linux) ruby/2.2.1 You have no installed plugins. OS : Ubuntu 14.04
$ heroku pg:info --app myapp === DATABASE_URL Plan: Hobby-dev Status: Available Connections: 1/20 PG Version: 9.4.1 Created: 2015-05-16 07:05 UTC Data Size: 6.7 MB Tables: 6 Rows: 0/10000 (In compliance) Fork/Follow: Unsupported Rollback: Unsupported
-20084919 0 $return_value = $driver->wait()->until($expectedCondition)
-35951605 0 Swift xcode two errors: load controller is not allowed and autoresize not equal to views window EDIT: If you need me to post more class programs just let me know in the comments.
Screenshot of what I'm trying to create: enter image description here
NOTE: There's no need to look at the code below if you decide to run the project because all the classes I posted below are inside the dropbox zipped project file.
Each of the squares on the bottom selects a different color and there's an invisible square that selects the type of shape off to the right of the green one. After the user selects one of these shapes, the user will be able to draw in a certain part of the screen.
Entire project: https://www.dropbox.com/s/rhj641yku230f3v/SwiftXcodeProejctTwoErrors6767.zip?dl=0
If you run the project, create an account, then click sign in, then click one of the rows, then click on one of the colored boxes (red and green squares) the app will crash and get the following error message:
2016-03-11 17:06:43.580 finalProject2[11487:1058358] <UIView: 0x7faba1677710; frame = (0 0; 414 736); autoresize = W+H; gestureRecognizers = <NSArray: 0x7faba1658d90>; layer = <CALayer: 0x7faba16563f0>>'s window is not equal to <finalProject2.RowTableViewController: 0x7faba165a3c0>'s view's window! File slot 1 File slot 2 File slot 3 File slot 4 File slot 5 File slot 6 File slot 7 File slot 8 File slot 9 File slot 10 File slot 11 File slot 12 2016-03-11 17:06:44.746 finalProject2[11487:1058358] Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior (<UIAlertController: 0x7faba16b7d60>) MainProject scene class:
import UIKit weak var FirstFileNameTextField: UILabel! enum ShapeType: String { case Line = "Line" case Ellipse = "Ellipse" case Rectangle = "Rectangle" case FilledEllipse = "Filled Ellipse" case FilledRectangle = "Filled Rectangle" case Scribble = "Scribble" } let shapes: [ShapeType] = [ .Line, .Ellipse, .Rectangle, .FilledEllipse, .FilledRectangle, .Scribble ] class MainProjectScene: UIViewController { var row: Row? @IBAction func PressedSaveAs(sender: UIButton) //this is the save as function that I would like to know how to change { //1. Create the alert controller. var alert = UIAlertController(title: "Name/rename your file:", message: "Enter a filename to name/rename and save your file", preferredStyle: .Alert) //2. Add the text field. You can configure it however you need. alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in textField.text = "Your file name" }) alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in let textField = alert.textFields![0] as UITextField print("Text field: \(textField.text)") // rows.cell.textLabel?.text = textField.text CurrentFileName = textField.text! rows[IndexPath.row].FileName = textField.text! rows[IndexPath.row].UserText = self.TextUserScrollEdit.text! })) // 4. Present the alert. self.presentViewController(alert, animated: true, completion: nil) // rows[indexPath.row].FileName = rows.cell.textLabel?.text // rows[i] = textField.text // if let detailViewController = segue.destinationViewController as? MainProjectScene { // if let cell = sender as? UITableViewCell { // if let indexPath = self.tableView.indexPathForCell(cell) { // detailViewController.row = rows[indexPath.row] } override func viewWillAppear(animated: Bool) { if let r = row { row!.FileName = r.FileName row!.QuartzImage = r.QuartzImage row!.UserText = r.UserText rows[IndexPath.row].UserText = self.TextUserScrollEdit.text! } } override func viewDidLoad() { super.viewDidLoad() TextUserScrollEdit.text = rows[IndexPath.row].UserText // FacebookButton.addTarget(self, action: "didTapFacebook", forControlEvents: .TouchUpInside) } @IBOutlet weak var TextUserScrollEdit: UITextView! @IBOutlet weak var NewFileButton: UIButton! @IBOutlet weak var TwoDQuartzButton: UIButton! @IBOutlet weak var YouTubeButton: UIButton! @IBOutlet weak var TwitterButton: UIButton! @IBOutlet weak var OpenFileButton: UIButton! @IBOutlet weak var SnapChatButton: UIButton! @IBOutlet weak var FacebookButton: UIButton! @IBAction func PressedTwoDQuartzButton(sender: UIButton) { } @IBAction func PressedSnapchatButton(sender: UIButton){ UIApplication.sharedApplication().openURL(NSURL(string: "https://www.snapchat.com/")!) } @IBAction func PressedYouTubeButton(sender: UIButton) { UIApplication.sharedApplication().openURL(NSURL(string: "https://www.youtube.com/")!) } @IBOutlet weak var InstagramButton: UIButton! @IBAction func PressedFacebookButton(sender: UIButton) { UIApplication.sharedApplication().openURL(NSURL(string: "http://www.facebook.com")!) } @IBAction func PressedInstagramButton(sender: UIButton) { UIApplication.sharedApplication().openURL(NSURL(string: "https://www.instagram.com/")!) } @IBAction func PressedTwitterButton(sender: UIButton) { UIApplication.sharedApplication().openURL(NSURL(string: "https://twitter.com/")!) } @IBOutlet weak var SaveAsButton: UIButton! // @IBOutlet weak var shapeButton: ShapeButton! @IBOutlet weak var canvas: CanvasView! @IBOutlet var colorButtons: [UIButton]! @IBOutlet weak var shapeButton: ShapeButton! @IBAction func selectColor(sender: UIButton) { UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: CGFloat(0.25), initialSpringVelocity: CGFloat(0.25), options: UIViewAnimationOptions.CurveEaseInOut, animations: { for button in self.colorButtons { button.frame.origin.y = self.view.bounds.height - 58 } sender.frame.origin.y -= 20 }, completion: nil) canvas.color = sender.backgroundColor! shapeButton.color = sender.backgroundColor! } @IBAction func selectShape(sender: ShapeButton) { let title = "Select Shape" let alertController = UIAlertController(title: title, message: nil, preferredStyle: .ActionSheet) for shape in shapes { let action = UIAlertAction(title: shape.rawValue, style: .Default) { action in sender.shape = shape self.canvas.shape = shape } alertController.addAction(action) } presentViewController(alertController, animated: true, completion: nil) } } ShapeButton class:
import UIKit class ShapeButton: UIButton { let shapes: [ShapeType] = [ .Line, .Ellipse, .Rectangle, .FilledEllipse, .FilledRectangle, .Scribble ] var shape: ShapeType = .Line { didSet { setNeedsDisplay() } } var color: UIColor = UIColor.blueColor() { didSet { setNeedsDisplay() } } // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code let context = UIGraphicsGetCurrentContext() CGContextSetStrokeColorWithColor(context, color.CGColor) CGContextSetFillColorWithColor(context, color.CGColor) CGContextSetLineWidth(context, 2) let x1: CGFloat = 5 let y1: CGFloat = 5 let x2: CGFloat = frame.width - 5 let y2: CGFloat = frame.height - 5 let rect = CGRect(x: x1, y: y1 + 5, width: frame.width - 10, height: frame.height - 20) switch shape { case .Line: CGContextMoveToPoint(context, x1, y1) CGContextAddLineToPoint(context, x2, y2) CGContextStrokePath(context) case .Ellipse: CGContextStrokeEllipseInRect(context, rect) case .Rectangle: CGContextStrokeRect(context, rect) case .FilledEllipse: CGContextFillEllipseInRect(context, rect) case .FilledRectangle: CGContextFillRect(context, rect) case .Scribble: CGContextMoveToPoint(context, x1, y1) CGContextAddCurveToPoint(context, x1 + 80, y1 - 10, // the 1st control point x2 - 80, y2 + 10, // the 2nd control point x2, y2) // the end point CGContextStrokePath(context) } } } Canvas view class:
import UIKit /* This program is for Xcode 6.3 and Swift 1.2 */ class CanvasView: UIView { var shape: ShapeType = .Line var color: UIColor = UIColor.blueColor() var first :CGPoint = CGPointZero var last :CGPoint = CGPointZero var points: [CGPoint] = [] // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code let context = UIGraphicsGetCurrentContext() CGContextSetStrokeColorWithColor(context, color.CGColor) CGContextSetFillColorWithColor(context, color.CGColor) let rect = CGRect(x: first.x, y: first.y, width: last.x - first.x, height: last.y - first.y) switch shape { case .Line: CGContextMoveToPoint(context, first.x, first.y) CGContextAddLineToPoint(context, last.x, last.y) CGContextStrokePath(context) case .Ellipse: CGContextStrokeEllipseInRect(context, rect) case .Rectangle: CGContextStrokeRect(context, rect) case .FilledEllipse: CGContextFillEllipseInRect(context, rect) case .FilledRectangle: CGContextFillRect(context, rect) case .Scribble: CGContextMoveToPoint(context, first.x, first.y) for p in points { CGContextAddLineToPoint(context, p.x, p.y) } CGContextStrokePath(context) } } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { if let touch = touches.first { first = touch.locationInView(self) last = first points.removeAll(keepCapacity: true) if shape == .Scribble { points.append(first) } setNeedsDisplay() } } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { if let touch = touches.first { last = touch.locationInView(self) if shape == .Scribble { points.append(last) } setNeedsDisplay() } } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { if let touch = touches.first { last = touch.locationInView(self) if shape == .Scribble { points.append(last) } setNeedsDisplay() } } override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { } }
-37700393 0 Using Draft.js with Reagent Does anyone have any luck adapting Draft.js for Reagent? There's pretty heavy editing issues if Draft.js is imported right away via reagent/adapt-react-class. Cursor jumps, disappearing symbols when you're typing, onChange calls with incorrect EditorState, you name it.
People are reporting problems like this in clojurians/reagent Slack channel, but it seems there's no solution so far.
Any help would be greatly appreciated.
-6381302 0 What type of security should I use if I wish to have a Forgotton Password ability on our website? AES?unfortunately, we've been requested to offer our users the ability to get an email sent to their registered account, their password .. if they have forgotten their password.
"Click here if you have forgotten your password"
So - this means i need to be able to DECRYPT the password. I don't like it, but that's the requirements. I'm used to use a SALT and HASHING a password with SHA1. then storing the salt and the hashed password into the repository.
Not sure what I should be doing if I wish to store the password which can be decrypted now. Is it more or less the same, but I should use AES instead?
Would love some help (and preferably code samples in .NET).
Cheers!
NOTE: Please don't turn this thread into a topic about HASHING vs DECRYPTING vs OpenAuth.
-4432210 0Appears to function as design.
-34888901 1 What's the best way to index a large number of arrays for calculating the cosine similarity?Goal: calculating the most relevant article using cosine similarity.
I have a function that will produce an array of scores of different topics for each article. For example:
[0.6, 0.7, 1] represent the article's scores in the [math, physics, bio] category.
With a given article, I will find the most relevant article by calculating the cosine similarity between the array of given article against the rest of the arrays of other articles.
I am thinking of using pickle to store my data and use numpy to calculate cosine similarity and it can find cosine similarity very fast with matrix manipulation. However I am running into a decision problem as of how to index each array with its corresponding article id.
I have thought of storing each array into a dictionary with the key as the article id and the value as the array. However, i think that will make it hard for me to calculate cosine similarity among a large number of arrays.
Any suggestions and ideas would be greatly appreciated, thanks!
-6478410 0If I have not wrongly misinterpreted your question, then here is what you want to do -
If I have correctly interpreted your problem, then...
Here is what my code does -
So if this is the directory structure of the .tgz file -
parent/ xyz.tgz/ a b c d.tgz/ x y z a.tgz/ # note if I extract this directly, it will replace/overwrite contents of the folder 'a' m n o p After extraction, the directory structure will be -
parent/ xyz.tgz xyz/ a b c d/ x y z a 1/ # it extracts 'a.tgz' to the folder 'a 1' as folder 'a' already exists in the same folder. m n o p Although I have provided plenty of documentation in my code below, I would just brief out the structure of my program. Here are the functions I have defined -
FileExtension --> returns the extension of a file AppropriateFolderName --> helps in preventing overwriting/replacing of already existing folders (how? you will see it in the program) Extract --> extracts a .tgz file (safely) WalkTreeAndExtract - walks down a directory (passed as parameter) and extracts all .tgz files(recursively) on the way down. I cannot suggest changes to what you have done, as my approach is a bit different. I have used extractall method of the tarfile module instead of the bit complicated extract method as you have done. (Just have glance at this - http://docs.python.org/library/tarfile.html#tarfile.TarFile.extractall and read the warning associated with using extractall method. I don`t think we will be having any such problem in general, but just keep that in mind.)
So here is the code that worked for me -
(I tried it for .tar files nested 5 levels deep (ie .tar within .tar within .tar ... 5 times), but it should work for any depth* and also for .tgz files.)
# extracting_nested_tars.py import os import re import tarfile file_extensions = ('tar', 'tgz') # Edit this according to the archive types you want to extract. Keep in # mind that these should be extractable by the tarfile module. def FileExtension(file_name): """Return the file extension of file 'file' should be a string. It can be either the full path of the file or just its name (or any string as long it contains the file extension.) Examples: input (file) --> 'abc.tar' return value --> 'tar' """ match = re.compile(r"^.*[.](?P<ext>\w+)$", re.VERBOSE|re.IGNORECASE).match(file_name) if match: # if match != None: ext = match.group('ext') return ext else: return '' # there is no file extension to file_name def AppropriateFolderName(folder_name, parent_fullpath): """Return a folder name such that it can be safely created in parent_fullpath without replacing any existing folder in it. Check if a folder named folder_name exists in parent_fullpath. If no, return folder_name (without changing, because it can be safely created without replacing any already existing folder). If yes, append an appropriate number to the folder_name such that this new folder_name can be safely created in the folder parent_fullpath. Examples: folder_name = 'untitled folder' return value = 'untitled folder' (if no such folder already exists in parent_fullpath.) folder_name = 'untitled folder' return value = 'untitled folder 1' (if a folder named 'untitled folder' already exists but no folder named 'untitled folder 1' exists in parent_fullpath.) folder_name = 'untitled folder' return value = 'untitled folder 2' (if folders named 'untitled folder' and 'untitled folder 1' both already exist but no folder named 'untitled folder 2' exists in parent_fullpath.) """ if os.path.exists(os.path.join(parent_fullpath,folder_name)): match = re.compile(r'^(?P<name>.*)[ ](?P<num>\d+)$').match(folder_name) if match: # if match != None: name = match.group('name') number = match.group('num') new_folder_name = '%s %d' %(name, int(number)+1) return AppropriateFolderName(new_folder_name, parent_fullpath) # Recursively call itself so that it can be check whether a # folder named new_folder_name already exists in parent_fullpath # or not. else: new_folder_name = '%s 1' %folder_name return AppropriateFolderName(new_folder_name, parent_fullpath) # Recursively call itself so that it can be check whether a # folder named new_folder_name already exists in parent_fullpath # or not. else: return folder_name def Extract(tarfile_fullpath, delete_tar_file=True): """Extract the tarfile_fullpath to an appropriate* folder of the same name as the tar file (without an extension) and return the path of this folder. If delete_tar_file is True, it will delete the tar file after its extraction; if False, it won`t. Default value is True as you would normally want to delete the (nested) tar files after extraction. Pass a False, if you don`t want to delete the tar file (after its extraction) you are passing. """ tarfile_name = os.path.basename(tarfile_fullpath) parent_dir = os.path.dirname(tarfile_fullpath) extract_folder_name = AppropriateFolderName(tarfile_name[:\ -1*len(FileExtension(tarfile_name))-1], parent_dir) # (the slicing is to remove the extension (.tar) from the file name.) # Get a folder name (from the function AppropriateFolderName) # in which the contents of the tar file can be extracted, # so that it doesn't replace an already existing folder. extract_folder_fullpath = os.path.join(parent_dir, extract_folder_name) # The full path to this new folder. try: tar = tarfile.open(tarfile_fullpath) tar.extractall(extract_folder_fullpath) tar.close() if delete_tar_file: os.remove(tarfile_fullpath) return extract_folder_name except Exception as e: # Exceptions can occur while opening a damaged tar file. print 'Error occured while extracting %s\n'\ 'Reason: %s' %(tarfile_fullpath, e) return def WalkTreeAndExtract(parent_dir): """Recursively descend the directory tree rooted at parent_dir and extract each tar file on the way down (recursively). """ try: dir_contents = os.listdir(parent_dir) except OSError as e: # Exception can occur if trying to open some folder whose # permissions this program does not have. print 'Error occured. Could not open folder %s\n'\ 'Reason: %s' %(parent_dir, e) return for content in dir_contents: content_fullpath = os.path.join(parent_dir, content) if os.path.isdir(content_fullpath): # If content is a folder, walk it down completely. WalkTreeAndExtract(content_fullpath) elif os.path.isfile(content_fullpath): # If content is a file, check if it is a tar file. # If so, extract its contents to a new folder. if FileExtension(content_fullpath) in file_extensions: extract_folder_name = Extract(content_fullpath) if extract_folder_name: # if extract_folder_name != None: dir_contents.append(extract_folder_name) # Append the newly extracted folder to dir_contents # so that it can be later searched for more tar files # to extract. else: # Unknown file type. print 'Skipping %s. <Neither file nor folder>' % content_fullpath if __name__ == '__main__': tarfile_fullpath = 'fullpath_path_of_your_tarfile' # pass the path of your tar file here. extract_folder_name = Extract(tarfile_fullpath, False) # tarfile_fullpath is extracted to extract_folder_name. Now descend # down its directory structure and extract all other tar files # (recursively). extract_folder_fullpath = os.path.join(os.path.dirname(tarfile_fullpath), extract_folder_name) WalkTreeAndExtract(extract_folder_fullpath) # If you want to extract all tar files in a dir, just execute the above # line and nothing else. I have not added a command line interface to it. I guess you can add it if you find it useful.
Here is a slightly better version of the above program -
http://guanidene.blogspot.com/2011/06/nested-tar-archives-extractor.html
You probably want to move your whiteLine subview initialization to initWithStyle:reusedIdentifier: Currently you set up the alpha before it gets instantiated. Also, you're creating a new view every time drawRect: is called, which definitely is a no-no as well.
I'm not currently at the compiler, but something like this should solve your issue:
Note that I also added the autorelease call to your whiteLine subview (I assume it is a retained property). You may want to consider using ARC if you're not comfortable with Cocoa Memory Management. Otherwise I suggest re-reading Apple's Memory Management guide and possibly excellent Google Objective-C Code Style Guide
In BaseCell.m:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)identifier { self = [super initWithStyle:style reuseIdentifier:identifier]; if (self) { self.whiteLine = [[[UIView alloc] initWithFrame:CGRectMake(0.0, self.frame.size.height-1.0, self.frame.size.width, 1.0)] autorelease]; self.whiteLine.backgroundColor = [UIColor whiteColor]; [self addSubview:self.whiteLine]; } return self; } - (void)dealloc { self.whiteLine = nil; [super dealloc]; } - (void)rowIsOdd:(BOOL)isOdd { self.whiteLine.alpha = (isOdd ? 0.7 : 0.3); }
-23030458 0 L2 and L3 caches also have cache lines that are smaller than a virtual memory system page. The size of L2 and L3 cache lines is greater than or equal to the L1 cache line size, not uncommonly being twice that of the L1 cache line size.
For recent x86 processors, all caches use the same 64-byte cache line size. (Early Pentium 4 processors had 64-byte L1 cache lines and 128-byte L2 cache lines.)
IBM's POWER7 uses 128-byte cache blocks in L1, L2, and L3. (However, POWER4 used 128-byte blocks in L1 and L2, but sectored 512-byte blocks in the off-chip L3. Sectored blocks provide a valid bit for subblocks. For L2 and L3 caches, sectoring allows a single coherence size to be used throughout the system.)
Using a larger cache line size in last level cache reduces tag overhead and facilitates long burst accesses between the processor and main memory (longer bursts can provide more bandwidth and facilitate more extensive error correction and DRAM chip redundancy), while allowing other levels of cache and cache coherence to use smaller chunks which reduces bandwidth use and capacity waste. (Large last level cache blocks also provide a prefetching effect whose cache polluting issues are less severe because of the relatively high capacity of last level caches. However, hardware prefetching can accomplish the same effect with less waste of cache capacity.) With a smaller cache (e.g., typical L1 cache), evictions happen more frequently so the time span in which spatial locality can be exploited is smaller (i.e., it is more likely that only data in one smaller chunk will be used before the cache line is evicted). A larger cache line also reduces the number of blocks available, in some sense reducing the capacity of the cache; this capacity reduction is particularly problematic for a small cache.
-22050293 0You're very close actually:
columns.Bound(property => property.neatProperty).Width(38).EditorTemplateName("neatPropertyDropDownList").Title("NeatProperty") And then in a separate view called "neatPropertyDropDownList.cshtml"
@using System.Collections; @(Html.Kendo().DropDownList() .Name("NeatProperty") .DataTextField("Value") .DataValueField("Text") .BindTo("don't forget to bind!") )
-13918646 0 presentRenderbuffer using memory? I have simple drawing code like the following - repeated calls to draw several objects, followed by one call to glBindRenderbufferOES and one call to presentRenderbuffer -
Objects draw fine, BUT - the call to presentRenderBuffer allocates a good amount of memory with each call
I've generated and bound frame and render buffers - once - then never really do anything with them after that -
Should I be clearing my buffers after each call to presentRenderBuffer? Or is there some other way to give back memory after calling?
// these four calls made for each object Loop over objects glVertexPointer(3, GL_FLOAT, 0, ... glTexCoordPointer(2, GL_FLOAT, ... glNormalPointer(GL_FLOAT, 0, ... glDrawArrays(GL_TRIANGLES, 0,... // then, one-time call to these glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer); [context presentRenderbuffer:GL_RENDERBUFFER_OES];
-19990356 0 how to parse multiple file names and get relevant information in C# asp aspx I've been trying to figure out a way for the program to read all of the files from the path or zip file as input. Than read all of the file names inside of the input folder and split it so I can get information such as what is product id and chip name. Than store the pdf file in the correct db that matches with the product id and chip name.
The product id would be KHSA1234C and chip name LK454154.
Example File name: N3405-H-KAD_K-KHSA1234C-542164143_LK454154_GFK.pdf
public void btnUploadAttach_Click(object sender, EventArgs e) { string fName = this.FileUploadCFC.FileName; string path = @"C:\mydir\"; string result; result = Path.GetFileNameWithoutExtension(fName); Console.WriteLine("GetFileNameWithoutExtension('{0}') return '{1}'", fName, result); result = Path.GetFileName(path); Console.WriteLine("GetFileName('{0}') return '{1}'", path, result); string[] sSplitFileName = fName.ToUpper().Split("-".ToCharArray()); foreach (char file in fName) { try { result = sSplitFileName[0] + "_" + sSplitFileName[1] + "-" + sSplitFileName[2] + "_" + sSplitFileName[3] + "_" + sSplitFileName[4] + "_" + sSplitFileName[5] + "_" + sSplitFileName[6]; } catch { return; } } } I don't know if I'm on the right track or not. Can someone help me? Thank you.
-3044038 0You can download this sample application mentioned in this blog. It runs on GlassFish but it is an Eclipse project. You can easily import the Eclipse project into NetBeans.
-533370 0Thread.Abort will close the thread, of course, as it will call Win32 TerminateThread.
Outcome of this action will depend on how your API likes to be closed by TerminateThread.
If your method is called somthing like NuclearPlant.MoveRod() or Defibrillator.Shock(), I'd rather wait these 30 seconds.
This method gives no chance to the victim to do some cleanup:
TerminateThreadis used to cause a thread to exit. When this occurs, the target thread has no chance to execute any user-mode code. DLLs attached to the thread are not notified that the thread is terminating. The system frees the thread's initial stack.
As stated in MSDN:
-354302 0
TerminateThreadis a dangerous function that should only be used in the most extreme cases. You should callTerminateThreadonly if you know exactly what the target thread is doing, and you control all of the code that the target thread could possibly be running at the time of the termination. For example,TerminateThreadcan result in the following problems:
- If the target thread owns a critical section, the critical section will not be released.
- If the target thread is allocating memory from the heap, the heap lock will not be released.
- If the target thread is executing certain kernel32 calls when it is terminated, the kernel32 state for the thread's process could be inconsistent.
- If the target thread is manipulating the global state of a shared DLL, the state of the DLL could be destroyed, affecting other users of the DLL.
We used to do this years ago for a 4GL macro-compiler; if you put the macro library and support libraries and your code on a RAM disk, compiling an application (on an 80286) would go from 20 minutes to 30 seconds.
-6544387 0I think you have to see Density Considerations for Preventing from Scaling.
The easiest way to avoid pre-scaling is to put the resource in a resource directory with the nodpi configuration qualifier. For example:
res/drawable-nodpi/icon.png When the system uses the icon.png bitmap from this folder, it does not scale it based on the current device density.
From http://developer.android.com/guide/practices/screens_support.html#DensityConsiderations
-28649728 0 Devexpress LookUpEdit - serach second column by value meberI want to know it is posible to filters **LookUpEdit ** dropdown list by the column that corresponds to the ValueMember value.
LookUpEdit.DataSource = ds.Tables(0) LookUpEdit.ValueMember = ds.Tables(0).Columns("VALUE").Caption.ToString LookUpEdit.DisplayMember = ds.Tables(0).Columns("DISPLAYtext").Caption.ToString LookUpEdit.View.FocusedRowHandle = DevExpress.XtraGrid.GridControl.AutoFilterRowHandle LookUpEdit.AllowFocused = True LookUpEdit.CloseUpKey = New KeyShortcut(Keys.Add) LookUpEdit.NullText = "" I using devexpress 14.2.3. and vb.net
-3164525 0Also you can create something like:
public class JqGridJsonData { public int Total {get;set;} public int Page {get;set;} etc } And serialize this to json with Json.NET http://james.newtonking.com/pages/json-net.aspx
-20753449 0To do this, you could e.g. use a bool-query with a should to weigh in a span_first-query which in turn has a span_multi
Here is a runnable example you can play with: https://www.found.no/play/gist/8107157
#!/bin/bash export ELASTICSEARCH_ENDPOINT="http://localhost:9200" # Index documents curl -XPOST "$ELASTICSEARCH_ENDPOINT/_bulk?refresh=true" -d ' {"index":{"_index":"play","_type":"type"}} {"title":"Female"} {"index":{"_index":"play","_type":"type"}} {"title":"Female specimen"} {"index":{"_index":"play","_type":"type"}} {"title":"Microscopic examination of specimen from female"} ' # Do searches # This will match all documents. curl -XPOST "$ELASTICSEARCH_ENDPOINT/_search?pretty" -d ' { "query": { "prefix": { "title": { "prefix": "femal" } } } } ' # This matches only the two first documents. curl -XPOST "$ELASTICSEARCH_ENDPOINT/_search?pretty" -d ' { "query": { "span_first": { "end": 1, "match": { "span_multi": { "match": { "prefix": { "title": { "prefix": "femal" } } } } } } } } ' # This matches all, but prefers the one's with a prefix match. # It's sufficient that either of these match, but prefer that both matches. curl -XPOST "$ELASTICSEARCH_ENDPOINT/_search?pretty" -d ' { "query": { "bool": { "should": [ { "span_first": { "end": 1, "match": { "span_multi": { "match": { "prefix": { "title": { "prefix": "femal" } } } } } } }, { "match": { "title": { "query": "femal" } } } ] } } } '
-9713620 0 You are not changing which object is being referred to by the parameter (which is not allowed here). Instead you are changing the state of the object (which is allowed here).
In other words, when you pass your e1 EmployeeBean object into the method, the x parameter refers to the same object that e1 refers to, and within the method, this cannot change, and so you can't do this:
public EmployeeBean changeFinalvalue(final EmployeeBean x) { x = new EmployeeBean(); // changing the reference is not allowed! return x; } But what you're doing -- changing the state of the object -- is allowed.
The only way that I know to prevent problems like this is to make a deep copy of the object passed in as parameter and work on the copy/clone object. You could also make the EmployeeBean immutable, but then it wouldn't be much of a Bean, now would it?
Edit: I figured that this question has had to have been asked here many times, and on a little searching, I've found that of course it has. Please look at these links for a good discussion on this. Note that this is a general issue about final variables whether they are method parameters or class fields:
java-final-keyword-for-variables
java-final-modifier
Just a thought(hadn't tried practically)
SELECT * FROM TABLE_NAME having max(na) = na GROUP BY nm_mp If it works or doesn't work, do tell me. Its for all category.
For just that two category, try this.
SELECT * FROM TABLE_NAME WHERE nm_mp IN('matematika', 'bahasa inggris') having max(na) = na GROUP BY nm_mp
-2452414 0 http handlers not working on web server but works on localhost i have a couple of xml files in my asp.net web application that i don't want anyone to access other than my server side code. this is what i tried..
<add verb="*" path="*.xml" type="System.Web.HttpForbiddenHandler" /> i wrote this inside the <httpHandlers>
it works well on the localhost but not in the server... the server without any hesitation displays the xml file... i have no idea how to proceed...
thanks in advance..:)
Update: the server has IIS6, windows server 2003
-18833771 0"android:process" and "android:taskAffinity" allows you to have different processes and affinities within the same package (application).
"android:multiprocess" simply means if you want to allow the activity to have a different process-id. This only works within the same app, not when the activity is started from a different a different package.
What are you exactly trying to do? If you want to share the same context and private files, you should use sharedUserId instead (you have to sign them using the same certificate as well).
-12156550 0if i'd understood your correctly, python example:
>>> a=[1,2,3,4,5,6,7,8,9,0] >>> >>> >>> len_a = len(a) >>> b = [1] >>> if len(set(a) - set(b)) < len_a: ... print 'this integer exists in set' ... this integer exists in set >>> math base: http://en.wikipedia.org/wiki/Euler_diagram
-1953036 0You can always use a Python property to accomplish your goal:
class ClassA(db.Model): name = db.StringProperty() def __get_classBdeleted(self): return self.classB_set.filter('deleted_flag =', 'True') classBdeleted = property(__get_classBdeleted) class ClassB(db.Model): name = db.StringProperty() deleted_flag = db.BooleanProperty() classA = db.ReferenceProperty(ClassA)
-1669137 0 The Audiere library makes this extremely easy to do. Here's a nearly complete C# program to generate the DTMF tone for the "1" button:
AudioDevice device = new AudioDevice(); OutputStream tone1a = device.CreateTone(697); // part A of DTMF for "1" button OutputStream tone1b = device.CreateTone(1209); // part B tone1a.Volume = 0.25f; tone1b.Volume = 0.25f; tone1a.Play(); tone1b.Play(); Thread.Sleep(2000); // when tone1a stops, you can easily tell that the tone was indeed DTMF tone1a.Stop(); To use Audiere in C#, the easiest way to get up and running is to use Harald Fielker's C# binding (which he claims works on Mono and VS; I can confirm it works in the both full version of VS2005 and using the separate Express 2008 versions of C# and VC++). You'll need to download the Win32 Audiere DLL, lib, and header (which are all in the same zip) and you'll need to build the C# binding from source using both VC++ and C#.
One of the nice benefits of using Audiere is that the calls are non-blocking. You don't have to wait for tone1a to stop playing before you start tone1b, which is clearly a necessity for playing complex tones. I am not aware of any hard upper limits on how many simultaneous output streams you can use, so it's probably whatever your hardware/OS supports. By the way, Audiere can also play certain audio files (MP3, WAV, AIFF, MOD, S3M, XM, IT by itself; Ogg Vorbis, Flac, Speex with external libraries), not just pure generated tones.
One possible downside is that there is a slightly audible "click" as you start or stop an individual tone; it's not noticeable if you add one tone to an already playing tone. The easiest workaround I've found for that is to slowly ramp the tone's volume up or down when you're turning the tone on or off, respectively. You might have to play around with the ramp speed to get it to sound "just right".
Note that Audiere is LGPL-licensed, and the binding has no license attached to it. You'll have to consult your legal team or try to get a hold of Harald if you want to use his binding in a commercial product; or you could just make your own binding and avoid the hassle.
Using Visual C++ Express 2008, open up bindings/csharp/libaudieresharpglue/vc8.0/libaudieresharpglue.sln. VC++ will automatically convert the solution to a VS9 solution.
In another folder, you should have the Audiere package from Sourceforge. Under your VC++ project properties, go to Configuration Properties > C/C++ > General, and make sure you have path/to/audiere-1.9.4-win32/include in your "Additional Include Directories." Then, in that same window, go to Linker > General and make sure you have /path/to/audiere-1.9.4-win32/lib in your "Additional Library Directories." Then, you should be able to build the project (preferably in Release mode) and this output libaudieresharpglue.dll in your vc8.0/Release folder.
Next, open up Visual C# Express 2008. Open up bindings\csharp\test\vc8.0\AudiereCSharpTest.sln and let it convert the solution. The project should build fine, but then you will get an error when you run it. That's fine; in your csharp/test/vc8.0/bin/Release folder, you need to add both libaudieresharpglue.dll from the VC++ solution and audiere.dll from the package from Sourceforge.
Now, you should be able to build and run AudiereCSharpTest. Note that by default, #define stream_test is not commented out at the top of AudiereTest.cs, and that will reference a file that is not on your hard drive. You can simply comment out that #define and uncomment noise_test or square_test.
That should cover it; if I missed any details, hopefully they are small enough to get by on your own :)
-35563424 0Try calling
chart.notifyDataChanged()
and
chart.invalidate()
After setting the offsets.
-29108765 0 How do I AJAX post to an MVC action from within a javascript file?The following code exists in a file called job.js. When I run this code against localhost everything behaves properly. When I do so against my intranet server where there is an application name I get a 404.
Job.updateJob = function () { $.post('/Builder/ListJobItems', function (data) { ... }); } I would love to use @Url.Action() but as I said this is javascript (.js) file. I am also aware of the hack where you put a data value onto the body element, but for architectural reasons, I want this code to be decoupled from the DOM. It is a data acquisition engine, why should it even know what a DOM is.
I would be fine with a solution that parses window.location in some fashion, but the problem that I am having their is that I need a solution that will work everywhere.
What frustrates me most is that I can't see how this isn't a problem everyone would face. Why isn't there a solution? Does everyone just put all of their JavaScript into the razor view? Does no one isolate code into modules anymore? I can't believe either of these is true, and yet there don't seem to be any forth coming solutions for this. I am at a loss.
-11885973 0 how to automatically make new file with mvimWhen I run mvim . it opens NERDTree but doesnt open a new file/buffer.
How might I accomplish this? Ideally when you type mvim . from terminal it would open MacVim, close NERDtree, and open a new buffer
I'm not sure if this is possible but is there a way that if I run mvim . from the command line multiple times it wouldn't open vim in a new window each time?
You want to add 1 instead of i on each for loop iteration.
cal.add(Calendar.SECOND, 1);
-15094660 0 Recommended way to login to a website through an application My application has to login to a website by posting a form, and keep track of the cookie provided till the application is terminated.
I have achieved this using the "WebView" class. I have doubts on weather this is the most efficient way to achieve this as I do not wish to display any webpages but Simply submitting another form once logged in.
Is their any other solution/Classes that can handle this with less traffic (smaller footprint)?
-28577699 0You don't have to call Flush() on Close()/Dispose(), FileStream will do it for you as you can see from its source code:
http://referencesource.microsoft.com/#mscorlib/system/io/filestream.cs,e23a38af5d11ddd3
[System.Security.SecuritySafeCritical] // auto-generated protected override void Dispose(bool disposing) { // Nothing will be done differently based on whether we are // disposing vs. finalizing. This is taking advantage of the // weak ordering between normal finalizable objects & critical // finalizable objects, which I included in the SafeHandle // design for FileStream, which would often "just work" when // finalized. try { if (_handle != null && !_handle.IsClosed) { // Flush data to disk iff we were writing. After // thinking about this, we also don't need to flush // our read position, regardless of whether the handle // was exposed to the user. They probably would NOT // want us to do this. if (_writePos > 0) { FlushWrite(!disposing); // <- Note this } } } finally { if (_handle != null && !_handle.IsClosed) _handle.Dispose(); _canRead = false; _canWrite = false; _canSeek = false; // Don't set the buffer to null, to avoid a NullReferenceException // when users have a race condition in their code (ie, they call // Close when calling another method on Stream like Read). //_buffer = null; base.Dispose(disposing); } }
-2426070 0 Looks like I over-thought this one a bit. Turns out target is just the target child you are adding and that is just another way to define it as opposed to defining it as an inline attribute to the AddChild tag.
-31622387 0The Streams from the linked answer seem like an analog of core.async channels.
Instead of removing all listeners each event maybe pass in a channel that has event details put to it. The same channel should go to the button's logic handler where it will repeatedly be taken from.
-33367125 0 how to undo a git stash to get to a position before the stashI did a git stash and lost changes to some of my files. There were a number of files that changed in the local repo before I did the git stash. After the stash it changed some of the files. how can I undo the stash to get the previous state before doing git stash without losing all of my files that are not changed my stash
-10255557 0Yes CubeGrid is available to Power and Enterprise license holders from Isomorphic. Check out the CubeGrid and Facets classes and take a look at the show cases on the smartgwt pages.
http://www.smartclient.com/smartgwtee/showcase/#cube_analytics and follow examples.
If you are just able to use ListGrid you can achieve the same thing through iterating through the records. If you are able to use a database you can enter customSQL
such as:
<operationBindings> <operationBinding operationType="fetch" operationId="VEP_AREA_RECORD"> <customSQL> SELECT * FROM (SELECT SUBSTRING(MeasurementTime,7,4) [Year], CASE SUBSTRING(Time,1,2) WHEN '01' THEN 'Jan' WHEN '02' THEN 'Feb' WHEN '03' THEN 'Mar' WHEN '04' THEN 'Apr' WHEN '05' THEN 'May' WHEN '06' THEN 'Jun' WHEN '07' THEN 'Jul' WHEN '08' THEN 'Aug' WHEN '09' THEN 'Sep' WHEN '10' THEN 'Oct' WHEN '11' THEN 'Nov' WHEN '12'THEN 'Dec' END as [Month], [value] , [col1] as col1, col1 [col1_name], col2 [col2_name], col3 [col3], [col4_name] FROM your_table WHERE MeasurementValue IS NOT NULL) TableDate PIVOT <what you want in rows> FOR [Month] IN ( [Jan],[Feb],[Mar],[Apr], [May],[Jun],[Jul],[Aug], [Sep],[Oct],[Nov],[Dec] ) ) AS PivotTable ORDER BY groupCol1, groupCol2 </customSQL> clearly these columns could be actual values in your records/db or derived (in my case derived from the datefield. I"m not a SQL guru so if there's a better way I'd love to hear it.
In the above exmple the output would be
[jan] [feb] [mar] etc.....in your case [col1_valA] [col2_val1] valx valy [col1_valB] [col2_val2
-7146909 0 Validate HTML form with JQuery Can someone see where I'm going wrong with this form validation? I was using an example I found online and it does not work for me.
I want to validated the input fields with the jquery before passing it on to the server side script. It supposed to print error message next to the field where the user is missing an input.
Here's the code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Register</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-5"> <link rel="stylesheet" type="text/css" href="style1.css" /> <link rel="stylesheet" type="text/css" href="forms.css" /> <script src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#registerform").validate({ rules: { username: "required", firstname: "required", email: {// compound rule required: true, passwd: true, email: true, }, username:{ username: true }, url: { url: true }, comment: { required: true } }, messages: { comment: "Please enter a comment." } }); }); </script> <style type="text/css"> label { width: 10em; float: left; } label.error { float: none; color: red; padding-left: .5em; vertical-align: top; } p { clear: both; } .submit { margin-left: 12em; } em { font-weight: bold; padding-right: 1em; vertical-align: top; } </style> </head> <body> Please register below <p /> <form action=" " id="registerform" method="POST"> <table cellspacing="9"> <tr><td><b>Username:</b></td><td><input type="text" name="username" size="30"></td></tr> <tr><td><b>First name:</b></td><td><input type="text" name="firstname" size="30"/></td></tr> <tr><td><b>Surname:</b> </td><td><input type="text" name="lastname" size="30"/></td></tr> <tr><td><b>Email : </b> </td><td><input type="text" name="email" size="30"/></td></td></tr> <tr><td><b>Password :</b> </td><td><input type="password" name="passwd" size="30"/></td></tr> <tr><td><b>Telephpone:</b></td><td><input type="text" name="telephone" size="30"/></td></td></tr> <tr><td><b>House No:</b></td><td><input type="text" name="ad1" size="30"/></td></td></tr> <tr><td><b>Street Name:</b></td><td><input type="text" name="street" size="30"/></td></tr> <tr><td><b>Town/ City:</b></td><td><input type="text" name="town" size="30"/></td></tr> <tr><td><b>Post code:</b></td><td><input type="text" name="pcode" size="30"/></td></tr> </table> <p /> <input class="submit" type="submit" value="Sign Up!" /> <input type="reset" value ="Clear Form" onClick="return confirm('Are you sure you want to reset the form?')"> </form> </body> Here's the code the original code that I got from a website somewhere and it works. But I can't seem to use the example in my code.
<html> <head> <title>Simple Form Validation</title> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#form2").validate({ rules: { name: "required",// simple rule, converted to {required:true} email: {// compound rule required: true, email: true }, url: { url: true }, comment: { required: true } }, messages: { comment: "Please enter a comment." } }); }); </script> </head> <body> <form id="form2" method="post" action=""><br /> Name * <input type="text" name="name" /> <br /> E-Mail *<input type="text" name="email" /> <br /> URL <input type="text" name="url" /> <br /> Your comment * <textarea name="comment" ></textarea> <br /> <input class="submit" type="submit" value="Submit"> </form> </body> </html> Update: Thanks to @Usman it's now working. One more question though, is it possible to change the default error message instead of the 'This field is required' ?
Thanks
-37979276 0 Google Maps: How to draw labels (country, city names, etc.) over my overlayI need to draw some graphics over google maps. Graphics is not always transparent, so I'd like to draw text labels (country names, city names, etc.) over my graphics.
For graphics I use overlay map type , it is shown over base map. But I failed to draw labels over it?
I guessed that there shall be a way to draw base map twice, with different style settings (so I style map with not labels, put my overlay, and then put overlay with roadmap with labels only), but it does not seem like I can use basic map types as overlay ones. Another way I see is to manually get tile with labels only by composing URL. This works, but as far as I understand accessing map tiles directly is prohibited by ToS.
Is there a working and, well, legal way to do that?
Here is jsfiddle which illustrates URL composing solution: https://jsfiddle.net/GRaAL/jyr81p2c/
// here is how I get google maps tile with labels only function getLabelsOnlyTile(coord, zoom) { return "https://maps.googleapis.com/maps/vt?pb=!1m5!1m4!1i" + zoom + "!2i" + (coord.x) + "!3i" + (coord.y) + "!4i512!2m3!1e0!2sm!3i353022921!3m14!2sen!3sUS!5e18!12m1!1e47!12m3!1e37!2m1!1ssmartmaps!12m4!1e26!2m2!1sstyles!2zcC52Om9mZixzLmU6bHxwLnY6b24!4e0"; }
-18451644 0 ! is used to reference one member of a collection ... CollectionName!MemberName
Forms is the name of a collection whose members are Form objects, and includes those forms which are currently open in your Access session.
A Form has a collection of Control objects. So appending !ControlName to the form reference gets you a reference to that control.
So Forms![HiddenUserCheck]![txtStatus] refers to a control named txtStatus in a form named HiddenUserCheck which is open in your Access session.
What you get from that reference is the control's default property, Value ... the value contained in that control.
Let's say we have structure
struct MyStruct { public string a; } When we assign it to the new variable what will be happened with the string? So for example, we expect that string should be shared when structs are copied in the stack. We're using this code to test it, but it returns different pointers:
var a = new MyStruct(); a.a = "test"; var b = a; IntPtr pA = Marshal.StringToCoTaskMemAnsi(a.a); IntPtr pB = Marshal.StringToCoTaskMemAnsi(b.a); Console.WriteLine("Pointer of a : {0}", (int)pA); Console.WriteLine("Pointer of b : {0}", (int)pB); The question is when structs are copied in the stack and have string inside did it share the string or the string is recreated?
[UPDATE]
We also tried this code, it returns different pointers as well:
char charA2 = a.a[0]; char charB2 = b.a[0]; unsafe { var pointerA2 = &charA2; var pointerB2 = &charB2; Console.WriteLine("POinter of a : {0}", (int)pointerA2); Console.WriteLine("Pointer of b : {0}", (int)pointerB2); }
-35150355 0 You might be able to use UIManager.put("TabbedPane.contentAreaColor", new Color(255, 255, 0, 100));

import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TransparentTabbedPaneTest { public JComponent makeUI() { Color bgc = new Color(110, 110, 0, 100); Color fgc = new Color(255, 255, 0, 100); UIManager.put("TabbedPane.shadow", fgc); UIManager.put("TabbedPane.darkShadow", fgc); UIManager.put("TabbedPane.light", fgc); UIManager.put("TabbedPane.highlight", fgc); UIManager.put("TabbedPane.tabAreaBackground", fgc); UIManager.put("TabbedPane.unselectedBackground", fgc); UIManager.put("TabbedPane.background", bgc); UIManager.put("TabbedPane.foreground", Color.WHITE); UIManager.put("TabbedPane.focus", fgc); UIManager.put("TabbedPane.contentAreaColor", fgc); UIManager.put("TabbedPane.selected", fgc); UIManager.put("TabbedPane.selectHighlight", fgc); UIManager.put("TabbedPane.borderHightlightColor", fgc); JTabbedPane tabs = new JTabbedPane(); JPanel tab1panel = new JPanel(); tab1panel.setBackground(new Color(0, 220, 220, 50)); JPanel tab2panel = new JPanel(); tab2panel.setBackground(new Color(220, 0, 0, 50)); JPanel tab3panel = new JPanel(); tab3panel.setBackground(new Color(0, 0, 220, 50)); JCheckBox cb = new JCheckBox("setOpaque(false)"); cb.setOpaque(false); tab3panel.add(cb); tab3panel.add(new JCheckBox("setOpaque(true)")); tabs.addTab("Tab 1", tab1panel); tabs.addTab("Tab 2", tab2panel); tabs.addTab("Tab 3", new AlphaContainer(tab3panel)); JPanel p = new JPanel(new BorderLayout()) { private Image myBG = new ImageIcon(getClass().getResource("test.png")).getImage(); @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(myBG, 0, 0, getWidth(), getHeight(), this); } }; p.add(tabs); p.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); return p; } public static void main(String... args) { EventQueue.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); f.getContentPane().add(new TransparentTabbedPaneTest().makeUI()); f.setSize(320, 240); f.setLocationRelativeTo(null); f.setVisible(true); }); } } //https://tips4java.wordpress.com/2009/05/31/backgrounds-with-transparency/ class AlphaContainer extends JComponent { private JComponent component; public AlphaContainer(JComponent component) { this.component = component; setLayout( new BorderLayout() ); setOpaque( false ); component.setOpaque( false ); add( component ); } /** * Paint the background using the background Color of the * contained component */ @Override public void paintComponent(Graphics g) { g.setColor( component.getBackground() ); g.fillRect(0, 0, getWidth(), getHeight()); } }
-18892002 0 I should expose my "properties" inside a provider and access them inside config. Usage of provider.
-10887980 1 libjpeg.so.62: cannot open shared object file: No such file or directoryI am trying to do some image processing with python and the PIL. I was having a problem that I wouldn't correctly import the _imaging folder so I did a reinstall and now I am getting this problem:
libjpeg.so.62: cannot open shared object file: No such file or directory I did apt-get remove python-imaging in the command line and then apt-get install python-imaging and now it won't work in Eclipse. Any tips?
-15919755 0try using this
<TableLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="bottom" android:stretchColumns="*"> <TableRow android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center_horizontal"> <Button android:id="@+id/btnManualLookup" android:text="ABC" android:layout_height="wrap_content" android:layout_width="0dp" android:layout_weight="1" android:textColor="#000000" android:padding="20dip" android:gravity="center"/> <Button android:id="@+id/downloadcerti" android:text="DEF" android:layout_height="wrap_content" android:layout_width="0dp" android:layout_weight="1" android:textColor="#000000" android:padding="20dip" android:gravity="center"/> <Button android:id="@+id/settingsbutton" android:text="GHI" android:layout_height="wrap_content" android:layout_width="0dp" android:layout_weight="1" android:textColor="#000000" android:padding="20dip" android:gravity="center"/> </TableRow>
-13979689 0 LOAD DATA LOCAL INFILE php mysql I am getting error
#7890 - Can't find file 'C:UsersAdminDesktopBL postcodes.csv.zip'. here is the script
LOAD DATA LOCAL INFILE 'C:\Users\Admin\Desktop\BL postcodes.csv.zip' IGNORE INTO TABLE uk_pc FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (Postcode, Latitude, Longitude, Easting, Northing, GridRef, County, District, Ward, DistrictCode, WardCode, Country, CountyCode) i have tried to change folders and change permission also but same error ... (working on localhost server)
-33291969 0open notepad and type in
dir > dar.txt
Save as D.txt in the folder where the file you want to know the size of
Rename D.txt to D.bat
run D.bat
A file will be created called dar.txt
Open dar.txt with notepad and you will find all the files in that folder listed with their size.
-27547235 0When overriding a virtual method, you must keep the original "contract" of the method, which in your case is a string a variable.
In order to do what you want, you can create a virtual overload which takes two strings:
public class A { public virtual void DoSomething(string a) { // perform something } public virtual void DoSomething(string a, string b) { // perform something } } public class B : A { public override void DoSomething(string a, string b) { // perform something slightly different using both strings } } If what you want is to accept N strings in your method, you can use the params keyword:
public class A { public virtual void DoSomething(params string[] allStrings) { // Do something with the first string in the array // perform something } }
-15531922 0 package is a reserved word, don't use it as part of a package name. If you try to add a package with "package" as part of it in Eclipse, you will get an error message:
Invalid package name. 'package' is not a valid Java identifier Rename the package, then remove the import statement. You don't need to import a file that's in the same package as the one it's referenced in.
-33419570 0 jquery validate requires two clicks to submitI have a form that has two buttons. One to edit a specific candidate after the information has been submitted, another button to just submit and add another candidate. Since there are two buttons on the screen, I need to know which one was clicked so that I can escort the user down the right path.
I am using the jQuery Validation Plugin to help me validate the form before posting it. To prevent users from double clicking the button and submitting a duplicate candidate, I am disabling the button and changing the button to "Submitting" as demonstrated here:
/* This will change the button only if the form has passed and change the button to submitting and disable it */ submitHandler: function(form) { $('#saveandadd').click(function() { $('#saveandadd').val('Submitting...'); $('saveandadd', this).attr('disabled', 'disabled'); form.submit(); }); $('#saveandedit').click(function() { $("input[name='setvalue']").val('1'); $('#saveandedit').val('Submitting...'); $('saveandedit', this).attr('disabled', 'disabled'); form.submit(); So far this is nice as I can change the button that was clicked to submitting. However, I have noticed a strange problem. Either button requires two clicks to submit it.
I have setup a fiddle here: Form Validation that requires the first and last name to be filled in. You will be prompted as an error if those fields are not filled in.
Thanks in advance
-14450215 0First of all, this is how you do it:
var outer = function() { this.inner = { innermost: function() { alert("innermost"); } } } var outer = new outer; outer.inner.innermost(); The reason why it didn't work the way you did it is because you define a function inner - so outer.inner is a function. You could do var inner = new (outer.inner)(); and then call inner.innermost(); but that's obviously ugly and not what you want.
I am converting my nodejs project into typescript nodejs. I have changed the extensions of .js files to .ts, however now I am getting require() errors. To overcome this problem, I tried
import express from "express" However this gives me "Can not find module error". I have researched it and narrowed it down to the issue where I guess TypeScript needs express.d.ts file for detecting the Express module. However I couldn't find the express.d.ts file anywhere in my project. Which ultimately means I am missing something.
Can somebody point me in the right direction or perhaps help me resolve this problem?
-1808498 0Basically if a user gets any error other than 403 or 404 (most notable other than those is 500 which is sent if there's an exception) they'll be redirected to that page, which won't exist (And if you're in IIS7 integrated pipeline or have IIS6 wildcard mapped they'll then get bounced to FileNotFound.htm - otherwise they'll just see a standard 404).
It'd probably be nice to at least give the user a "Oh no! Something is wrong!" page.
-18327890 0ok, looks like sqlite either doesn't have what I need, or I am missing it. Here's what I came up with:
declare zorder as integer primary key autoincrement, zuid integer in orders table
this means every new row gets an ascending number, starting with 1
generate a random number:
rnd = int(random.random() * 1000000) # unseeded python uses system time
create new order (just the SQL for simplicity):
'INSERT INTO orders (zuid) VALUES ('+str(rnd)+')'
find that exact order number using the random number:
'SELECT zorder FROM orders WHERE zuid = '+str(rnd)
pack away that number as the new order number (newordernum)
clobber the random number to reduce collision risks
'UPDATE orders SET zuid = 0 WHERE zorder = '+str(newordernum)
...and now I have a unique new order, I know what the correct order number is, the risk of a read collision is reduced to negligible, and I can prepare that order without concern that I'm trampling on another newly created order.
Just goes to show you why DB authors implement sequences, lol.
-19245842 0std::endl calls flush stream while cout << "\n" does not flush the stream, so cout << "\n"; gain better performance, especially while you call it in loop.
§27.7.3.8 Standard basic_ostream manipulators
namespace std { template <class charT, class traits> basic_ostream<charT,traits>& endl(basic_ostream<charT,traits>& os); } 1 Effects: Calls os.put(os.widen(’\n’)), then os.flush().
-38094981 0 Linux checking shell command (bash) How can I check if a shell command ends with some text? For instance if I type
$ http://example.com/file.webm (ends with .webm) it will be automatically replaced with
$ wget http://example.com/file.webm Of course only if command consists of one part.
I'm using bash as my shell.
I have a concern is that I want from a given date to retrieve the start date of the week for example: 15/04/2015 So the beginning of the week will: 13/04/2015 (for me the beginning of the week is Monday).
thanks
-33252144 0 when to use Repository methods and when to use mongoTemplate?I am working on Spring data mongo with my Spring MVC application. I need to understand which is the correct way to improve performance if I wish to use multiple criteria's.
Repository methods? OrMongoTemplate/MongoOperations?Which is advisable to use to improve performance with many contional criteria's ?
-20501416 0LINQ statements return IEnumerable objects, and your method is returning a single Request object. In your case looks like you only need to return the first result of the LINQ statement.
Something like:
Dim pr = (From r In dc.Request From p In dc.Process.Where(Function(v) v.IdReq = r.IdReq And v.idProcess Is Nothing) Select New {Request = r}).FirstOfDefault Return pr
-19243938 0 Keep the text in textboxes saved I have these textboxes where the user enters data and then presses a button to process the data. Now the data entered by the user is alot and to give the user some slack I want to make it possible whenever you press the button, the application saves the data, so when you close the application and start it back up again the textboxes are filled with the last entered data.
I was thinking about using a .txt file to save the data. Only I have found some difficulties with this. One of the problems is that I keep getting a messagebox from the microsoft .NET Framework everytime I try to run my application. The messagebox says the Index was outside the bounds of the array. Even though I think my code doesn't exceed the bounds of my array.
And here is the code that I use:
First I declared an array and filled it with variables that contain the content of the textboxes:
string[]settings = new string[5]; settings[0] = openKey; settings[1] = secretKey; settings[2] = statusRequestPath; settings[3] = statusRequestAPI; settings[4] = setSeconds.ToString(); Then I use the following code to write the data to a text file.
using (StreamWriter writeFile = new StreamWriter(@"C:\Audio Silence Detector\AudioSilenceDetector.txt")) { foreach (string line in settings) { writeFile.WriteLine(line); } } And to put the text of the .txt file back in the application I have put this in the formload:
string[] lines = System.IO.File.ReadAllLines(@"C:\Audio Silence Detector\AudioSilenceDetector.txt"); tbOpenKey.Text = lines[0]; tbSecretKey.Text = lines[1]; tbStatusRequestPath.Text = lines[2]; tbStatusRequestAPI.Text = lines[3]; tbSeconds.Text = lines[4]; I changed my code to this and it seems to have fixed the issue I was having:
if (lines.LongLength == 5) { tbOpenKey.Text = lines[0]; tbSecretKey.Text = lines[1]; tbStatusRequestPath.Text = lines[2]; tbStatusRequestAPI.Text = lines[3]; tbSeconds.Text = lines[4]; }
-36050552 0 c3 scatter chart radius size This has been something that is boggling my mind and its so simple i feel like i should of cracked it already. I just want to use a data set to drive the radius of a scatter plot.
I have some test code listed below that has the radius right now tied to d.x When i try and attach it to d.r or even radius it just gives me NaN. What mistake am i making?
var chart = c3.generate({ point: { r: function(d) { return d.x *7 ; } }, data: { xs: { user: 'user_x', r: 'radius', }, columns: [ ["user_x", 1, 3.0, 10, 7], ["user", 0.2, 0.2, 0.2, 0.2], ["radius", 4, 5, 6, 7], ], type: 'scatter' }, });
JSfiddle https://jsfiddle.net/moschmo/war2pxs6/
-38451968 0its transparent , takes background colour
-5519075 0C does not support function overloading. C++ does.
And since you accidentally declared trapezoid_volume as trapezoid, you get a compiler error.
I have the following situation:
Base is a base class. T is a template that can assume any derived class of Base.
The underlying layer provide me data from Base class, that I need to convert to a specific class on the above layer (that layer where the code is written) to work on a user level.
Here is the code:
template <class T> class Access { std::vector<std::unique_ptr<T> getData(); } template <class T> std::vector<std::unique_ptr<T> getData() { /// Get data from below layer std::vector<std::unique_ptr<Base>> retData; retData = getDataFromBelowLayer(); /// Now I have to cast Base to T std::vector<std::unique_ptr<T>> retCastData; for (auto &item : retData) { std::unique_ptr<T> = static_cast<T>(item); <<---- NOT WORKING retCastData.push_back(std::move(item)); <<---- NOT WORKING } return retCastData; } How can I efficiently cast the vector of unique_ptr´s of Base class received to the vector of unique_ptr´s of T type as shown.
Thanks for helping.
-5208335 0try simply indicating ctypes the argtypes it takes and the ones it returns:
nDll = ctypes.WinDLL('ndll.dll') nDll.restype = ctypes.c_double nDll.argtypes = [ctypes.c_char_p] result = nDll.iptouint("12.345.67.890").value Although, consider these points:
1) if, as the name indicates, this converts an IPv4 value s ina string to an Unsigned Int, the return type os not "double" as you say - it would be ctypes.c_uint32
2) Your example value is not a valit IPv4 address, and cannot be converted to a 32 bit integer (neither does it makes sense as a "double" - i.e. a 64 bit floating point number) - it is simply invalid
3) You don't need that if you are just trying to have an unsigned 32bit value for an ipv4 address in Python. There are quite a few, very readable, easier, and multiplatform ways to do that with pure python. For example:
def iptoint(ip): value = 0 for component in ip.split("."): value <<= 8 #shifts previous value 8 bits to the left, #leaving space for the next byte value |= int(component) # sets the bits for the new byte in the address return value update: In Python 3.x there is the ipaddress module - https://docs.python.org/3/library/ipaddress.html - which is also available as a pip install for Python 2.x - it can handle this always in the correct way, and works fine with IPv6 as well.
-15149118 0 Text Lines are missed when reading a file Line by Line in Perl.I want to extract and log various parameters from a 3G modem as there are intermittent dropouts. As such I am using wget to read 3Ginfo.html from a 3G modem and placing the contents into a file contents.txt. Using Notepad++ to open this file shows all of the data.
Due to my reputation, I cannot post pictures, therefore the code below is the best I can do; from Notepad++ (with View All Characters turned on), I get:
<tr>[LF] <td class='hd'>Signal Strength:</td>[LF] <td>[LF] -72[CR]  (dBm) (High)</td>[LF] </tr>[LF] However, when the file is read line by line from Perl, it is clear that there are less lines than those reported by Notepad++ and data is missing. In this case the actual signal strength value is missing.
Here is the Perl code to read the file:
open hLOGFILE, "<output.txt"; while (<hLOGFILE>) { print "Line no $. Text is $_ "; } Here is the output (as text, because I cannot post pictures yet):
Line no 98 Text is <tr> Line no 99 Text is <td class='hd'>Signal Strength:</td> Line no 100 Text is <td>  (dBm) (High)</td> Line no 102 Text is </tr> It is clear that there are missing lines and it is related to the <cr> end of line terminator. I have tried slurping the file and the lines are still missing.
Apart from reading byte by byte and then trying to parse the file that way (which is not very appealing) I can not find a solution.
My plan is to simply extract and log the lines of interest every minute or so.
I have tried opening the file specifying various encoding but still no joy. If Notepad++ can read and display all the data, why does it not work in Perl. When using more from the Windows XP command line, it show that the data is also missing.
When I view source from chrome I get,
<tr> <td class='hd'>Received Signal Code Power(RSCP):</td> <td align='center'> -78 dBm</td> </tr>
-14507111 0 Method in main wont call method of a object instance? This is a java assignment containing 3 class files. The problem is when I call the "doOperations" method in main. The if statements read the file correctly, but the object methods dont work(e.g. tv.on, tv.volumeUp tv.setChannel(scan.nextInt(), etc.)).
Can anyone see where I am going wrong? Thanks.
TV class file.
import java.io.*; import java.util.Scanner; public class TV { boolean on; boolean subscribe; int currentchannel; int indexChan; int volume; File chanList; Scanner chanScan; TVChannel[] channels; final int MaxChannel = 100; public TV(){ on = false; currentchannel = 1; volume = 1; channels = new TVChannel[MaxChannel]; //Create object of an array, default value = null. subscribe = false; } public void turnOn(){ on = true; } public void turnOff(){ on = false; } public void channelUp(){ currentchannel++; } public void channelDown(){ currentchannel--; } public void volumeUp(){ volume++; } public void volumeDown(){ volume--; } public TVChannel getChannel(){ return channels[currentchannel]; } public void setChannel(int c){ if(channels[c]!= null) currentchannel = c; } public boolean subscribe(String provider) throws IOException{ chanList = new File(provider); chanScan = new Scanner(chanList); if(chanList.exists()){ while(chanScan.hasNext()){ indexChan = chanScan.nextInt(); channels[indexChan] = new TVChannel(indexChan, chanScan.nextLine()); } chanScan.close(); return true; } else return false; } public void printAll(){ for(int i = 0; i < MaxChannel; i++){ if(channels[i]!= null) System.out.println(channels[i].channelNumber+"\t"+channels[i].channelName); } } public void displayChannel(int c){ if(channels[c]!= null) System.out.println(channels[c].getChannel()+"\t"+channels[c].getName()); } public void displayCurrentChannel(){ if(channels[currentchannel] != null) System.out.println(channels[currentchannel].getChannel() +" "+ channels[currentchannel].getName()); } } Main function
import java.io.File; import java.io.IOException; import java.util.Scanner; public class TestTV { public static void main(String[] args) throws IOException{ TV tv = new TV(); tv.subscribe("chan.txt"); if(tv.subscribe = true){ tv.printAll(); doOperations("operations.txt", tv); } } //Static means only one instance of object. public static void doOperations(String opFileName, TV tv) throws IOException{ File op = new File(opFileName); Scanner scan = new Scanner(op); String opa = scan.next(); while(scan.hasNext()){ System.out.println(scan.next()); if(opa.equals("on")) tv.turnOn(); else if(opa.equals("off")) tv.turnOff(); else if(opa.equals("channelUp")) tv.channelUp(); else if(opa.equals("channelDown")) tv.channelDown(); else if(opa.equals("volumeUp")) tv.volumeUp(); else if(opa.equals("volumeDown")) tv.volumeDown(); else if(opa.equals("showChannel")) tv.displayCurrentChannel(); else if(opa.equals("setChannel"))tv.setChannel(scan.nextInt()); //Error } scan.close(); } }
-9145836 0 understanding executing c code in stack ( Mac Hackers Handbook code) I was looking at this example w.r.t executing code in the stack:
#include <stdio.h> #include <stdlib.h> #include <string.h> char shellcode[] = “\xeb\xfe”; int main(int argc, char *argv[]){ void (*f)(); char x[4]; memcpy(x, shellcode, sizeof(shellcode)); f = (void (*)()) x; f(); } This causes a segmentation fault. My understanding this is because the shellcode runs out of memory for the rest of the bytes as x only has a size of 4 bytes. And this results in creating a write operation of copying to stack memory and that causes a seg. fault as stack memory is read only. Is my understanding correct ?
-13289321 0try to do it,like below code...
private void Form1_Load(object sender, EventArgs e) { FillCountry();
} private void FillCountry() { string str = "SELECT CountryID, CountryName FROM Country"; SqlCommand cmd = new SqlCommand(str,con); //cmd.Connection = con; //cmd.CommandType = CommandType.Text; // cmd.CommandText = "SELECT CountryID, CountryName FROM Country"; DataSet objDs = new DataSet(); SqlDataAdapter dAdapter = new SqlDataAdapter(); dAdapter.SelectCommand = cmd; con.Open(); dAdapter.Fill(objDs); con.Close(); comboBox1.ValueMember = "CountryID"; comboBox1.DisplayMember = "CountryName"; comboBox1.DataSource = objDs.Tables[0]; } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { if (comboBox1.SelectedValue.ToString() != "") { int CountryID = Convert.ToInt32(comboBox1.SelectedValue.ToString()); FillStates(CountryID); comboBox3.SelectedIndex = 0; } } private void FillStates(int countryID) { string str = "SELECT StateID, StateName FROM State WHERE CountryID =@CountryID"; SqlCommand cmd = new SqlCommand(str, con); // SqlConnection con = new SqlConnection(Con); // cmd.Connection = con; // string str="SELECT StateID, StateName FROM State WHERE CountryID =@CountryID"; // cmd.Connection = con; //cmd.CommandType = CommandType.Text; // cmd.CommandText = "SELECT StateID, StateName FROM State WHERE CountryID =@CountryID"; cmd.Parameters.AddWithValue("@CountryID", countryID); DataSet objDs = new DataSet(); SqlDataAdapter dAdapter = new SqlDataAdapter(); dAdapter.SelectCommand = cmd; con.Open(); dAdapter.Fill(objDs); con.Close(); if (objDs.Tables[0].Rows.Count > 0) { comboBox2.ValueMember = "StateID"; comboBox2.DisplayMember = "StateName"; comboBox2.DataSource = objDs.Tables[0]; } } private void comboBox2_SelectedIndexChanged(object sender, EventArgs e) { int StateID = Convert.ToInt32(comboBox2.SelectedValue.ToString()); FillCities(StateID); } private void FillCities(int stateID) { //SqlConnection con = new SqlConnection(str,con); string str = "SELECT CityID, CityName FROM City WHERE StateID =@StateID"; SqlCommand cmd = new SqlCommand(str,con); // cmd.Connection = con; //cmd.CommandType = CommandType.Text; // cmd.CommandText = "SELECT CityID, CityName FROM City WHERE StateID =@StateID"; cmd.Parameters.AddWithValue("@StateID", stateID); DataSet objDs = new DataSet(); SqlDataAdapter dAdapter = new SqlDataAdapter(); dAdapter.SelectCommand = cmd; con.Open(); dAdapter.Fill(objDs); con.Close(); if (objDs.Tables[0].Rows.Count > 0) { comboBox3.DataSource = objDs.Tables[0]; comboBox3.DisplayMember = "CityName"; comboBox3.ValueMember = "CItyID"; }
-12558248 0 Try manually setting your view layers z-property to ensure the hierarchy is what you need.
-26675462 0Remark, it is a very general question that doesn't fit well to the usage of this community.
Supervisor are here to control the way your application starts and evolves in time. It starts processes in the right order with a verification that everything is going fine, manage the restart strategy in case of failure, pool of processes, supervision tree... The advantages are that it helps you to follow the "let it crash" rule in your application, and it concentrates in a few line of code the complex task to coordinate all your processes.
I use gen_event mainly for logging purposes. You can use this behavior to connect on demand different handlers depending on your target. In one of my application, I have by default a graphical logger that allows to check the behavior at a glance, and a textual file handler that allows deeper and post mortem analysis.
Gen_server is the basic brick of all applications. It allows to keep a state, react on call, cast and even simple messages. It manages the code changes and provides features for start and stop. Most of my modules are gen_servers, you can see it as an actor which is responsible to execute a single task.
Gen_fsm brings to gen server the notion of a current state with a specific behavior, and transition from state to state. It can be used for example in a game to control the evolution of the game (configuration, waiting for players, play, change level...)
When you create an application you will identify the different tasks yo have to do and assign them to either gen_server either gen_fsm. You will add gen_event to allow publish/subscribe mechanism. Then you will have to group all processes considering their dependency and error recovering. This will give you the supervision tree and restart strategy.
-22831653 0 Find applications starting with a specific string applescriptI want to find if an application is installed using AppleScript.
The application can have different versions installed in the same PC.
Hence, the name of the application is in the format "FooBar vXX.XX"
Now, when I tried
tell application "Finder" to get application "FooBar" The script launched a pop up, asking the user to find the app manually. Because, I didn't give the full name of the application - which includes the version number.
My query is, how can I find the installed application without its full name? This is necessary because I don't know which version is installed.
Can I use a regex in this case - How do I use it in this example?
-28808571 0 Back to page using ajax form with form settingsI have a page that offers the user results. From that page there are additional sort options and advanced search options that are submitted by POST by AJAX to a script and the output is inserted into a div using jquery.
Once the user clicks one of the results, they are redirected to the details page. When I click back from that page it doesnt load says form submission error.
Not sure what to be looking for all the stuff I have seen is for when there are simply multiple ajax pages in one page.
-2230420 0I've not tested this, but I think you can request the page using ajax and check the response code - if there's no errors and the status code is 200 then the page is accessible.
-13142537 0First, replace cat $strLocalDir"config.txt" by cat "${strLocalDir}config.txt".
Then, check what does config.txt contains ? This will be moved to the $URLS variable, maybe it s not well formed.
When you have such problems try to insert debug statements, like print. Test the value of your variables each time they're needed, you'll know more precisely where does the code fail.
-10812330 0All styleable attributes are here: http://developer.android.com/reference/android/R.styleable.html
All styles (themes) are here: http://developer.android.com/reference/android/R.style.html
-12355086 0 What's the usage of tesseract useROI method?Is there a documentation for tesseract dotnetwrapper? as in like a java doc or something? I'm trying to understand what this useROI method does?
-3487744 0 In PL/sql oracle stored procedure,trying to use analytical functionsIs it better to use cursor or analytical functions in a stored procedure for performance improvement?
-6204250 0@interface ContactUs : UINavigationViewController { IBOutlet UIWindow *window; IBOutlet UITextView *textView; IBOutlet UIButton *button; } // Add properties to the all outlets // -(IBAction) buttonpressed: (id) sender; And in the implementation - write the code for buttonpressed and you can make use that for whatever your goals are.
-33516227 0 Eclipse: Error importing android-support-v7-appcompat to workspaceI'm new. I use Eclipse.
As it is shown in several video tutorials.
File> Import -> Existing Android Project -> (Route sdk / extas / android / support / v7 / appcompat).
Imports almost all very well, however these errors appear within me res / values-v21
[2015-11-04 02:35:50 - android-support-v7-appcompat] D:\workspace\android-support-v7-appcompat\res\values-v21\themes_base.xml:131: error: Error: No resource found that matches the given name: attr 'android:colorPrimaryDark'.
[2015-11-04 02:35:50 - android-support-v7-appcompat] [2015-11-04 02:35:50 - android-support-v7-appcompat] D:\workspace\android-support-v7-appcompat\res\values-v21\themes_base.xml:140: error: Error: No resource found that matches the given name: attr 'android:windowElevation'.
[2015-11-04 02:35:50 - android-support-v7-appcompat] [2015-11-04 02:35:50 - android-support-v7-appcompat] D:\workspace\android-support-v7-appcompat\res\values-v21\themes_base.xml:144: error: Error: No resource found that matches the given name: attr 'android:windowElevation'.
[2015-11-04 02:35:50 - android-support-v7-appcompat]
PS: I have updated all my extras. SDK Tools, Android and Android Support Support Repository Library.
-9816909 0Use the following code:
protected void CashPayButton_Click(object sender, EventArgs e) { foreach(Gridviewrow gvr in Cash_GridView.Rows) { if(((CheckBox)gvr.findcontrol("MemberCheck")).Checked == true) { int uPrimaryid= gvr.cells["uPrimaryID"]; } } }
-28360697 0 In mainactivity.java:
after code text view:
TextView txt = (TextView) findViewById(R.id.textView id); Enter this code:
txt.setMovementMethod(new ScrollingMovementMethod()); and you will be ok.
-24606235 0 Issue inputing sas date as datalinesI've the following code. Though I've entered 30jun1983 it gets saved as 30/jun/2020. And it is reading only when there's two spaces between the date values in the cards and if there's only one space it reads the second value as missing.
DATA DIFFERENCE; infile cards dlm=',' dsd; INPUT DATE1 DATE9. Dt2 DATE9.; FORMAT DATE1 DDMMYY10. Dt2 DDMMYY10.; DIFFERENCE=YRDIF(DATE1,Dt2,'ACT/ACT'); DIFFERENCE=ROUND(DIFFERENCE); CARDS; 11MAY2009 30jun1983 ; RUN;
-22487714 0 Use SqlFunctions.DatePart static method. It will be transformed into DATEPART SQL function call in generated SQL query:
Returns an integer that represents the specified datepart of the specified date.
This function is translated to a corresponding function in the database. For information about the corresponding SQL Server function, see DATEPART (Transact-SQL).
To get week number, use "week" as parameter.
In this question: ServiceStack JsonServiceClient based test fails, but service works in browser I'm looking for some clue as to why the test generates an exception, when an interactive browser test succeeds. Originally I could run tests and interact via the browser.
Now I'm asking for some direction on how to debug this. Basically, if I step through my test case, I reach a line like this: Tranactions response = client.Get(request); and then it raises an exception. I'm thinking I should download the servicestack source and add the project to my solution, in order to step through that code and get further insight into what's going on. Any advice?
Bascially you have first to do a:
SurfFeatureDetector surf(400); surf.detect(image1, keypoints1); And then a:
surfDesc.compute(image1, keypoints1, descriptors1); Why detect and comput are 2 different operation?
Doing the computing after the detect doesn't make redundance loops?
I found myself that .compute is the most expensive in my application.
.detect is done in 0.2secs
.compute Takes ~1sec. Is there any way to speed up .compute ?
Without seeing the import statement that you tried, I am not 100% sure about why is that happening... But perhaps the reason is that you are using the default delimiter for fields, which is precisely a comma, so if you want to keep it, you should use a different delimiter, like for example:
--fields-terminated-by \t Another option would be to use --enclosed-by '\"', and it would look like "sami, ramesh".
Hope that helps! If it doesn't, please post your import statement to see where the problem is.
-5310283 0 Comet with scalaI am developing one application with GWT as client and my server side code written in Java servelt and I am fetching some data from another server. that another server code is in Scala. so the question is how can i push data from another server to my main server and display that data to client using comet ( gwt-comet.jar)
Please help me.
Thanks
-15109040 0 Open application without tapping on iconIs there any way by which we can launch the app by the external volume button or by any other gestures made on the iPhone instead of launching by the default way?
OR
Can our app recognise the users interaction with the volume button when app is in the background?
-15733849 0 assignment switch case c ++Requirements
for loop to input the data each bird watcher has collected.for loop, a do ... while loop to input and process the data collected by one bird watcher.do ... while loop a switch statement is used to calculate the number of eggs for each type of bird. the default option, which does nothing, is used when an x is entered.do ... while loop is exited when an X is entered for the type of bird.ok, now my problem is I can't seem to get through my switch case. It prompts me for the first watcher's info, when I enter it, it never moves over to the next watcher.
The input data given is
3 E2 O1 V2 E1 O3 X0 V2 V1 O1 E3 O2 E1 X0 V2 E1 X And here is the code that I got so far:
#include <iostream> #include <cstdlib> using namespace std; int main() { int totNrVultureEggs, totNrEagleEggs, totNrOwlEggs, nrEggs, nrVultureEggs, nrEagleEggs, nrOwlEggs, nrBirdWatchers, nrEggsEntered; char bird; // initialize grand totals for number of eggs for each type of bird cout << "How many bird watchers took part in the study?"; cin >> nrBirdWatchers; // loop over number of bird watchers for (int i = 0; i < nrBirdWatchers ;i++ ) { // initialize totals for number of eggs for each type of bird // this bird watcher saw nrVultureEggs = 0; nrEagleEggs = 0; nrOwlEggs = 0; cout << "\nEnter data for bird watcher " << i + 1 << ":" << endl; //loop over bird watchers do{ cin >> bird >> nrEggs; switch (bird) { case 'E': case 'e': nrEagleEggs = nrEagleEggs + nrEggs; case 'O': case 'o': nrOwlEggs = nrOwlEggs + nrEggs; case 'V': case 'v': nrVultureEggs = nrVultureEggs + nrEggs; default : nrBirdWatchers++; break; } }while (i < nrBirdWatchers ) ; cout << "Bird watcher " << i + 1 << " saw " << nrVultureEggs; cout << " vulture eggs, " << nrEagleEggs << " eagle eggs and "; cout << nrOwlEggs << " owl eggs " << endl; // increment grand totals for eggs } // display results cout << "\nTotal number of vulture eggs: " << totNrVultureEggs; cout << "\nTotal number of eagle eggs: " << totNrEagleEggs; cout << "\nTotal number of owl eggs: " << totNrOwlEggs; return 0; }
-7273371 0 How do I edit and save a nib file at runtime? Imagine an application that has a number of buttons it is displaying to the user. This application wants to allow the user to move the buttons around on the screen, customizing the display, and then save this configuration for later use. That is, when the app is closed and relaunched, it will come back up with the same configuration.
I would like to create a nib file with the "factory default" button layout, but then create a new nib file storing the new UI after the user has configured it just the way they like it. How does one do this?
Thanks!
-16629287 0 How do I check if a "name" value exists in a SQLLite Database?I have a SQLLite Database of sites with a name field. I have save and create buttons. I want to run my addRecord() or updateRecord() depending on whether or not the value in the name field exists.
I have this method in my DBAdapter:
public Cursor getRow(long rowId) { String where = KEY_ROWID + "=" + rowId; Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null); if (c != null) { c.moveToFirst(); } return c; } How can I create a similar method to get the rowID based on the name String supplied?
ie
public Cursor getRowID(String _name) { ... }
-26273376 0 You need to change window.location in a success callback since it may happen before the asynchronous POST request is finished.
$.ajax({ type: "POST", url: "/mobile.php", data: {values:"mobile"} success: function(){ window.location = "http://dekstopversionexample.lt"; } });
-4118396 0 Extended WPF Toolkit - Binding Text of richtextbox I am newbie in WPF. I need make TwoWay and OneWayToSource bind to string variable. I want use richtextbox from Extended WPF Toolkit ,because I think it is the easy way.
So I try use richtebox from this library in xaml, code is here:
<Window x:Class="PokecMessanger.ChatWindow" xmlns:extToolkit="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit.Extended" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="ChatWindow" Height="429" Width="924"> ///... <extToolkit:RichTextBox Name="rtbRpText" Text="{Binding _rpText, Mode=OneWayToSource}" Grid.Column="0"></extToolkit:RichTextBox> In code behind, I have this code:
private string _rpText = string.Empty; public ChatWindow(PokecCommands pokecCmd) { rtbRpText.DataContext = _rpText; } Problem is, if I wrote something in richtextbox, variable _rpText is still empty, where can be problem?
-22523418 0 I append a text in my table cell using a click event.Now i need to remove the selected text using another click event. how can i make it possibleI append a text in my table cell using a click event.Now i need to remove the selected text using another click event. how can i make it possible
$( "#btsubmit" ).click(function(){ $("#our_table td.highlighted").append("<span id='sp1'>Appended<span>"); }); $( "#btnClose" ).click(function(){ });
-14552858 0 I can't help much without knowledge about Java BufferedImage,Graphics, PrinterJob and other related classes implementation. (You may start a bounty for this question to possibly draw attention of people having more intristic knowledge about java awt graphic stuff).
As you obviously must have noticed using BufferedImage (or not using it) is what makes a difference in SVG output. In the version that works you draw the rectangle directly on Graphic context provided to you as print() method argument and I believe that's how it was designed to be used by authors of Printable interface and printing framework.
In the second approach (that doesn't work correct) you first draw rectangle onto new BufferedImage object and then draw this image on the provided Graphic context. So you do something much less straightforward than just drawing directly on the context. There is well known truth or intuition among developers that the less straightforward way do you use some API, the bigger is a chance that you do something unexpected by its authors :(.
My hypotesis is following: BufferedImage is (as you can deduce from its Javadocs)just a raster image, ie. grid of pixels. That's why svg file is populated with lots of small rectangles (trying to mimic pixels). The Graphics object provided by draw() method may be more abstract and operate on shapes rather than pixels, which is much more appropriate to be written to vector graphics formats like SVG. But that's just hypotesis.
The question is, do you really need to use BufferedImage? If I understand correctly, you want user to be able to edit rectangle on screen and when ready export it to SVG. Can't you just remember for example upper left corner and dimensions of rectangle edited by user and then use this data to recreate this rectangle directly on Graphics object provided by print(), like:
public int print(Graphics g, PageFormat pf, int page) throws PrinterException { ... g.fillRect(userRect.x,userRect.y,userRect.width,userRect.height); ... } ?
(userRect is object of your own custom class which just stores data about image edited by user)
That's a very good question which actually made me realise that we don't have it documented. We'll fix it.
As for now the expected format looks like this (you can use MongooseIM's debug shell to generate it).
scram:serialize(scram:password_to_scram(<<"ala_ma_kota">>, 4096)). <<"==SCRAM==,xB2++RvZklv0rV5I1iuCpoxLqL0=,sKXBkOFrtyGxKqYo/dlzeKfYszU=,oplvMJ5VDxQ7rJZuIj0ZfA==,4096">> In other words, MongooseIM expects the format to be:
==SCRAM==,StoredKey,ServerKey,Salt,IterationCount the ==SCRAM== prefix is constant, other parts depends on the password.
Hope that helps.
-3376115 0No. It's not a redundant parameter; the code that utilizes a SalesStrategy should not know which concrete class it is using, so the method signature must be identical in all derived classes.
-37175215 0 Error when trying to create a Timer in EJBI'm having a problem with a timer in EJB.I don't have experience whit this type application, so I don't know What to do for resolve this problem.
timer cod:
@Schedule(minute="*/2", second="0", dayOfMonth="*", month="*", year="*", hour="6-23", dayOfWeek="*", persistent = false) public void cargaC() { ....} @Schedule(minute="10", second="0", dayOfMonth="*", month="*", year="*", hour="1", dayOfWeek="*", persistent = false) public void limpaTabelaC(){ ....} error:
18:56:10,103 INFO [org.jboss.as.ejb3] (EJB default - 4) JBAS014121: Timer: [id=c7a5c2c9-2b6c-49d8-956a-f831ebab53c3 timedObjectId=PrjX_V2.PrjX_V2.CargaDados auto-timer?:true persistent?:false timerService=org.jboss.as.ejb3.timerservice.TimerServiceImpl@35d07654 initialExpiration=Wed May 11 06:00:00 BRT 2016 intervalDuration(in milli sec)=0 nextExpiration=Wed May 11 18:58:00 BRT 2016 timerState=IN_TIMEOUT will be retried 18:56:10,103 INFO [org.jboss.as.ejb3] (EJB default - 4) JBAS014123: Retrying timeout for timer: [id=c7a5c2c9-2b6c-49d8-956a-f831ebab53c3 timedObjectId=PrjX_V2.PrjX_V2.CargaDados auto-timer?:true persistent?:false timerService=org.jboss.as.ejb3.timerservice.TimerServiceImpl@35d07654 initialExpiration=Wed May 11 06:00:00 BRT 2016 intervalDuration(in milli sec)=0 nextExpiration=Wed May 11 18:58:00 BRT 2016 timerState=IN_TIMEOUT 18:56:14,813 ERROR [org.jboss.as.ejb3] (EJB default - 4) JBAS014122: Error during retrying timeout for timer: [id=c7a5c2c9-2b6c-49d8-956a-f831ebab53c3 timedObjectId=PrjX_V2.PrjX_V2.CargaDados auto-timer?:true persistent?:false timerService=org.jboss.as.ejb3.timerservice.TimerServiceImpl@35d07654 initialExpiration=Wed May 11 06:00:00 BRT 2016 intervalDuration(in milli sec)=0 nextExpiration=Wed May 11 18:58:00 BRT 2016 timerState=RETRY_TIMEOUT: javax.ejb.EJBException: Unexpected Error someone can help me?
-37181181 0 Right way to store Image in database through Entity FrameworkI have converted an image to a byte array using below code to store it in Database
if (Request.Content.IsMimeMultipartContent()) { var provider = new MultipartMemoryStreamProvider(); await Request.Content.ReadAsMultipartAsync(provider); foreach (var file in provider.Contents) { var filename = file.Headers.ContentDisposition.FileName.Trim('\"'); var attachmentData = new AttachmentData (); attachmentData.File = file.ReadAsByteArrayAsync().Result; db.AttachmentData.Add(attachmentData); db.SaveChanges(); return Ok(attachmentData); } } Here File column in DB is of type "varbinary(max)" and in EF model it is byte array (byte[]).
Using above code I was able to save the image in the File column something similar to "0x30783839353034453437304430413143136303832....." (This length is exceeding 43679 characters which is more than default given to any column so the data got truncated while storing it)
I have to change the default length(43679) of column to store it in database.
Am I doing it the correct way to retrieve and store image in Database. I was also thinking to store the image as "Base64 String" but 43679 will still exceed.
I am using Angular JS to show the image on front end which uses WebAPI to fetch and save the image as ByteArray in database.
-7794 0How about:
protected override void OnPreviewTextInput(System.Windows.Input.TextCompositionEventArgs e) { e.Handled = !AreAllValidNumericChars(e.Text); base.OnPreviewTextInput(e); } private bool AreAllValidNumericChars(string str) { foreach(char c in str) { if(!Char.IsNumber(c)) return false; } return true; }
-32701824 0 Swift: Comparing Implicitly Unwrapped Optionals results in "unexpectedly found nil while unwrapping an Optional values" If got this class and would like to compare instances of it based on the value
class LocationOption: NSObject { var name:String! var radius:Int! var value:String! override func isEqual(object: AnyObject?) -> Bool { if let otherOption = object as? LocationOption { return (self.name == otherOption.name) && (self.radius == otherOption.radius) && (self.value == otherOption.value) } return false } } When executing this:
var a = LocationOption() var b = LocationOption() a.name = "test" b.name = "test" if a == b { // Crashes here!! print("a and b are the same"); } This crashes with "unexpectedly found nil while unwrapping an Optional value"? You can copy all this into a Playground to reproduce.
It seems to be due to the Implicitly Unwrapped Optionals. If I declare all fields as Optionals it works as expected.
But in my case, I would like to have these properties as Implicitly Unwrapped Optionals. How should I write the isEqual?
===
UPDATE: @matt is right and as I didn't want to change to "regular" Optionals I ended up with this:
class LocationOption: Equatable { var name:String! var requireGps:Bool! var radius:Int! var value:String! } func ==(lhs: LocationOption, rhs: LocationOption) -> Bool { let ln:String? = lhs.name as String?, rn = rhs.name as String? let lr = lhs.radius as Int?, rr = rhs.radius as Int? return ln == rn && lr == rr }
-3109912 0 The "correct" way according to the Java EE architecture would be to have a JCA connector to do inbound/outbound connection with the SMTP server.
The JCA connector can do whatever you want, including threading and connection to external systems with sockets. Actually JMS is just a special kind of JCA connector that connects to JMS broker and delivers message to "regular" MDB. A JCA connector can then poll the SMTP server and delivers the message to a custom MDB.
The best document about JCA is Creating Resource Adapters with J2EE Connector Architecture 1.5, and it does actually use the example of email delivery. Luck you :) I suggest you have a look at it. The code can be found as part of the Java EE samples and uses JavaMail, but I don't know if it's production ready.
Related:
You got the parameters in the wrong order (from the documentation)
Pattern.matches(String regex, CharSequence input)
-38012493 0 Try this editablegrid framework http://www.editablegrid.net/en/
-32280137 0The parameters to glfwOpenWindow are specifying the desired values. However, it's entirely possible that your driver doesn't support the exact format you're asking for (24 bit color, 24 bit depth, no alpha, no stencil). GLFW will attempt to find the best match while meeting your minimums.
In this case it's probably giving you the most standard format of RGBA color (32 bit) and a 24/8 bit depth/stencil buffer, or it could be creating a 32 bit depth buffer. You'd actually need to call glfwGetWindowParam to query the depth and stencil bits for the default framebuffer, and then build your renderbuffers to match that.
Use string.TrimEnd on your TextBox Text.
Participant.Text = participants.TrimEnd(',');
-16330171 0 Anorm says no results were returned for select query preceded by inserts (PSQLException: No results were returned by the query) I'm writing a Play 2 application with a Postgres backend.
My code has a sql string which is a concatenation of two inserts and a select. Then when I try to execute my query, anorm blows up and says me no results have been returned. I could break it up into two separate queries but then I'd be making an unnecessary trip to the database?
The sql string is pretty simple.
val sql = """ insert into gameconstants ... values ...; insert into gamevariables ... values ...; select lastval() as gameid; """ Then the code that throws the exception just tries to get the gameid from query. This should work right?
DB.withTransaction { implicit connection => val gameid = SQL(sql).on( ... )() .map(row => row[Long]("gameid")).head } Here is the error [PSQLException: No results were returned by the query.]
-16173593 0 Where should Exceptions be put that are used by multiple projects?I need to refactor a project with two data models into two separate projects. Both projects use the same Exceptions. Should I create a 3rd project only for these exceptions? Cloning sounds like a no-go.
-4736248 0Sluama - Your suggestion fixed it! Such an obvious answer. The " was terminating the Where clause string. I could have sworn I tried that, but I guess not. Becuase, I just happened to come back to this question and saw your answer and it works!
<asp:EntityDataSource ID="EDSParts" runat="server" ConnectionString="name=TTEntities" DefaultContainerName="TTEntities" EnableFlattening="False" EntitySetName="Parts" OrderBy="it.ID DESC" Where ="(CASE WHEN (@PartNumber IS NOT NULL) THEN it.[Number] LIKE REPLACE(@PartNumber, '*', '%') ELSE it.[ID] IS NOT NULL END)"> <WhereParameters> <asp:ControlParameter Name="PartNumber" Type="String" ControlID="txtPartNumberQuery" PropertyName="Text" /> </WhereParameters> </asp:EntityDataSource>
-21972293 0 Data Type for Currency in Entity Framework What data type should I use to hold currency values in Entity Framework 6 and what data type should I map it in SQL Server 2012?
Thank You, Miguel
-27520469 0 iOS UITextField value without tapping on RETURN buttonIs it possible to take UITextField value without tapping RETURN button?. If I type something in LOGIN UITextField and then tap on PASSWORD UITextField, it looks like LOGIN value is empty, however if I type something in LOGIN, and then tap RETURN everything's fine.
Without tapping on RETURN http://gyazo.com/2ca0f263275fd65ae674233f34d90280
With tapping on RETURN http://gyazo.com/9ccc39ba7080b6b6344454ec757d3c0f
Here's my code:
TextInputTableViewCell.m
@implementation TextInputTableViewCell -(void)configureWithDictionary:(NSMutableDictionary *)dictionary { self.cellInfoDictionary = dictionary; NSString *title = [dictionary objectForKey:@"title"]; NSString *imageName = [dictionary objectForKey:@"imageName"]; UIColor *color = [dictionary objectForKey:@"bgColor"]; BOOL secureTextEntry = [dictionary objectForKey:@"secure"]; self.myTextField.placeholder = title; self.myImageView.image = [UIImage imageNamed:imageName]; self.contentView.backgroundColor = color; self.myTextField.secureTextEntry = secureTextEntry; self.myTextField.delegate = self; } -(BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; if (textField.text) { [self.cellInfoDictionary setObject:textField.text forKey:@"value"]; } return NO; } @end LoginViewController.m
@interface LoginViewController () <UITableViewDataSource, UITableViewDelegate, NewRestHandlerDelegate> @property (strong, nonatomic) IBOutlet UITableView *tableView; @property (strong, nonatomic) NSArray *datasource; @end static NSString *textInputCellIdentifier = @"textInputCellIdentifier"; static NSString *buttonCellIdentifier = @"buttonCellIdentifier"; @implementation LoginViewController { NSString *email; NSString *password; NewRestHandler *restHandler; } - (void)viewDidLoad { [super viewDidLoad]; NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; if ([defaults boolForKey:@"logged"]) [self performSegueWithIdentifier:@"Logged" sender:self]; [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TextInputTableViewCell class]) bundle:nil] forCellReuseIdentifier:textInputCellIdentifier]; [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ButtonTableViewCell class]) bundle:nil] forCellReuseIdentifier:buttonCellIdentifier]; restHandler = [[NewRestHandler alloc] init]; restHandler.delegate = self; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSDictionary *dictionary = [self.datasource objectAtIndex:indexPath.row]; NSString *cellIdentifier = [dictionary objectForKey:@"cellIdentifier"]; UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if ([cell respondsToSelector:@selector(configureWithDictionary:)]) { [cell performSelector:@selector(configureWithDictionary:) withObject:dictionary]; } return cell; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.datasource.count; } ... - (NSArray *)datasource { if (!_datasource) { NSMutableArray* datasource = [NSMutableArray arrayWithCapacity:5]; NSMutableDictionary* loginDictionary = @{@"cellIdentifier": textInputCellIdentifier, @"title": @"Login", @"imageName": @"edycja02.png", @"bgColor": [UIColor whiteColor], }.mutableCopy; NSMutableDictionary* passwordDictionary = @{@"cellIdentifier": textInputCellIdentifier, @"title": @"Password", @"imageName": @"edycja03.png", @"bgColor": [UIColor whiteColor], @"secure": @YES, }.mutableCopy; NSMutableDictionary* loginButtonDictionary = @{@"cellIdentifier": buttonCellIdentifier, @"title": @"Login", @"imageName": @"logowanie01.png", @"bgColor": [UIColor colorWithRed:88/255.0 green:88/255.0 blue:90/255.0 alpha:1], @"textColor": [UIColor whiteColor], }.mutableCopy; NSMutableDictionary* facebookLoginButtonDictionary = @{@"cellIdentifier": buttonCellIdentifier, @"title": @"Login with Facebook", @"imageName": @"logowanie02.png", @"bgColor": [UIColor colorWithRed:145/255.0 green:157/255.0 blue:190/255.0 alpha:1], @"textColor": [UIColor whiteColor], }.mutableCopy; NSMutableDictionary* signUpButtonDictionary = @{@"cellIdentifier": buttonCellIdentifier, @"title": @"Sign up", @"imageName": @"logowanie03.png", @"bgColor": [UIColor colorWithRed:209/255.0 green:210/255.0 blue:212/255.0 alpha:1], @"textColor": [UIColor whiteColor], }.mutableCopy; [datasource addObject:loginDictionary]; [datasource addObject:passwordDictionary]; [datasource addObject:loginButtonDictionary]; [datasource addObject:facebookLoginButtonDictionary]; [datasource addObject:signUpButtonDictionary]; _datasource = datasource; } return _datasource; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { if (indexPath.row == 2) { email = [self.datasource[0] valueForKey:@"value"]; password = [self.datasource[1] valueForKey:@"value"]; NSLog(@"Email: %@", email); NSLog(@"Password: %@", password); ...
-1715943 0 workaround: site is www.site.com code incl. document.domain='site.com' A customer site that I cannot change has the line 'document.domain = "site.com"; while the site is at www.site.com.
The effect is that FB connect window login gets stuck after submitting username+password.
Firebug shows its in infinite loop inside dispatchmessage function, which gives perpetual exception:
Error: Permission denied for <http://www.site.com> to get propertyl Window.FB from <http://site.com> Any idea how to work around this? I prefer not to ask the customer to remove the document.domain='site.com'
-15523470 0This depends on how your struct is defined, whether or not you want your output to be human-readable, and whether or not the output file is meant to be read on a different architecture.
The fwrite solution that others have given will write the binary representation of the struct to the output file. For example, given the code below:
#include <stdio.h> int main(void) { struct foo { int x; char name1[10]; char name2[10]; } items[] = {{1,"one","ONE"}, {2,"two","TWO"}}; FILE *output = fopen("binio.dat", "w"); fwrite( items, sizeof items, 1, output ); fclose( output ); return 0; } if I display the contents of binio.dat to the console, I get the following:
john@marvin:~/Development/Prototypes/C/binio$ cat binio.dat oneONEtwoTWOjohn@marvin:~/Development/Prototypes/C/binio$ john@marvin:~/Development/Prototypes/C/binio$ od -c binio.dat 0000000 001 \0 \0 \0 o n e \0 \0 \0 \0 \0 \0 \0 O N 0000020 E \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 0000040 \0 \0 \0 \0 002 \0 \0 \0 t w o \0 \0 \0 \0 \0 0000060 \0 \0 T W O \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 0000100 \0 \0 \0 \0 \0 \0 \0 \0 0000110
The integer values show up as garbage (not reproduced above) because they've been stored as the byte sequences 01, 00, 00, 00 and 02, 00, 00, 00 (x86 is little-endian), which are not printable characters. Also note that all 10 characters of name1 and all 20 characters of name2 are written to the file, which may or may not be what you want.
The situation gets even more complicated if your struct contains pointers, because what gets stored to the file is the pointer value, not the thing being pointed to:
#include <stdio.h> int main(void) { struct foo { int x; char *name1; char *name2; } items[] = {{1,"one","ONE"}, {2,"two","TWO"}}; FILE *output = fopen("binio.dat", "w"); fwrite( items, sizeof items, 1, output ); fclose( output ); return 0; } This time I get
john@marvin:~/Development/Prototypes/C/binio$ cat binio.dat ��������john@marvin:~/Development/Prototypes/C/binio$ john@marvin:~/Development/Prototypes/C/binio$ od -c binio.dat 0000000 001 \0 \0 \0 260 205 004 \b 264 205 004 \b 002 \0 \0 \0 0000020 270 205 004 \b 274 205 004 \b 0000030
Note that none of the strings appear in the file at all; if you read this file in with a different program, all it will see are (most likely) invalid addresses.
If you want your output to be human-readable and you want to be able to read those values in on a different architecture, you almost have to go with formatted output, meaning you have to write each member separately:
#include <stdio.h> int main(void) { struct foo { int x; char *name1; char *name2; } items[] = {{1,"one","ONE"}, {2,"two","TWO"}}; FILE *output = fopen("binio.dat", "w"); int i; for (i = 0; i < sizeof items / sizeof items[0]; i++) { fprintf(output, "%d %s %s\n", items[i].x, items[i].name1, items[i].name2); } fclose( output ); return 0; } john@marvin:~/Development/Prototypes/C/binio$ cat binio.dat 1 one ONE 2 two TWO
You can certainly wrap that operation in a function of your own, something like
int printFoo( FILE *output, const struct foo item ) { return fprintf( output, "%d %s %s\n", item.x, item.name1, item.name2); } but in the end, that's about as simple as it gets.
The fwrite solution works great if you're not concerned about readability and portability, but you still have to be careful if you have any pointer members within the struct.
Why not use Jquery to call CKEditor to replace your div...seems much more straightforward:
$( 'textarea' ).ckeditor(); Reference Here: http://ckeditor.com/blog/CKEditor_for_jQuery
-4282486 0 How to track more than one remote with a given branch using Git?The situation is this:
I have more than one remote repository - for reference, lets say that one is the "alpha" repository, and we have recently set up a new "beta" repository, which some users have migrated to.
Both repositories have a "master" branch.
How do I set up my local master such that it will attempt to automatically push and pull to and from both the alpha and beta repositories, without manually specifying the remote I want to use each time?
I should elaborate that I don't want to set up two local branches 'master-alpha' and 'master-beta', I want the same local branch to track both remotes.
-25188107 0"I'm thinking more TDD, like in an OOP language. Is such a thing possible in Haskell?"
A better question is "is such a thing necessary in Haskell?" ;-)
[I realise that is not the question you actually asked. Feel free to ignore this answer.]
In an OO language, we build objects that talk to other objects to get their job done. To test such an object, we build a bunch of fake objects, hook the real object up to the fake ones, run the method(s) we want to test, and assert that it calls faked methods with the expected inputs, etc.
In Haskell, we write functions. The only thing a pure function does is take some input, and produce some output. So the way to test that is to just run the thing, feeding it known inputs and checking that it returns known outputs. What other functions it calls in the process of doing that doesn't matter; all we care about is whether the answer is right.
In particular, the reason we don't usually do this in OOP is that calling some arbitrary method might cause "real work" to happen — reading or writing disk files, opening network connections, talking to databases and other servers, etc. If you're just testing one part of your code, you don't want the test to depend on whether some database is running on a real network server somewhere; you just want to test one little part of your code.
With Haskell, we separate anything that can affect the Real World from stuff that just does data transformations. Testing stuff that just transforms data in memory is delightfully trivial! (Testing the parts of your code that do interact with the Real World is still hard, in general. But hopefully those parts are very small now.)
The Haskell test style of choice seems to be property-based testing. For example, if you've got a function to solve an equation, you write a QuickCheck property that randomly generates 100 equations, and for each one, it checks whether the number returned actually solves the original equation or not. It's a tiny handful of code that automatically tests just about everything you'd ever want to know! (But not quite: You need to make sure that the "randomly" chosen equations actually test all the code paths you care about.)
-7870094 0 Change color scheme on komodo editHi this is a very noob question but i am trying to change the color scheme on komodo edit, version 6. I am running windows 7. I put the .ksf file in the /schemes folder, now what?
-27472769 0 Generating a Unique ID by using Rand()Trying to create a ajax private chat. But can't seem to generate a unique ID that hasn't been used by another user.
$genid = rand(1,999999999999); foreach($genid as &$rand){ $q = mysql_query("SELECT ".$q_pchat." FROM users WHERE pchat_id1='".$rand."'"); $r = mysql_num_rows($q); if($r == 0){ $chatid = $rand; break; } } Get an internal server error 500. I think it's cause its an infinite loop.
-38396949 0You can see there are comments in aapt_rules.txt. Beside each kept class there are corresponding layout files that referenced this class. Like that:
# view res/layout/abc_list_menu_item_layout.xml #generated:17 # view res/layout/abc_popup_menu_item_layout.xml #generated:17 -keep class android.support.v7.internal.view.menu.ListMenuItemView { <init>(...); } If you remove the layout file from build process this line will desappear and class will not be kept. The class will be shrinked if it's not actually used somewhere.
So how can we remove layout file from appcompat library? I can see few options, none of them is perfect but they work.
You can just remove file from sdk\extras\android\m2repository\com\android\support\appcompat-v7\version\appcompat-v7-version.aar. Enough for testing, bad for production because the same file may be used in some other projects. I tried and it works.
Put fake file with the same name into your project. Name conflict will happen. Build process will prefer your fake file because project files have higher priority. This way file from appcompat will be ignored. I tried and it works.
Probably you can make some fancy gradle script that removes unwanted files during the build process. I haven't tried that.
(shrinkResources option doesn't help because aapt_rules.txt is generated BEFORE shrinkResources is actually involved.)
I hope somebody will suggest a better way to do that
After doing that all unwanted lines were gone from aapt_rules.txt. But it saved me about 100 KB from the final apk size. So not big deal for me. But in your case results may be different.
-20296286 0I don't claim to fully understand the why here, but as best I can tell, this is what's going on.
summary.default actually calls oldClass rather than class. Why I'm not sure, although I'm sure there's a good reason.
Somewhat cryptically in ?class we find the following passages:
Many R objects have a class attribute, a character vector giving the names of the classes from which the object inherits. If the object does not have a class attribute, it has an implicit class, "matrix", "array" or the result of mode(x) (except that integer vectors have implicit class "integer"). (Functions oldClass and oldClass<- get and set the attribute, which can also be done directly.)
So what's going on here is that class returns the implicit class (numeric). Note that attr(a$alpha,"class") returns NULL. Since the attribute doesn't exists, oldClass faithfully returns NULL.
As for the differences between mode, type and class, the first two are related, the third is sort of a separate idea. Mode and type are (I think) actually fairly well explained in the documentation. mode tells you the storage mode of an object, but it is relying on the result of typeof, so they are (mostly) the same. Or connected, at least. But the different values that typeof returns are simply collapsed down to a smaller subset.
Your JSON is invalid or your server responding with invalid JSON.
It should be like this
{ "name":"rezepte", "id":"1", "name":null, "alter":"Ab 6.Monat", "kategorie":null, "tageszeit":"Mittags", "portionen":"1 baby- und 1 Erwachsenenportion", "bild":"\u0000\u0000\u0000\u0000\u0000", "vorrat":"2", "zubereitungszeit":"45", "zubereitung0":null, "zubereitung1":null, "zubereitung2":null, "info":null }
-39982831 0 To assign the output of a command to a variable, wrap the command in backticks or $().
RESULT=$(cat $LOGFILE | tail -1) Your command performed the environment variable assignment RESULT=cat, and then executed the command $LOGFILE | tail -1 in that environment. Since $LOGFILE is not an executable file, you got an error.
I assume you have a problem with the webroot, i.e. public_html/webtest is set as a root of your site and thus anything outside this folder is not accessible for the app.
Can you verify this?
-21147959 0 Add .com to end of my string in phpWhat I'm trying to is search my string to see if there is any of the following arrays there
if not then we need to add .com to end of it.
$kwlines is my string and i have set it to test but this is what I get
test.comtest.com.comtest.com.com.comtest.com.com.com.comtest.com.com.com.com.comtest.com.com.com.com.com.comtest.com.com.com.com.com.com.com
foreach ($kwlines as $kw) { $owned_urls= array('.com', '.co.uk', '.net','.org', '.gov','.gov.co.uk','.us'); foreach ($owned_urls as $url) { if (strpos($kw, $url) !== TRUE) { $kw .= ".com"; echo "$kw"; } } Could you please help me understand what I do wrong?
Thank you
-37427070 0Add
android{ .... packagingOptions { exclude 'META-INF/LICENSE' exclude 'META-INF/LICENSE-FIREBASE.txt' exclude 'META-INF/NOTICE' } } to your app's gradle file.
-8275004 0Ok, I've got it figured out now! What was happening is it was trying to speak before TTS was initialized. So in a thread I wait for ready to not == 999. Once its either 1 or anything else we'll then take care of speaking. This might not be safe putting it in a while loop but... It's working nonetheless.
import java.util.HashMap; import java.util.Locale; import android.app.Service; import android.content.Intent; import android.media.AudioManager; import android.os.IBinder; import android.speech.tts.TextToSpeech; import android.speech.tts.TextToSpeech.OnInitListener; import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener; import android.util.Log; public class TTSService extends Service implements OnInitListener, OnUtteranceCompletedListener { TextToSpeech mTTS; int ready = 999; @Override public void onCreate() { Log.d("", "TTSService Created!"); mTTS = new TextToSpeech(getApplicationContext(), this); new Thread(new Runnable() { @Override public void run() { while(ready == 999) { //wait } if(ready==1){ HashMap<String, String> myHashStream = new HashMap<String, String>(); myHashStream.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_NOTIFICATION)); myHashStream.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "1"); mTTS.setLanguage(Locale.US); //mTTS.setOnUtteranceCompletedListener(this); mTTS.speak("I'm saying some stuff to you!", TextToSpeech.QUEUE_FLUSH, myHashStream); } else { Log.d("", "not ready"); } } }).start(); stopSelf(); } @Override public IBinder onBind(Intent intent) { return null; } @Override public void onDestroy() { mTTS.shutdown(); super.onDestroy(); } @Override public void onInit(int status) { Log.d("", "TTSService onInit: " + String.valueOf(status)); if (status == TextToSpeech.SUCCESS) { ready = 1; } else { ready = 0; Log.d("", "failed to initialize"); } } public void onUtteranceCompleted(String uttId) { Log.d("", "done uttering"); if(uttId == "1") { mTTS.shutdown(); } } }
-17547685 0 Declare type object in an oracle package Is there a way to declare type object in a package ?
it seems like the one following is not supported in the context the package
TYPE xxx AS OBJECT thank you
-40774484 0you can do on a other way:
Create a Select with this Concats
select GROUP_CONCAT( CONCAT(" ('",field1,"','",field2,"')")) as vals from my_table; The Result look like this:
Result
mysql> select GROUP_CONCAT( -> CONCAT(" ('",field1,"','",field2,"')")) as vals -> from my_table; +---------------------------------------------------------------------------------------------------------+ | vals | +---------------------------------------------------------------------------------------------------------+ | ('O1','AC'), ('O1','PT'), ('O2','PT'), ('O3','MI'), ('O3','PT'), ('O4','EG'), ('O4','PT'), ('O5','PT') | +---------------------------------------------------------------------------------------------------------+ 1 row in set (0,00 sec) mysql> and the you can direct concat this in the insert statement and you only read one row and only write and execute one statement.
your Code
String selectStatement = "SELECT GROUP_CONCAT(CONCAT(" ('",field1,"','",field2,"')")) as vals FROM dbx.testx where time between ('2016-09-01 00:00:00') and ('2016-09-03 23:59:59');"; ResultSet resultSetForSelect = st.executeQuery(selectStatement); String insertStatement = "INSERT INTO testy(" + "field1," + "field2)" + + String from result + "ON DUPLICATE KEY UPDATE field1 = VALUES(field1);"; <----field1 is a unique key but not primary # execute one time
-32155249 0 I would say the answer is: you can't. (or at least: you shouldn't). This is not what Webpack is supposed to do. Webpack is a bundler, and it should not be used for other tasks (in this case: copying static files is another task). You should use a tool like Grunt og Gulp to do such tasks. It is very common to integrate webpack as a grunt task or as a gulp task. They both have other tasks useful for copying files like you described. grunt-contrib-copy or gulp-copy.
For other assets (not the index.html), you can just bundle them in with webpack (that is exactly what webpack is for). var image = require('assets/my_image.png'); But I assume your index.html needs to not be a part of the bundle, and therefore it is not a job for the bundler.
im new to javascript and phonegap and im sitting here the whole day and try to solve this problem.
I have a list and i want to filter some data. And before i filter it, i want to download some data from a server and add it to the list. ( the list is local and if someone uses the search function, new data should pop up too).
The idea is that i create the list with jquery and use the listviewbeforefilter-event to download the data from a server and add it to the list. Then jquery should filter the list.
It works fine when i search filter for 2 chars.
But this doesnt work as expected when i search for more than 2 chars. I receive the correct data from the server and it will be added to my list but the there is no more filtering in my original list. So i see my original list + the loaded data. Also the console.log("second") is shown first and then console.log("first). Somehow jquery/phonegap skips the .then part and then comes back to it.
I tried to put the 3 lines ($ul.html( content );$ul.listview( "refresh" );$ul.trigger( "updatelayout");) below the second console.log and then the filter of my local data works but the data from the server wont be shown.
I hope someone can help me with this weird problem.
Heres my code for the listviewbeforefilter-event:
<html> <head> <meta charset="utf-8"> <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" /> <title>Listview Autocomplete - jQuery Mobile Demos</title> <link rel="stylesheet" href="css/jquery.mobile-1.3.2.min.css" /> <script src="cordova.js"></script> <script src="js/jquery-2.0.3.min.js"></script> <script src="js/jquery.mobile-1.3.2.min.js"></script> <script> $( document ).on( "pageinit", "#myPage", function() { $( "#autocomplete" ).on( "listviewbeforefilter", function ( e, data ) { // this is a second list which is a backup. It is needed because after each search the original list is flooded with old entries. var content = document.getElementById("autocomplete2").innerHTML; var requestdata = ""; var $ul = $( this ); $input = $( data.input ), value = $input.val(); // ajax call returns cities with at least 3 characters if ( value && value.length > 2 ) { $.ajax({ url: "http://gd.geobytes.com/AutoCompleteCity", dataType: "jsonp", crossDomain: true, data: { q: $input.val() } }) // The response is saved in html which i append to the original content .then( function ( response ) { var html = ""; console.log("first"); $.each( response, function ( i, val ) { html += "<li>" + val + "</li>"; }); content = content + html; $ul.html( content ); $ul.listview( "refresh" ); $ul.trigger( "updatelayout"); }); console.log("second"); } }); }); </script> and that is the body with the list:
</head> <body> <div data-role="page" id="myPage"> <div data-role="header" data-theme="f"> <h1>Listview </h1> </div><!-- /header --> <div data-role="content"> <div class="content-primary"> <ul id = "autocomplete" data-role="listview" data-filter="true" data-filter-placeholder="Search people..." data-filter-theme="d"data-theme="d" data-divider-theme="d"> <li data-role="list-divider">A</li> <li><a href="index.html">Adam Kinkaid</a></li> <li><a href="index.html">Alex Wickerham</a></li> <li><a href="index.html">Avery Johnson</a></li> </ul> </div><!--/content-primary --> </div><!-- /content --> <script type="text/javascript" charset="utf-8"> $(function(){ $( "#autocomplete2" ).hide(); }); </script> <ul id = "autocomplete2" data-role="listview" data-filter-theme="d"data-theme="d" data-divider-theme="d"> <li data-role="list-divider">A</li> <li><a href="index.html">Adam Kinkaid</a></li> <li><a href="index.html">Alex Wickerham</a></li> <li><a href="index.html">Avery Johnson</a></li> </ul> </div><!-- /page --> </body> </html>
-10913752 0 I solve the problem with this code.and we shold to use interface "IPlugin" in a seperate class library and use in other project.
Assembly objAssembly = Assembly.LoadFrom("Company.dll"); Type objAssemblyType = objAssembly.GetType(); foreach (Type type in objAssembly.GetTypes()) { if (type.IsClass == true) { var classInstance = objAssembly.CreateInstance(type.ToString()) as IPlugin; lblFullName.Text = classInstance.FullName("Mr. "); } }
-11505090 0 I have had this problem with append in IE to. I solved with changing append() to appendTo(). So instead of $(a).append(b);, write $(b).appendTo(a);
Hopes this works for you as it did for me :)
-26946564 0With bind, that Binds words to a specified context (in this case local context of function), and compose function, I get:
cascade: func [ times template start ] [ use [?1] [ ?1: start template: compose [?1: (template)] loop times bind template '?1 ?1 ] ] cascade 8 [?1 * 2] 1 == 256 cascade 3 [add 4 ?1] 5 == 17 val: 4 cascade 3 [add val ?1] 5 == 17 cascade2: func [ times template1 start1 template2 start2 /local **temp** ] [ use [?1 ?2] [ ; to bind only ?1 and ?2 and to avoid variable capture ?1: start1 ?2: start2 loop times bind compose [**temp**: (template1) ?2: (template2) ?1: **temp**] '?1 ?1 ] ] cascade2 5 [?1 * ?2] 1 [?2 + 1] 1 == 120 cascade2 5 [?1 + ?2] 1 [?1] 0 == 8
-36072028 0 The following works for me:
try (InputStream stream = Test.class.getResourceAsStream("/Test.xml")) { StreamSource source = new StreamSource(stream); final XML xml = new XMLDocument(source); } With the input file's hex dump:
FF FE 3C 00 3F 00 78 00 6D 00 6C 00 20 00 76 00 65 00 72 00 73 00 69 00 6F 00 6E 00 3D 00 27 00 31 00 2E 00 30 00 27 00 20 00 65 00 6E 00 63 00 6F 00 64 00 69 00 6E 00 67 00 3D 00 27 00 55 00 54 00 46 00 2D 00 31 00 36 00 27 00 3F 00 3E 00 3C 00 58 00 20 00 69 00 64 00 3D 00 22 00 31 00 22 00 2F 00 3E 00 As far as I can tell, in your example you are converting the contents of the file to a string. But this is problematic because you actually throw away the encoding when you convert bytes to string. When the SAX parser converts the string to a byte array, it decides it will be UTF-8, but the prolog states that it is UTF-16 and so you have a problem.
Instead, when I use the StreamSource, it just automatically detects the fact that the file is encoded in UTF-16 LE from the BOM.
If you are not using java-7 or up and cannot use try-with-resources, then use the stream.close() as before.
-31500093 0Basically this code relies on a little trick: if you seed the SHA1PRNG for the SUN provider and Bouncy Castle provider before it is used then it will always generate the same stream of random bytes. This is not always the case for every provider though; other providers simply mix in the seed. In other words, they may use a pre-seeded PRNG. In that case the getRawKey method generates different keys for the encrypt and decrypt, which will result in a failure to decrypt.
Basically this horrible code snippet abuses the SHA1PRNG as a Key Derivation Fucntion or KDF. You should use a true KDF such as PBKDF2 if the input is a password or HKDF if the input is a key.
That code snippet should be removed. It has been copied from Android snippets, but I cannot find that site anymore.
-14490919 0It has nothing to do with the inner function being named or not.
In the first screenshot you're inspecting the out variable, which references a function returned but outer. That function has x in its closure scope.
In the second screenshot you're inspecting the outer variable, which references a named global function. In that code snippet you don't have any variable to reference the result or outer(3). If you assign that to a variable just like you do in the first example var out = outer(3) and put a breakpoint after that assignment, you'll be able to see out's closure scope. Alternatively, you can inspect that by adding a "watch expression" of outer(3) in the debugger without the need to modify your code.
In fragment we have to read imageview in oncreateview
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.my_frag_layout2, container); img = (ImageView)view.findViewById(R.id.imgview); img.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent,0); } }); return view; }
-8466589 0 Cannot print variables onto the screen I want to print variables onto the screen of my game. I am using text boxes to display the variables. When I try update the text boxes, the text boxes are blank.
I use an EventListener to update the text boxes:
// Add the EventListener that updates the game HUD addEventListener(Event.ENTER_FRAME, updateHUD);
Here is the 'updateHUD()' function:
public function updateHUD(event:Event) { txtHealth.text = String(player.pHealth); txtDarts.text = String(player.pAmmo); txtScore.text = String(player.pScore); }` If I place txtScore.text = String("score"); within this code, not even "score" is printed. The Text Box is still blank.
I was talking with a friend about this. He said he had a similar issue in his project. His problem had to do with incorrect Text Box settings. The boxes I want to update are set to "Classic Text", "Dynamic Text," and "Singleline."
I have other text boxes that act as "labels." They are displayed just fine on the screen. But I do not try to change them.
Any help would be appreciated.
Thanks, Christian
-24426554 0keySet() does not create a new Set.
It simply offers a view of the keys in your map. It actually provides only a few operations which are iteration (with remove), size, emptiness, clear and contains. You cannot add an element to it otherwise it will throw an UnsupportedOperationException.
when I look some code, I find the following snap.
void ph_library_init_register(struct ph_library_init_entry *ent); #define PH_LIBRARY_INIT_PRI(initfn, finifn, pri) \ static __attribute__((constructor)) \ void ph_defs_gen_symbol(ph__lib__init__)(void) { \ static struct ph_library_init_entry ent = { \ __FILE__, __LINE__, pri, initfn, finifn, 0 \ }; \ ph_library_init_register(&ent); \ } my question is: 1. what is stribute means? 2. when does the code run?
-4618736 0Fixed it by parameterising my command, binding to a new property on my viewmodel and moving Command into the style:
<ToggleButton Margin="0,3" Grid.Row="3" Grid.ColumnSpan="2" IsThreeState="False" IsChecked="{Binding DataContext.IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"> <ToggleButton.Style> <Style TargetType="{x:Type ToggleButton}"> <Setter Property="Content" Value="Select All"/> <Setter Property="Command" Value="{Binding DataContext.SelectAllCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"/> <Style.Triggers> <Trigger Property="IsChecked" Value="True"> <Setter Property="Content" Value="Select None"/> </Trigger> </Style.Triggers> </Style> </ToggleButton.Style> </ToggleButton> Don't you just love WPF sometimes!
-29667596 0 After high traffic Cassandra WriteTimeoutExceptionI'm experimenting with cassandra to use it for storing tracking data. I process get requests (300 req/sec) with tracking information through django with uwsgi on nginx. The django application writes to cassandra (single cluster with 3 RF) directly. For this im taking the cassandra-driver (2.5.0).
After restarting all relevant services the whole thing works for about two hours. Then the server goes down and produces a server error 500.
Currently i don't know where the bottleneck is. Syslog show normal I/O activity on my system also CPU is just used by 32%.
I'm working primarily with counters. My tables look like this:
CREATE TABLE rollup_hour_counter ( name text, player_id text, hour timestamp, "count" counter, PRIMARY KEY ((name, player_id), hour) ) My code to write into cassandra looks like this:
rows = session.execute('UPDATE rollup_hour_counter ' 'SET count = count + 1' 'WHERE player_id=\'%s\' AND hour=\'%s:00:00\' AND name = \'name\'' % (player_uuid, date_now_hour)) I did some research on the errors in the log files.
uwsgi logs show:
Thu Apr 16 07:44:04 2015 - uwsgi_response_writev_headers_and_body_do(): Broken pipe [core/writer.c line 296] during GET /t/i/7bcdd5e185fd4608b0d3c3451f5ec56a/ (146.58.126.229)
cassandra log shows:
WARN [SharedPool-Worker-12] 2015-04-16 07:44:50,424 AbstractTracingAwareExecutorService.java:169 - Uncaught exception on thread Thread[SharedPool-Worker-12,5,main]: {} java.lang.RuntimeException: org.apache.cassandra.exceptions.WriteTimeoutException: Operation timed out - received only 0 responses. at org.apache.cassandra.service.StorageProxy$DroppableRunnable.run(StorageProxy.java:2174) ~[apache-cassandra-2.1.4.jar:2.1.4] at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) ~[na:1.7.0_76] at org.apache.cassandra.concurrent.AbstractTracingAwareExecutorService$FutureTask.run(AbstractTracingAwareExecutorService.java:164) ~[apache-cassandra-2.1.4.jar:2.1.4] at org.apache.cassandra.concurrent.SEPWorker.run(SEPWorker.java:105) [apache-cassandra-2.1.4.jar:2.1.4] at java.lang.Thread.run(Thread.java:745) [na:1.7.0_76] Caused by: org.apache.cassandra.exceptions.WriteTimeoutException: Operation timed out - received only 0 responses. at org.apache.cassandra.db.CounterMutation.grabCounterLocks(CounterMutation.java:146) ~[apache-cassandra-2.1.4.jar:2.1.4] at org.apache.cassandra.db.CounterMutation.apply(CounterMutation.java:122) ~[apache-cassandra-2.1.4.jar:2.1.4] at org.apache.cassandra.db.CounterMutation.apply(CounterMutation.java:122) ~[apache-cassandra-2.1.4.jar:2.1.4] at org.apache.cassandra.service.StorageProxy$8.runMayThrow(StorageProxy.java:1147) ~[apache-cassandra-2.1.4.jar:2.1.4] at org.apache.cassandra.service.StorageProxy$DroppableRunnable.run(StorageProxy.java:2171) ~[apache-cassandra-2.1.4.jar:2.1.4] ... 4 common frames omitted
nginx logs show:
2015/04/16 07:43:57 [error] 2111#0: *268738 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 82.115.124.102, server: server.someservice.com, request: "GET [...] HTTP/1.1", upstream: "uwsgi://unix:///tmp/track.sock", host: "server2.someotherservice.com", referrer: "[..]"
So first I thought that the uwsgi processes and sockets were responsible. I added some worker processes increased buffer size but no help.
Second i tuned some cassandra settings but no help:
My cassandra settings look like this:
num_tokens: 256 hinted_handoff_enabled: true max_hint_window_in_ms: 10800000 # 3 hours hinted_handoff_throttle_in_kb: 1024 max_hints_delivery_threads: 2 batchlog_replay_throttle_in_kb: 1024 authenticator: AllowAllAuthenticator authorizer: AllowAllAuthorizer permissions_validity_in_ms: 2000 partitioner: org.apache.cassandra.dht.Murmur3Partitioner data_file_directories: - /var/lib/cassandra/data commitlog_directory: /var/lib/cassandra/commitlog disk_failure_policy: stop commit_failure_policy: stop key_cache_size_in_mb: key_cache_save_period: 14400 row_cache_size_in_mb: 0 row_cache_save_period: 0 counter_cache_size_in_mb: counter_cache_save_period: 7200 saved_caches_directory: /var/lib/cassandra/saved_caches commitlog_sync: periodic commitlog_sync_period_in_ms: 10000 commitlog_segment_size_in_mb: 32 seed_provider: - class_name: org.apache.cassandra.locator.SimpleSeedProvider parameters: # seeds is actually a comma-delimited list of addresses. # Ex: "<ip1>,<ip2>,<ip3>" - seeds: "127.0.0.1" concurrent_reads: 96 concurrent_writes: 96 concurrent_counter_writes: 96 file_cache_size_in_mb: 1512 memtable_allocation_type: heap_buffers memtable_flush_writers: 96 index_summary_capacity_in_mb: index_summary_resize_interval_in_minutes: 60 trickle_fsync: false trickle_fsync_interval_in_kb: 10240 storage_port: 7000 ssl_storage_port: 7001 listen_address: localhost start_native_transport: true native_transport_port: 9042 start_rpc: true rpc_address: localhost rpc_port: 9160 rpc_keepalive: true rpc_server_type: sync rpc_min_threads: 60 rpc_max_threads: 96 thrift_framed_transport_size_in_mb: 15 memtable_flush_after_mins: 60 incremental_backups: false snapshot_before_compaction: false auto_snapshot: true tombstone_warn_threshold: 1000 tombstone_failure_threshold: 100000 column_index_size_in_kb: 64 batch_size_warn_threshold_in_kb: 5 compaction_throughput_mb_per_sec: 16 sstable_preemptive_open_interval_in_mb: 50 read_request_timeout_in_ms: 5000 range_request_timeout_in_ms: 10000 write_request_timeout_in_ms: 2000 counter_write_request_timeout_in_ms: 5000 cas_contention_timeout_in_ms: 1000 truncate_request_timeout_in_ms: 60000 request_timeout_in_ms: 10000 cross_node_timeout: false endpoint_snitch: SimpleSnitch dynamic_snitch_update_interval_in_ms: 100 dynamic_snitch_reset_interval_in_ms: 600000 dynamic_snitch_badness_threshold: 0.1 request_scheduler: org.apache.cassandra.scheduler.NoScheduler server_encryption_options: internode_encryption: none keystore: conf/.keystore keystore_password: cassandra truststore: conf/.truststore truststore_password: cassandra # More advanced defaults below: # protocol: TLS # algorithm: SunX509 # store_type: JKS # cipher_suites: [TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_RSA_WITH_AES_256_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA] # require_client_auth: false client_encryption_options: enabled: false keystore: conf/.keystore keystore_password: cassandra # require_client_auth: false # Set trustore and truststore_password if require_client_auth is true # truststore: conf/.truststore # truststore_password: cassandra # More advanced defaults below: # protocol: TLS # algorithm: SunX509 # store_type: JKS # cipher_suites: [TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_RSA_WITH_AES_256_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA] internode_compression: all inter_dc_tcp_nodelay: false Does someone have an idea where the bottleneck is?
-34317571 0 how to work around with fusion table styles limited to 5I have a fusion table. I use the following javascript code to toggle 2 styles.
fusionTableLayer.setOptions({ styles: styles1 }); fusionTableLayer.setOptions({ styles: styles2 }); Problem is my style2 has more than 7 styles. But because of the limitation of fusiontable, the 6th and 7th styles doesn't work. How can work around this?
stylesIMD = [{ where: 'myVar <= 5', polygonOptions: { fillColor: '#27FF24', } }, { where: 'myVar > 5 AND myVar <= 10', polygonOptions: { fillColor: '#7BFB1E', } }, { where: 'myVar > 10 AND myVar <= 20', polygonOptions: { fillColor: '#D1F71A', } }, { where: 'myVar > 20 AND myVar <= 30', polygonOptions: { fillColor: '#F4C015', } }, { where: 'myVar > 30 AND myVar <= 40', polygonOptions: { fillColor: '#F06110', } }, { where: 'myVar > 40 AND myVar <= 50', polygonOptions: { fillColor: '#ED0B15', } }, { where: 'myVar > 50', polygonOptions: { // fillColor: '#5C0517', strokeWeight: strokeWeight } }];
-23088546 0 Getting day of the week With this code, I get the days that make up a given month, but if I want to get if the month starts on a Monday or Tuesday, as I do?
Calendar mycal = new GregorianCalendar(anni, Calendar.FEBRUARY, 1); int giorni = mycal.getActualMaximum(Calendar.DAY_OF_MONTH); // 28
-33493114 0 Try this,
on your blade something link below.
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-6"> <div class="form-group {{ $errors->has('name') ? 'has-error' : '' }} control-required"> {!! Form::label('title', 'Title') !!}<span class="mand_star"> *</span> {!! Form::text('title', isset($news->title) ? $news->title : \Input::old('title'), [ 'class' => 'form-control', 'placeholder' => 'News Title', 'required' => 'required' ]) !!} <span class="error_span"> {{ $errors->first('title') }}</span> </div> </div> On your controller something like.
if ($validation->fails()) { return redirect()->route('your route path')->withErrors($validation)->withInput(); } it works for all individual input fields also fills old data in that field.
hope it helps.
-25694195 0You can use
window.history.go(-2) //Go two pages back or the same method twice
history.back(); //Go one page back history.back(); //Go another one page back
-2634538 0 Why not use after_create callback and create the feedback in that method?
-16234919 0When no charset is defined in the content-type header of your HTTP request, resteasy assumes 'charset=US-ASCII'. See org.jboss.resteasy.plugins.providers.multipart.InputPart:
/** * If there is a content-type header without a charset parameter, charset=US-ASCII * is assumed. * <p> * This can be overwritten by setting a different String value in * {@link org.jboss.resteasy.spi.HttpRequest#setAttribute(String, Object)} * with this ("resteasy.provider.multipart.inputpart.defaultCharset") * String`enter code here` as key. It should be done in a * {@link org.jboss.resteasy.spi.interception.PreProcessInterceptor}. * </p> */ So, as a work-around you can do the following:
@Provider @ServerInterceptor public class CharsetPreProcessInterceptor implements PreProcessInterceptor { @Override public ServerResponse preProcess(HttpRequest request, ResourceMethod method) throws Failure, WebApplicationException { request.setAttribute(InputPart.DEFAULT_CHARSET_PROPERTY, "charset=UTF-8"); return null; } }
-28973645 0 How do the parameters in ruby '.each do' for-loops work? What's confusing me in the code below is how the parameters state and abbrev match up with the keys and and the values of the hash? Or in other words, how is state matched up with 'oregon' and abbrev with 'OR' (if the parameters matched words in the hash, then I could understand that)
Are they matched up correctly because the first parameter is paired with the first value in the code block?
states = { 'Oregon' => 'OR', 'Florida' => 'FL', 'California' => 'CA', 'New York' => 'NY', 'Michigan' => 'MI' } states.each do |state, abbrev| puts "#{state} is abbreviated #{abbrev}" end The output of this code:
Oregon is abbreviated OR Florida is abbreviated FL California is abbreviated CA New York is abbreviated NY Michigan is abbreviated MI Sorry for not being able to put my question across clearly, still new to this :S
Thanks!
-14423464 0When you use the initializer list you can omit the (), when using a parameterless constructor. It does not matter with the new Cat() is inside the list or not.
-38888252 0Add changeHash: true from where you are redirecting. And then use 'history.back()' or 'history.go(-1)' from your current page. It will only take you 1 page back.
$.mobile.changePage("yourpage.html",{ transition: "flip", changeHash: true});
-13100760 0 As i remember a limitation for request to google maps api is 250 per day for one application. I also remeber that google can stop responce when you send to many request for some part of time. Tell what string did you get from google maps api with this 26th point?
-31106674 0ViewPatterns is probably the way to go here. Your code doesn't work because you need to call viewl or viewr on your Seq first to get something of type ViewL or ViewR. ViewPatterns can handle that pretty nicely:
{-# LANGUAGE ViewPatterns #-} foo (S.viewl -> S.EmptyL) = ... -- empty on left foo (S.viewl -> (x S.:< xs)) = ... -- not empty on left Which is equivalent to something like:
foo seq = case S.viewl seq of S.EmptyL -> ... (x S.:< xs) -> ...
-25744161 0 Can we change in method signature which will work for previous signature in Axis2 I have a webservice with signature public String m1(String s1, String s2) and I wanted to update this signature to public String m1(String s1, String s2, Object... args). Will it work for client calling m1(String s1, String s2)? Will it be a backword compatible?
I tried calling but it is throwing an exception as:
Exception in thread "main" java.lang.AbstractMethodError: SampleService.m1(Ljava/lang/String;Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String; at TestWsClient.main(TestWsClient.java:24)
-40307086 0 The gradient you see comes from safari default style.
You can remove it with -webkit-appearance:none;
Read more about -webkit-appearance here
-2385186 0 Check if Internet Connection Exists with Ruby?Just asked how to check if an internet connection exists using javascript and got some great answers. What's the easiest way to do this in Ruby? In trying to make generated html markup code as clean as possible, I'd like to conditionally render the script tag for javascript files depending on whether or not an internet condition. Something like (this is HAML):
- if internet_connection? %script{:src => "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js", :type => "text/javascript"} - else %script{:src => "/shared/javascripts/jquery/jquery.js", :type => "text/javascript"}
-8020748 0 IndicatingAjaxButton works only once I have derived a class from IndicatingAjaxButton (which is the button to a form). But the IAjaxIndicatorAware does only work once, i.e. if the validation of the form fails I print feedback messages within the form. During the 1st request the "onProgress-Circle" is shown. But if I click on the button again (after I made the right input on the form), there is no "onProgress-Circle" anymore.
I took a look in the generated HTML: 1) Before the first click, there is a img tag, which gets displayed when the request is started 2) After the first request is processed, this img tag is removed.
This are the evaluation steps that are returned from the server:
<evaluate><![CDATA[var e = Wicket.$('previouse--ajax-indicator'); if (e != null && typeof(e.parentNode) != 'undefined') e.parentNode.removeChild(e);]]></evaluate> This I guess leads to removing all childs from the button, also the img tag. Is this a bug or do I use the button in a wrong way?
I use Wicket 1.5
Thanks and kind regards, Soccertrash
-29360114 1 Django model filter compare month failSuppose I have this model:
class User(models.Model): id = models.AutoField(primary_key=True) username = models.CharField(max_length=10) last_login = models.DateTimeField(null=True) Here is one of the records in database,
id=15, username='yhbohh' last_login='2015-03-31 10:57:18' I would like to get a number count of objects with last login of month=3.
I tried in shell,
User.objects.filter(last_login__year=2015).count() # return 80 User.objects.filter(last_login__month=3).count() # return 0 User.objects.filter(last_login__day=31).count() # return 0 May I know why the last 2 queries return no records? I have searched from the other questions and notice than someone may suggest to use date range comparison to solve this problem. But I just wanna know the root cause of this unexpected result.
Thanks a lot!
-36823661 0 make input file variableI will like to get this script process csv files "$inputFilename = 'westmike1.csv';" with different names, when a import link to the file is click. At the moment I can go beyond process one file, and for me to use this script at that it will make me duplicate them.
Please I need an advice on this thanks.
error_reporting(E_ALL | E_STRICT); ini_set('display_errors', true); ini_set('auto_detect_line_endings', true); $inputFilename = 'westmike1.csv'; $outputFilename = 'westmike1.xml'; // Open csv to read $inputFile = fopen($inputFilename, 'rt'); // Get the headers of the file $headers = fgetcsv($inputFile); // Create a new dom document with pretty formatting $doc = new DomDocument(); $doc->formatOutput = true; // Add a root node to the document $root = $doc->createElement('rows'); $root = $doc->appendChild($root); // Loop through each row creating a <row> node with the correct data while (($row = fgetcsv($inputFile)) !== FALSE) { $container = $doc->createElement('row'); foreach ($headers as $i => $header) { $child = $doc->createElement($header); $child = $container->appendChild($child); $value = $doc->createTextNode($row[$i]); $value = $child->appendChild($value); } $root->appendChild($container); } $strxml = $doc->saveXML(); $handle = fopen($outputFilename, "w"); fwrite($handle, $strxml); fclose($handle); $xml = simplexml_load_file('westmike1.xml') or die("ERROR: Cannot create SimpleXML object"); // open MySQL connection $connection = mysqli_connect("localhost", "mikeshop", "sho****", "mike_shop") or die ("ERROR: Cannot connect"); // process node data // create and execute INSERT queries
-10946503 0 I didn't realise this, and now I feel quite stupid. However, maybe someone who is just starting out will be able to save themselves a few minutes of head-bashing by this answer.
It turns out that changes to the database.yml file are only applied once the apache service is restarted/reloaded. Everything is working fine now.
-27536812 0 const-correctness in void methods and lambda 'trick'I have a method that accepts a reference of an object as const, this method doesn't change anything of the method and the const indicates that, the thing is that this method also calls other method that is within the class and is void, doesn't accept any argument and is also virtual, meaning that the class that extends the base class can override the method BUT it needs to be const as well. Eg:
#include <iostream> class Boz { public: virtual void introduce() const = 0; }; class Foo { public: virtual void callable() const { // ... } void caller(const Boz& object) const { callable(); object.introduce(); } }; class Bar : public Boz { public: void introduce() const { std::cout << "Hi." << std::endl; } }; class Biz : public Foo { public: void callable() const { std::cout << "I'm being called before the introduce." << std::endl; } }; int main(void) { Biz biz; biz.caller(Bar()); return 0; } The output would be:
I'm being called before the introduce. Hi. As you can see callable must to be const in order to be called. If I change and do this:
class Biz : public Foo { public: void callable() { std::cout << "I'm being called before the introduce." << std::endl; } }; It will compile not errors are thrown but the callable method won't be called, but the virtual one as it's defined as const. It's quite obvious.
The trickiest part here:
class Foo { public: virtual void callable() { // ... } void caller(const Boz& object) const { auto trick = [&] () { callable(); }; trick(); object.introduce(); } }; class Biz : public Foo { public: void callable() { std::cout << "I'm being called before the introduce." << std::endl; } }; It works and the callable method is called. No errors like passing 'const ...' as 'this' argument.
What I'm trying to do is to call callable without the need of being const and the reason is simple: The method doesn't change anything, he don't have access to the object that is begin passed as argument on caller method then we assume that he doesn't have the need to be const but the compiler throws an error even that way. The real problem is that callable is virtual and classes can extend the base class, implement their own callable and try to call other methods but can't if it's not const as well.
What I want is pretty much that, is to know how can I call the virtual method without the need of being const (the reason is pretty much that, I'm kind forcing the users that extends the class and override the callable method to only call const methods and this is not what I want) and of course understand what happens with the lambda and why it works.
I'm working on a site with CRUD capabilities for a school project. We're using angular, JSON groovy and MySql for the project. I'm using this code in an HTML file:
$scope.getUsers=function(){ $scope.employees=$http.get('getUsers.groovy').success(function(response){ return response.data } When I run the html page and call the getUser function, I get this error:
syntax error getUsers.groovy:1
The code in the groovy file seems correct:
import groovy.sql.Sql import flexjson.JSONSerializer; import org.json.JSONArray; import org.json.JSONObject; import java.sql.SQLException; import java.sql.ResultSet; import java.sql.ResultSetMetaData; System.out.println("Arrived users"); JSONSerializer serializer = new JSONSerializer(); response.setHeader("Access-Control-Allow-Origin", "*"); sql = Sql.newInstance("jdbc:mysql://localhost:8080/test", "root","", "com.mysql.jdbc.Driver") def query="select c.id,c.Name, c.Address, c.Department from people c order by c.id"; JSONArray json = new JSONArray(); sql.eachRow(query) {row-> JSONObject obj = new JSONObject(); obj.put("id",row.id); obj.put("name",row.Name); obj.put("address",row.Address); obj.put("dept",row.Department); json.put(obj); } out<< json; Any help would be greatly appreciated!! It's for my final project
-24596829 0 package manager for angularjs -14804219 0 web.config prevents file downloadable or viewableI am very new to ASP.net. I visited a website long time ago which I cannot remember the URL now. I wanted to open their CSS file to see the source, but once I clicked the error message says, "you don't have premission to act ........."
Now I want to do the same thing to lock up my files. Even visitors could see the file name, but they are unable to open or download it.
I wonder if it is possible to achieve on ASP.net or IIS7?
Many thanks for suggestions.
-5771554 0The -1 is because integers start at 0, but our counting starts at 1.
So, 2^32-1 is the maximum value for a 32-bit unsigned integer (32 binary digits). 2^32 is the number of possible values.
To simplify why, look at decimal. 10^2-1 is the maximum value of a 2-digit decimal number (99). Because our intuitive human counting starts at 1, but integers are 0-based, 10^2 is the number of values (100).
I'm trying to make a simple program (for learning purposes) using exception handling. What I'm trying to do is:
try: x = int(input()) except ValueError as var: # HERE I WANT TO USE THE 'x' STRING VALUE I know about the the various ways to use the exception message (for instance by using str(var)).
For example, if the input is bla which would cause a ValueError exception, print(var) outputs invalid literal for int() with base 10: 'bla', which is not really usable.
However, I created this program that should use str(var) to my advantage:
try: x = int(input()) except ValueError as var: s = str(var) print('Exception message: ' +s) i=0 while (s[i] != '\''): i = i+1 i = i+1 print_str = '' while (s[i] != '\''): print_str = print_str + str(s[i]) i++ print('print_str = ' + print_str) This program would probably work after a few changes..
So my question is: Is there a more direct way to get the 'x' string value?
-40297651 0Try storing it as bytes:
UUID uuid = UUID.randomUUID(); byte[] uuidBytes = new byte[16]; ByteBuffer.wrap(uuidBytes) .order(ByteOrder.BIG_ENDIAN) .putLong(uuid.getMostSignificantBits()) .putLong(uuid.getLeastSignificantBits()); con.createQuery("INSERT INTO TestTable(ID, Name) VALUES(:id, :name)") .addParameter("id", uuidBytes) .addParameter("name", "test1").executeUpdate(); A bit of an explanation: your table is using BINARY(16), so serializing UUID as its raw bytes is a really straightforward approach. UUIDs are essentially 128-bit ints with a few reserved bits, so this code writes it out as a big-endian 128-bit int. The ByteBuffer is just an easy way to turn two longs into a byte array.
Now in practice, all the conversion effort and headaches won't be worth the 20 bytes you save per row.
-24576683 0Pointing i to a different object does not mutate the (original) object. This is not special to primitives. Say you have a List<List<Object>> or a List<List<String>>:
List<List<String>> wrapper = new ArrayList<List<String>>(); List<String> l1 = new ArrayList<String>(); wrapper.add(l1); l1 = new ArrayList<String>(); l1.add("hello"); for(List<String> list : wrapper) { for(String string : list) { System.out.println(string); } } If you now iterate over wrapper you find it contains 1 empty list. This is equivalent to your first example. Your second example looks like:
List<List<String>> wrapper = new ArrayList<List<String>>(); List<String> l1 = new ArrayList<String>(); wrapper.add(l1); l1.add("hello"); for(List<String> list : wrapper) { for(String string : list) { System.out.println(string); } } In this case the wrapper now contains 1 list with one value in it.
I'm writing a HTTP/HTML script on LoadRunner VuGen 11.50 and I need to inspect the results of a web_custom_request, but the snapshot created is chunked to 100 Kb. It says that "Snapshot Step data exceeds maximum size and cannot be fully displayed..."
Is there a way to modify this maximum size so I can read the complete response of the server?
-137060 0 Too many "pattern suffixes" - design smell?I just found myself creating a class called "InstructionBuilderFactoryMapFactory". That's 4 "pattern suffixes" on one class. It immediately reminded me of this:
http://www.jroller.com/landers/entry/the_design_pattern_facade_pattern
Is this a design smell? Should I impose a limit on this number?
I know some programmers have similar rules for other things (e.g. no more than N levels of pointer indirection in C.)
All the classes seem necessary to me. I have a (fixed) map from strings to factories - something I do all the time. The list is getting long and I want to move it out of the constructor of the class that uses the builders (that are created by the factories that are obtained from the map...) And as usual I'm avoiding Singletons.
-15560334 0ah vb6 :) it's been a long time....
basically, you can't debug .NET code within VB6 IDE.
However, nothing stops you from creating a .NET test project to unit test the .NET dll. And that's what you should have done prior to reference it in VB6.
If you need to track down a specific issue, another way you can use is to write debugging infos to a file/database/event view/... when the dll is in debug mode, like which functions were called, parameters, stack trace...
-10059675 0Just for debugging purposes, try setting the backgroundColor of aLabel and aReflectionView to see where they're being placed.
aLabel.backgroundColor = [UIColor redColor]; aReflectionView.backgroundColor = [UIColor blueColor]; You should see that the aReflectionView is properly centered within its superview, but the aLabel, contained within it, is not. Why not? Because of this line:
UILabel *aLabel = [[UILabel alloc]initWithFrame:CGRectMake(((self.view.bounds.size.width / 2) - 150), 0, 300, 90)]; Since aLabel is contained within aReflectionView, it should be centered within the aReflectionView bounds, not the bounds of self.view. Scroll right to see the change:
UILabel *aLabel = [[UILabel alloc]initWithFrame:CGRectMake(((aReflectionView.bounds.size.width / 2) - 150), 0, 300, 90)]; For your purposes, it may be better to make aLabel simply fill aReflectionView:
UILabel *aLabel = [[UILabel alloc]initWithFrame:aReflectionView.bounds];
-29161726 0 you can use given query.
CREATE TABLE TABLE_NAME1 ( id BIGINT(20) NOT NULL AUTO_INCREMENT, Ctime DATETIME DEFAULT NULL, KEY id (id) ) ENGINE=INNODB AUTO_INCREMENT=286802795 DEFAULT CHARSET=utf8 PARTITION BY RANGE( TO_DAYS(Ctime) ) ( PARTITION p1 VALUES LESS THAN (TO_DAYS('2011-04-02')), PARTITION p2 VALUES LESS THAN (TO_DAYS('2011-04-03')), PARTITION p3 VALUES LESS THAN (TO_DAYS('2011-04-04')), PARTITION p4 VALUES LESS THAN (TO_DAYS('2011-04-05')), PARTITION p5 VALUES LESS THAN (TO_DAYS('2011-04-06')), PARTITION p6 VALUES LESS THAN (TO_DAYS('2011-04-07')) );
-38182509 0 APC cache usage I have to use APC cache just for opcode caching. so is it enough to just enable it from php.ini file with setting variable apc.stat to 'false'? I am already using memcache for object caching. do I need to use APC cache functions like apc_add, apc_fetch etc?
-38204922 0In addition to Rene Vogt's answer, you can use switch statement combined with null conditional operator. It makes code more readable:
switch (var?.ToString()) { case "A": return 1; case "B": return 2; default: return 0; }
-30047256 0 Mongodb, time difference between two checkpoints I m actually developping an application using a Mongodb database. Actually, there's a system with "checkpoints", a user scan an NFC tag when he enters in a place, and scan this same tag to leave this place.
So, in my database, I have something like :
{ "enterDate":"the-date-iso-string-formatted", "leaveDate":"the-date-iso-string-formatted" } Actually, I need to detect what is the time between two different end point. I mean, how much time the user takes to travel from one place, to the next one.
In fact it corresponds to the avg of all the
endPoint[1].enterDate- endPoint[0].leaveDate
What is the best way, or the quickest way to manage this ?
Thanks for advance
-18444544 0Do fetching from the database and processing in a background thread.
Then reduce the number of coordinates in the path using the Douglas–Peucker algorithm:

And cache the results.
-8441369 0 How to force compile-warnings if not all public things are JavaDoc'd?I want to get warnings at compile time for every public thing (class, interface, field, method) which doesn't have a Javadoc comment.
How can I enable this in Eclipse?
-22925858 0If you want simple percentages, randomly pick a number between [0,99], and "assign" ranges to different outcomes. Simply,
- (NSString*)randomWord { uint32_t r = arc4random_uniform(100); if (r < 1) return word1; if (r < 41) return word2; return word3; }
-6290454 0 VS Setup Project - Launch condition for .Net Framework 3.5 or higher I need to create a setup project for my application. I need to add launch condition to make sure user has .Net framework 3.5 or higher installed on his machine. Is there a way to do so?
I have tried creating the setup project in VS 2005, 2008 and 2010. I have also tried setting up the version in launch condition to be 3.5 and then opened the project file in notepad to set "Allow Later Versions" to true, without any success.
The setup still asks me to download .Net framework 3.5 when I have .Net framework 4.0 installed on my system.
Any help will be deeply appreciated.
Thanks, Manjeet
-20631085 0It can return null for some older J2ME devices which might not have support for location (it will work for most recent J2ME devices too). It shouldn't return null for other cases e.g. iOS, Android, Windows Phone etc..
-29939684 0As explained on the Scala homepage the imports from java.lang are done automatically whereas all other classes have to be imported explicitly.
I just found python-snappy on github and installed it via python. Not a permanent solution, but at least something.
-19003011 0 How can I format input fields to form time of day using PHP date() function?I want the user to select a time of day which I then want to convert using the date() function so it can be inserted into a Mysql database datetime table field.
<select name="event-start-time-hours" class="event-time"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8" selected>8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> </select> <select name="event-start-time-mins" class="event-time"> <option value="00" selected >00</option> <option value="05">05</option> <option value="10">10</option> <option value="15">15</option> <option value="20">20</option> <option value="25">25</option> <option value="30">30</option> <option value="35">35</option> <option value="40">40</option> <option value="45">45</option> <option value="50">50</option> <option value="55">55</option> </select> <select name="event-start-timeofday" class="event-time"> <option value="" selected >AM</option> <option value="">PM</option> </select> I tried:
$time = $_POST['event-start-time-mins'] .$_POST['event-start-time-hours']; var_dump($dob = date("H:i:s", $time)); print_r($_POST['event-start-time-hours']); print_r($_POST['event-start-time-mins']); Which returns:
string(8) "01:03:22" 220
So how do I format this correctly? Many thanks.
-21385616 0If you don't wan't to write code at all, just use the FileUtils-class.
import org.apache.commons.io.FileUtils; ... public void yourMethod() { List<String> lines = FileUtils.readLines(yourFile); }
-30280448 0 Change HTML Theme of a specific port I want know that how can we change the theme of page of a specific port from default listing to custom looking theme.
I am looking to change my FTP port 21's theme from default to custom, dont exactly know how to..
-25737201 0 Six degrees of Kevin BaconThere are a couple other posts about degrees of Kevin Bacon, and the answers on those posts are similar to what I came up with myself before looking it up. But it's evident that I'm still doing something wrong from the results I get and the way the performance of my query falls off as I increase the degree of separation from Kevin Bacon.
Here's my query to find all actors with one degree of Kevin Bacon:
match p=(:Person {name:"Kevin Bacon"})-[:ACTED_IN*..2]-(:Person) return p If I understand correctly, that's equivalent to this:
match p=(:Person {name:"Kevin Bacon"})-[:ACTED_IN]->()<-[:ACTED_IN]-(:Person) return p And indeed, both of these queries return the same number of rows. But if I modify the first version of the query and increase the path length to 6 (i.e., three degrees of Kevin Bacon) it returns 978 rows. There are only 133 Person nodes in the database, so I would expect it to return at most 133 rows.
My guess is that it's returning multiple paths to some of the Person nodes. How do I tell it to return only the shortest path to each? Basically, I want to perform a single depth-first or breadth-first search. I think it might involve WITH, but I don't really understand how to use that yet.
Basically, I have a bunch of images that I can combine into a single image(an atlas) or use individually. For testing/designing purposes, I would like to keep all the images separate but for release they should all be combine into the atlas(for non-embeddable compilers) or embedded.
e.g., suppose I have 100 sprites. I can create a single atlas for them, use them all individually unembedded, or embed the atlas, or embed all the image.
I'd like to start out with the individual+unembedded case for development then move to the embedded atlas case or embedded individual case(but I think this is probably not as good as the embedded atlas).
Is there an easy way to set this up in C# so the transition will be minimal?
The problem with the embedded atlas is that I would have to convert loading images(simple Image.FromFile into extracting images from the atlas).
Just curious what would be a good approach to remove the need for rewriting a lot of code in the future when the switch is made.
I could have something like Image.FromAtlas that essentially figures out the details(uses FromFile if we are in "development mode" or extracts the image from the atlas if in production... I think the embedded case would be rather trivial to implement).
What do you think? Thanks.
-30363178 0 I would like drop down menu selections to bring post different images when different choices are selectedHere is my basic pull down selection tabs. How do I get each choice to post a different image (preferably html source images) when selected.
I would like the images to post within the div as well if possible.
<div id= "PERSONAL"> <p id= "Range"> Preferred Distance </p> <select class= "Distance" onchange="report(this.value)"> ` <option value="Pick3">Pick Your Range</option> <option value="100 Miles">100 Miles</option> <option value="1000 Miles">1000 Miles</option> <option value="More than 2000 Miles">More than 2000 Miles</option> <option value="Around the World">Around the World</option> </select> <p id= "Weather"> Preferred Weather </p> <select class= "Weather" onchange="report(this.value)"> <option value="Pick2">Pick Your Weather</option> <option value="Cold">Cold</option> <option value="Mild">Mild</option> <option value="Hot">Hot</option> <option value="Anything">Anything</option> </select> <p id= "Moisture"> Wet or Dry </p> <select class= "Moisture" onchange="report(this.value)"> <option value="Pick1">Pick Your Moisture</option> <option value="Desert">Desert Dry</option> <option value="Moderate">Wet and Dry</option> <option value="Rainy">Jungle Wet</option> <option value="Snow">Snow Time!</option> </select> </div>
-32871952 0 The following seems to work:
match (aType:Type:Class)-[:ANNOTATED_BY]->()-[:OF_TYPE]->(anAnnotationType:Type), (aType:Type)-[:DECLARES]->(aMethod:Method) optional match (aMethod)-[:ANNOTATED_BY]->()-[:OF_TYPE]->(tType:Type) with anAnnotationType, aMethod, tType where anAnnotationType.fqn = "com.mycompany.services.Service" and aMethod.name =~ "update.*" and ((tType is null) or not (tType.fqn = "com.mycompany.services.Transact")) return aMethod.name, tType
-10181990 0 jQuery selector, .hide() UL and LI elements I am trying to have a category index of expandable/colapsable elements, and when the user clicks a category it is rebuilt with an id of 'catSel'.
The problem is when the user clicks an <li> and the 'catSel' id is added to it, it will still be affected by the .hide(); and I don't want it to be. I should note that I have it working if the user clicks a <ul> element it will not be affected by the .hide();
What I really want is that if a <ul> or any of its <li> elements have the id of 'catSel' that that <ul> will not be affected by the .hide();
Here is the code and a sample link, you can see how the <ul> is not expanded but one of its <li> children has an id of 'catSel'
EDIT: Sorry for the bad explanation, I still can't explain it very well but I want it so that if a <ul> or one of its child <li> elements has an id="catSel" that it will not be affected by $('ul.catList:not(.level-0) li:has(ul):not(#catSel)').children('ul').hide();.
UPDATE:
I added this code:
// If an elementwith its id="catSel" show all of its parents and also update the parents class $('#catSel').parents().show(); $('#catSel').parents().removeClass('plusimageapply'); $('#catSel').parents().addClass('minusimageapply'); and now it seems to be working how I wanted it to. Thank you everyone who tried to make sense of my question and help me out.
jsFiddle: http://jsfiddle.net/nNR9W/
HTML:
<li> <a href="foo">Catalog Section 4</a> <ul class="level-1 catList"><li class="plusimageapply"> <a href="foo">Quick Disconnects</a> <ul class="level-2 catList" style="display: none; "> <li id="catSel" class="selectedimage"> <a href="foo">Foster</a></li> <li class="selectedimage"> <a href="foo">General Pump</a> </li> <li class="selectedimage"> <a href="foo">Hansen</a> </li> <li class="selectedimage"> <a href="foo">Parker</a> </li> </ul> </li> <li class="selectedimage"> <a href="foo">Quick Disconnects O-Rings</a> </li> </ul> jQuery:
$(document).ready(function() { // Set expandable UL elements class to 'plusimageapply' $('ul.catList li:has(ul):not(#catSel)').addClass('plusimageapply'); // Set unexpandable LI elements class to 'selectedimage' $('ul.catList li:not(:has(ul))').addClass('selectedimage'); // Set expanded UL elements class to 'minusimageapply' $('ul.catList li#catSel:has(ul)').addClass('minusimageapply'); // Hide expandable UL elements that are not currently selected with ID 'catSel' $('ul.catList:not(.level-0) li:has(ul):not(#catSel)').children('ul').hide(); // **** FIXED MY PROBLEM **** // If an elementwith its id="catSel" show all of its parents and also update the parents class $('#catSel').parents().show(); $('#catSel').parents().removeClass('plusimageapply'); $('#catSel').parents().addClass('minusimageapply'); // ************************** // Function for expand/collapse elements $('ul.catList:not(.level-0) li:has(ul)').each(function(column) { $(this).click(function(event) { if (this == event.target) { if ($(this).is('.plusimageapply')) { $(this).children('ul').show(); $(this).removeClass('plusimageapply'); $(this).addClass('minusimageapply'); } else { $(this).children('ul').hide(); $(this).removeClass('minusimageapply'); $(this).addClass('plusimageapply'); } } }); }); });
-21038781 0 @echo off pushd c:\test_dir for /r %%a in (*) do ( java -Durl=http://localhost:8983/solr/update/extract?literal.id=%%~nxa -Dtype=application/word -jar post.jar "%%~dpfnxa" ) This will process the files recursively.You can filter the files "wild-cards" expression -> for /r %%a in (*doc) or do it only for the current folder for %%a in (*) .
Is possible to delete only file content in Google Drive? i.e I wanted to delete content stream of a particulate file, not the file.
If possible, can some one explain the process?
Thanks in advance.
-691194 0 Why is my implementation of C++ map not storing values?I have a class called ImageMatrix, which implements the C++ map in a recursive fashion; the end result is that I have a 3 dimensional array.
typedef uint32_t VUInt32; typedef int32_t VInt32; class ImageMatrix { public: ImageMatrixRow operator[](VInt32 rowIndex) private: ImageMatrixRowMap rows; }; typedef std::map <VUInt32, VInt32> ImageMatrixChannelMap; class ImageMatrixColumn { public: VInt32 &operator[](VUInt32 channelIndex); private: ImageMatrixChannelMap channels; }; typedef std::map<VUInt32, ImageMatrixColumn> ImageMatrixColumnMap; class ImageMatrixRow { public: ImageMatrixColumn operator[](VUInt32 columnIndex); private: ImageMatrixColumnMap columns; }; typedef std::map<VUInt32, ImageMatrixRow> ImageMatrixRowMap; Each operator simply returns a map-wrapper class within, like so:
ImageMatrixRow ImageMatrix::operator[](VInt32 rowIndex) { return rows[rowIndex]; } ImageMatrixColumn ImageMatrixRow::operator[](VUInt32 columnIndex) { return columns[columnIndex]; } VInt32 &ImageMatrixColumn::operator[](VUInt32 channelIndex) { return channels[channelIndex]; } Basically, when I set the value as say 100, and test the value to cout, it shows as 0, and not the number to which I had set it.
for (VUInt32 a = 0; a < GetRowCount(); a++) { for (VUInt32 b = 0; b < GetColumnCount(); b++) { for (VUInt32 c = 0; c < GetChannelCount(); c++) { VInt32 value = 100; matrix[a][b][c] = value; VInt32 test = matrix[a][b][c]; // pixel = 100, test = 0 - why? cout << pixel << "/" << test << endl; } } } Note: I've altered the original code for this example so that it takes up less space, so some syntax errors may occur (please don't point them out).
-31289958 0 auto fix errors when removing a user control propertyWhen I remove a user control property that I have created and used in a project. There will be as many errors as times I have used control in project. For example imagine I have user control and it has a property named p1. when I remove p1 I get errors saying myusercontrol.p1 doesn't exist.
Is there a way to get rid of them automatically?
-35638617 0You code is not formatted with indents, so this may be wrong.
I suspect your indentation results in if j in screen: running after the for j... loop, not in it. Also, read the definition of pass.
Hello I need to compute logarithms on my stm32. I use arm-none-eabi-gcc. When I add -L/opt/tools/Sourcery_G++_Lite/arm-none-eabi/lib/ in my Makefile microcontroller stop to work. Unfortunately I can't debug my program because there is no debag pins on my device and I load program to flash via bootloader. I not use any math functioins from libraries - i just add library path to Makefile. Here is my full makefile:
OUTPUTDIR = $(BUILDDIR)/../../output DEPDIR = $(BUILDDIR)/.dep PWD = $(shell pwd) COMMONFLAGS = -mcpu=cortex-m3 -mthumb -ggdb3 CFLAGS += $(COMMONFLAGS) -Os $(INCLUDES) -I. CFLAGS += -std=c99 -Wall -Wextra -static -fdata-sections -ffunction-sections -fno-hosted -fno-builtin CFLAGS += -nostdlib -nodefaultlibs CFLAGS += -mapcs-frame -msoft-float CFLAGS += -MD -MP -MF $(DEPDIR)/$(@F).d LDFLAGS = $(COMMONFLAGS) -static LDFLAGS += -fno-exceptions -ffunction-sections -fdata-sections LDFLAGS += -static -Xlinker --gc-sections #LDFLAGS += -L/opt/tools/dima/Sourcery_G++_Lite/arm-none-eabi/lib/ ASFLAGS = $(COMMONFLAGS) CFLAGS += -DUSE_STDPERIPH_DRIVER CROSS = /opt/tools/Sourcery_G++_Lite/bin/arm-none-eabi GCC = $(CROSS)-gcc AS = $(CROSS)-as SIZE = $(CROSS)-size OBJCOPY = $(CROSS)-objcopy OBJDUMP = $(CROSS)-objdump NM = $(CROSS)-nm COBJ = $(addprefix $(BUILDDIR)/, $(CSRC:.c=.c.o)) ASMOBJ = $(addprefix $(BUILDDIR)/, $(ASMSRC:.s=.s.o)) OBJ = $(COBJ) $(ASMOBJ) V = $(if $(VERBOSE), , @) all: prebuild $(BUILDDIR)/$(TARGET).elf $(LDSCRIPT) @$(SIZE) $(BUILDDIR)/$(TARGET).elf @$(OBJCOPY) -O binary $(BUILDDIR)/$(TARGET).elf $(BUILDDIR)/$(TARGET).bin @$(OBJCOPY) -O ihex $(BUILDDIR)/$(TARGET).elf $(BUILDDIR)/$(TARGET).hex @$(OBJDUMP) -h -S -z $(BUILDDIR)/$(TARGET).elf > $(BUILDDIR)/$(TARGET).lss @$(NM) -n $(BUILDDIR)/$(TARGET).elf > $(BUILDDIR)/$(TARGET).sym @mkdir -p $(OUTPUTDIR) @cp $(BUILDDIR)/$(TARGET).bin $(OUTPUTDIR) @echo ======================================================================= $(BUILDDIR)/$(TARGET).elf: $(OBJ) @echo Linking $@ $(GCC) $(LDFLAGS) -T $(PWD)/$(LDSCRIPT) -o $@ $(OBJ) -lm $(COBJ): $(BUILDDIR)/%.c.o : %.c @echo Compiling $< @-mkdir -p $(@D) $(GCC) $(CFLAGS) -c $< -o $@ $(ASMOBJ): $(BUILDDIR)/%.s.o : %.s @echo Assembling $< @-mkdir -p $(@D) $(V)$(AS) $(ASFLAGS) -c ./$< -o $@ -include $(shell mkdir -p $(DEPDIR) 2>/dev/null) $(wildcard $(DEPDIR)/*) .PHONY: clean output clean: rm -rf $(BUILDDIR) What i do wrong? Thanks.
-22040153 0I'd use a Timer object.
There's a full example:
public class TimerActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); MyTimerTask myTask = new MyTimerTask(); Timer myTimer = new Timer(); myTimer.schedule(myTask, 3000, 1500); } // In this class you'd define an instance of your `AsyncTask` class MyTimerTask extends TimerTask { MyAsyncTask atask; final class MyAsyncTask extends AsyncTask<Param1, Param2, Param3> { // Define here your onPreExecute(), doInBackground(), onPostExecute() methods // and whetever you need ... } public void run() { atask = new MyAsyncTask<Param1, Param2, Param3>(); atask.execute(); } } }
-27045735 0 The Implicit Grant Type is being seen by many (lucadegasperi's oauth2-server-laravel among others) as the least secure of the OAuth2 grant types, therefore I recommend you to use JWT for your service website instead.
To integrate JWT with Laravel, have a look at the following library. It works very well, and is also supported by the popular out-of-the-box API package Dingo for Laravel (https://github.com/dingo/api):
As for the app(s), if the app is a first-party app, go for the OAuth2 password grant as mentioned by Florens Morselli. If it is third-party app, use the authorization code grant instead.
-30457301 0With no client driver at all, you can simply execute the psql command-line then read and process its output. This is particularly useful when invoking it as psql -qAt and/or using \copy.
Otherwise you must have some kind of client driver. Powershell has no built-in support code for the PostgreSQL protocol, so it therefore cannot communicate with PostgreSQL without some kind of client driver. nPgSQL would be the most obvious choice since it integrates well in .NET and is composed only of .NET assemblies. You could probably bundle nPgSQL up as a Powershell extension... but as usual, someone already did that.
Otherwise you probably want to install psqlODBC, which is a simple msiexec to install then usable using the usual ODBC support.
(The only reason Powershell can talk to MS SQL without installing additional drivers is that drivers for MS SQL are built in).
-25030459 0 Convert JObject to type at runtimeI am writing a simple event dispatcher where my events come in as objects with the clr type name and the json object representing the original event (after the byte[] has been processed into the jobject) that was fired. I'm using GetEventStore if anyone wants to know the specifics.
I want to take that clr type to do 2 things:
I have managed to get part 1 working fine with the following code:
var processedEvent = ProcessRawEvent(@event); var t = Type.GetType(processedEvent.EventClrTypeName); var type = typeof(IHandlesEvent<>).MakeGenericType(t); var allHandlers = container.ResolveAll(type); foreach (var allHandler in allHandlers) { var method = allHandler.GetType().GetMethod("Consume", new[] { t }); method.Invoke(allHandler, new[] { processedEvent.Data }); } ATM the issue is that processedEvent.Data is a JObject - I know the type of processedEvent.Data because I have t defined above it.
How can I parse that JObject into type t without doing any nasty switching on the type name?
-30606818 0The URL should be HTML encoded, and the query string values should be URL encoded.
The & should be HTML encoded as &, and : and / in the values should be URL encoded as %3A and %2F:
href="http://secure.hostgator.com/~affiliat/cgi-bin/affiliates/clickthru.cgi?id=vpspricing&page=http%3A%2F%2Fwww.hostgator.com%2Fvps-hosting" Breakdown: First the values vpspricing and http://www.hostgator.com/vps-hosting are URL encoded into vpspricing (no change) and http%3A%2F%2Fwww.hostgator.com%2Fvps-hosting so that you can put them in the URL. Then you HTML encode the entire URL so that you can put it in the attribute in the HTML code. It's only the & character that needs to be HTML encoded in this case.
Instead of
static int _difficulty; type this into your GameManager.h
@property int difficulty; You don't have to write the Setter and Getter by yourself, the property-statement do this for you. The Getter/Setter is stored in the instance of GameManager you use. So get the instance of you GameManager and there you set like this:
[MyGameManagerInstance setDifficulty:0]; and get like
[MyGameManagerInstance difficulty]; Due to the fact that the difficulty-property is in the .h file, it's part of the Class's API which you can access from other ViewController or Classes.
EDIT: Like you said, you could do this also with the NSUserDefaults. Just put it in like this:
[[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"Difficulty"]; and get it like this:
int myInt = [[NSUserDefaults standardUserDefaults] integerForKey:@"Difficulty"];
-36726504 0 Autohotkey Open Folder of Current Application or Process In this code no open current application folder because the FilePath variable include exe file name
F11:: PID = 0 WinGet, hWnd,, A DllCall("GetWindowThreadProcessId", "UInt", hWnd, "UInt *", PID) hProcess := DllCall("OpenProcess", "UInt", 0x400 | 0x10, "Int", False , "UInt", PID) PathLength = 260*2 VarSetCapacity(FilePath, PathLength, 0) DllCall("Psapi.dll\GetModuleFileNameExW", "UInt", hProcess, "Int", 0, "Str", FilePath, "UInt", PathLength) DllCall("CloseHandle", "UInt", hProcess) Run, Explorer %FilePath% Thanks in advance for any assistance.
-39705323 0 Call different method depending on Bool without if-statement in SwiftIs it possible to call one or another method depending a Bool value? I wish to do this:
var isLocked: Bool { didSet { // This is not Swift but indicates what I'm looking for. self.activityIndicator.(isLocked ? startAnimating() : stopAnimating()) } } I'm looking to do this using existing Swift 2 (or 3) language features; without class extensions.
Possibly a duplicate, but couldn't find.
-1757839 0I assume pageTabPanel isn't defined at the time you trigger the handler. Try to remove the var keyword in front of "var pageTabPanel =" to make it a global variable.
If that works, it's a scope/variable issue. The better solution is to give the tabpanel an id and call Ext.getCmp('tabpanelid').render('contentpanel') in your renderPageTabs method.
Hope that helps.
Regards, Steffen
-34445315 0Basically nscurl --ats-diagnostics <url> just tries all possible variants of connection to server and responses with PASS/FAIL results for each test. You should just find which tests pass for your server and set ATS configuration accordingly.
Here's a good article on ATS and checking server compliance, it also contains an nscurl example.
-23443041 0Try the following code , It may help you
$('.parent').each(function() { $(.keywordsubmit).click(function(e){ $('.parent').hide(); $(this).parent().show(); }); });
-40849963 0 You need to loop over the sheets in the workbook and manipulate each one individually:
Dim sheet As Worksheet For Each sheet In ActiveWorkbook.Worksheets sheet.Columns("A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete Next
-17649190 0 Thanks paul,
I've read through and do another round of research for this and I was using
String url ="http://someurl.com/passfail?parameter={"data1":"123456789","data2":"123456789"}"; String encodedURL = URIUtil.encodeQuery(url); and it gave me status 200, which is a success.
The API I used was from org.apache.commons.httpclient.util.URIUtil.
-13484797 0After investigation it seems that getting a 403 error happens if the account that is set in .setServiceAccountUser("admin.of.my@domain.com") is not a "Super Admin" of the domain.
However in the case above "admin.of.my@domain.com" is indeed a Super Admin of the domain. Also the code works well with any other Super Admin of the domain which leads to believe that there is something wrong with the account "admin.of.my@domain.com" in particular.
If this happens to anyone else - a.k.a. an account set as "Super Admin" which does not work to access Admins-only APIs through Service Accounts - make sure you let us know in the comments below and we'll investigate further if this impacts lots of people.
-6392749 0 i want my shape when hit with inside of stage , rotate and countinue move in true angle forever![My Map][1]
i want simulate Billiard ball in my project. but my code does not work good. when start with (for example) 34 degree , when hit with wall(stage in this example) return with true degree. in flash , as3
public function loop(e:Event) : void { if(luanch) { y += Math.sin(degreesToRadians(rotation)) * speed; x += Math.cos(degreesToRadians(rotation)) * speed; if (x > stage.stageWidth){ rotation -= 90; x = stage.stageWidth; trace("X :" , x , rotation); } else if (x < 0) { rotation += 90; x=3; //rotation += 90; trace("X :" , x , rotation); } if (y > stage.stageHeight) { y = stage.stageHeight; rotation -= 90; trace("Y : " , y , rotation); } else if (y <0) { rotation += 90; //rotation += 90; trace("Y :" , y , rotation); } } } public function degreesToRadians(degrees:Number) : Number { return degrees * Math.PI / 180; } } }
-38353495 0 DomSanitizationService is not a function As people always say there is no question called a dumb question.
I am learning Angular 2.0 following the official tutorial now. It is using rc2.0 as I can see from the packageconfig file. I was trying to suppress the frame work complaining the "Unsafe" url in the iFrame tag.
I have checked the instructions from this Stack Overflow Question and followed everything that's been shown in the LIVE Plunker.
My VS Code doesn't complain anything in the compile time but from the Chrome inspector I can see the error.
Following are the TS file of my project.
import { Component, OnInit, OnDestroy } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { ParcelsService } from './parcels.service'; import { SafeResourceUrl, DomSanitizationService } from '@angular/platform-browser'; import { Parcel } from './mock-parcels'; @Component({ template: ` <h2>Parcels</h2> <div *ngIf="parcel"> <h3>"{{parcel.checkUrl}}"</h3> <iframe width=800 height=500 src="{{safeUrl}}}"></iframe> <p> <button (click)="gotoHeroes()">Back</button> </p> </div> `, providers:[ParcelsService, DomSanitizationService] }) export class HeroDetailComponent implements OnInit, OnDestroy { parcel: Parcel; safeUrl : SafeResourceUrl; private sub: any; constructor( private route: ActivatedRoute, private router: Router, private service: ParcelsService, private sanitizer: DomSanitizationService) {} ngOnInit() { this.sub = this.route.params.subscribe(params => { let id = +params['id']; // (+) converts string 'id' to a number this.parcel = this.service.getParcel(id); }); this.safeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.parcel.checkUrl); } ngOnDestroy() { this.sub.unsubscribe(); } gotoHeroes() { this.router.navigate(['/heroes']); } } Has anyone ever come across similar issue? Please help to find what I have done wrong.
Thanks
-12647043 0You should not be storing numeric data as a string but if you do, then you will need to cast() it to apply a SUM() aggregate to it:
SELECT SUM(CAST(yourcolumn AS DECIMAL(10, 2))) FROM yourtable So your query will be:
select sum(cast(qty as DECIMAL(10, 2))) from inventory i where i.refDocNum = 485 and i.refApp = 'WO' and i.type in (20, 21)
-12710635 0 I suppose it is mandatory to use regex in your assignment... if not i would go for an xml parser...
But if YES I suggest you have a go with Reg Ex buddy
RegexBuddy makes it easier than ever for you to create regular expressions that do what you intend, without any guesswork. Still, you need to test your regex patterns to be 100% sure that they match what you want, and don't match what you don't want.
-1598810 0Is it a high resolution image? which you are trying to load,
-13168742 0Gibberish,
Try the ImageMapster jQuery plugin, which acts on image maps to offer (at v1.2.6) the following features :
The feature you need is the last one listed.
I've not used ImageMapster myself, but the demos are very impressive and indicative of a well written plugin.
-32072930 0 Scrollable Line ChartAm trying to use the ios-charts library based off the MPAndroidCharts; however am having some trouble getting a scrollable graph to work.
By scrollable I mean that I try to show only a portion of the data of the line and that you can scroll horizontally to see more results. E.g I have 30 results and I only show 10 at a time and then scroll horizontally to see more.
Have come up with an approximation by using the method
[self.containerView setVisibleXRangeWithMinXRange:24.0f maxXRange:24.0f]; However this seems to make the scrolling kind of jittery as it keeps on redrawing.
Am looking for an ios-charts example and clarification on methods to see whether I am on the right track or not.
-29008393 0I must say that it works perfectly like it should be.
If you want it to be:
Before After Screen Try this:
final LinearLayout screenRL = (LinearLayout) findViewById(R.id.screenRL); new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 4; i++) { LayoutInflater inflater = getLayoutInflater(); final View view = inflater.inflate(R.layout.dl, null); TextView txtTitleView = (TextView) view.findViewById(R.id.txtTitleView); txtTitleView.setText((i + 1) + ". Post"); Log.i("Check", "Before : "); runOnUiThread(new Runnable() { public void run() { Log.i("Check", "After"); screenRL.addView(view); } }); } runOnUiThread(new Runnable() { public void run() { Log.i("Check", "Screen"); } }); } }).start();
-6029712 0 If you're on Windows, try using setInternet2 so that your IT network thinks that it is Internet Explorer connecting to the internet. Often useful for evading corporate lockdown.
I'm trying to access the first item in an array within an angular.js view like this:
<p class="name-label">{{user_profile.email[0].emailAddress}}</p> My object looks like this:
Object { .... "email": [ { "emailType": "Primary", "emailAddress": "testuser@tp.com" } ], .... } This is not working - I don't get an error - it just doesn't display anything! Any ideas?
Thank you!
-40792557 0 Select past days from CalendarI am trying to open calendar from past days but calendar starts from today and past days.How to show only past days.For example today's date is 24-11-2016,i want to open calendar from 23-11-2016.This is my snippet code
`Calendar c = Calendar.getInstance(); fromYear = c.get(Calendar.YEAR); fromMonth = c.get(Calendar.MONTH); fromDay = c.get(Calendar.DAY_OF_MONTH);`
-1144825 0 can i do caching with php? I have read a few things here and there and about PHP being able to "cache" things. I'm not super familiar with the concept of caching from a computer science point of view. How does this work and where would I use it in a PHP website and/or application.
Thanks!
-34910745 0 What are the best practices for single-instanced classes in java?In my program I have a menu system in which I have a separate class for each menu, for example MainMenu would be a separate class. But the class is only supposed to be instanced once, and after I instance it, it is saved in a list which is all is used for after that. Should I use another solution than a separate class? Or should I make the constructor private and then make a private instance inside the class? I feel like this violates OOP, but I don't see another solution.
-21473611 0 Netbeans swing Master detail sample form delete not workingI'm using NB 7.4, JavaDb , jdk 7.
I tried to work on this example : http://simsam7.blogspot.in/2013/06/quick-crud-application-on-netbeans-73.html
In CRUD, CRU works good, but delete not working,and its not throwing any error also.
My Code for delete button.
int[] selected = masterTable.getSelectedRows(); List<com.fz.PurchaseOrder> toRemove = new ArrayList<com.fz.PurchaseOrder>(selected.length); for (int idx = 0; idx < selected.length; idx++) { com.fz.PurchaseOrder p = list.get(masterTable.convertRowIndexToModel(selected[idx])); toRemove.add(p); entityManager.remove(p); } list.removeAll(toRemove); I done debug, and i think error at entityManager.remove(p).
INFO : Output GUI - The row in table removes/delete good, but when i refresh it shows again.
-36905179 0 video tag volume control is not working in ionicI am using HTML video tag in my ionic app.
<video id="welcomeVideo" poster="img/WelcomeVideo.png" width="100%" preload="metadata" autoplay controls muted><source src="http://myWebsite.com/videos/welcome.mp4" type="video/mp4"/></video> Above code works fine in the browser, but when i run it on Android device, video starts playing as I have used autoplay attribute, but muted attribute doesn't work.
Even when I pause the video, video stops but audio plays in background. Also I am not getting volume control button in the app. But in browser it works without any giving any issue.
Any help will be appreciable.
-31622023 0The best way would be through feature detection in the browser. Since there is not a standard way of detecting touch through CSS. I would just do this JavaScript:
if ('ontouchstart' in document) { // Bring in the necessary CSS optimized for touch }
-15914069 0 Well, it seems like the main issue was with your css. When a mouseover event was triggered, the modalMask element was shown. The problem however was that you placed it on top of everything else with:
position: absolute; ... width: 100%; height: 100%; ... z-index: 1000; This means that you had an invisible layer blocking access to the links, and that's why there was no reaction after the first event.
While troubleshooting, i cleaned up the code for you at: http://jsfiddle.net/Z4ZGZ/18/
The 'close' button doesn't work in the fiddle, but it worked for me locally when i included the script file at the bottom of the body element.
-2000920 0Sometimes jQuery has problems firing the event if top level parent elements have their css overflow property set to anything other than auto.
-36908979 0u can try this plugin contact form 7 AutoSaver , Select some forms to enable auto-save on them, meaning when a user fill the form, without even submitting it, then navigates to another page and comes back or refreshes the page, they will see the data they previously filled still available for them!
https://wordpress.org/plugins/cf7-autosaver/
-36290219 0 Htaccess 301 change old URL I would like change url in my htaccess and using redirect 301 for SEO.
my old url:
RewriteRule ^my-oldurl-(([0-9]+)-[a-zA-z0-9_-]+).html$ index.php?page=my-detail&id=$1&cat=$2 [QSA,L] my new url:
RewriteRule ^my-newurl-(([0-9]+)-[a-zA-z0-9_-]+).html$ index.php?page=my-detail&id=$1&cat=$2 [QSA,L] My last test (error 500):
RewriteRule ^my-oldurl-(([0-9]+)-[a-zA-z0-9_-]+).html ^my-newurl-(([0-9]+)-[a-zA-z0-9_-]+).html [QSA,R=301] Thank you for any advice.
-24922753 0why use [yield]? Apart from it being slightly less code, what's it do for me?
Sometimes it is useful, sometimes not. If the entire set of data must be examined and returned then there is not going to be any benefit in using yield because all it did was introduce overhead.
When yield really shines is when only a partial set is returned. I think the best example is sorting. Assume you have a list of objects containing a date and a dollar amount from this year and you would like to see the first handful (5) records of the year.
In order to accomplish this, the list must be sorted ascending by date, and then have the first 5 taken. If this was done without yield, the entire list would have to be sorted, right up to making sure the last two dates were in order.
However, with yield, once the first 5 items have been established the sorting stops and the results are available. This can save a large amount of time.
-1381407 0The sort of background processing you're looking to do is not possible with push notification.
Push notification allows you to notify the user of something. An example would be a Twitter client that sends a notification when the user receives a direct message on Twitter.
Push notification can not react to things happening on the iPhone when the app is not running. Instead, it depends on you having a server that determines when to send a notification and then sends one.
I'm not seeing any need for background processing in your application. If you store the user's initial location, the next time the app loads you can get their location and calculate the distance between the two. If you're looking for the route travelled, you're out of luck unless you make a deal with AT&T like Loopt just did.
-39227367 0 Zombie getting error Unhandled rejection Error: Timeout: did not get to load all resources on this pageI am new to zombie JS. I want to fill the login fields and post the login form. I tried to code this in zombiejs, but getting below error.
Unhandled rejection Error: Timeout: did not get to load all resources on this page at timeout (C:\Users\sapna.maid\Desktop\nodejs\index\node_modules\zombie\lib \eventloop.js:601:38) at Timer.listOnTimeout (timers.js:92:15)
My code snippet is as below:
var zombie = require("zombie"); zombie.waitDuration = '30s'; //Browser.waitDuration = '300s'; var assert = require("assert"); browser = new zombie({ maxWait: 10000, waitDuration: 30*1000, silent: true }); browser.visit("https://example.com", function () { // fill search query field with value "zombie" console.log("LOADEDDDD !!!!", browser.location.href); console.log(this.browser.text('title')); assert.equal(this.browser.text('title'), 'Welcome - Sign In'); browser.fill('#user', 'user@example.com'); browser.fill('#pass', 'pass@123'); browser.document.forms[0].submit(); console.log(browser.text('title')); // wait for new page to be loaded then fire callback function browser.wait(5000).then(function() { // just dump some debug data to see if we're on the right page console.log(this.browser.success); assert.ok(this.browser.success); console.log("Browser title:: --------- " + this.browser.text('title')); assert.equal(this.browser.text('title'), 'Dashboard'); }) }); Please help me to resolve this issue. I am stuck here for long duration. Thanks in advance!
-34774819 0 0x3 error using pdbstr (Source indexing)I am trying to use the PDBSTR.EXE tool to merge version information into a PDB file and from time to time I encounter the following error: [result: error 0x3 opening K:\dev\main\bin\mypdbfile.pdb] <- can be a different PDB file.
An example of the command line that I use is:
pdbstr.exe -w -s:srcsrv -p:K:\dev\main\bin\mypdbfile.pdb -i:C:\Users\username\AppData\Local\Temp\tmp517B.stream Could you tell me what would cause error code 0x3?
If the error code is similar to the standard System error code 3 ERROR_PATH_NOT_FOUND, then it seems to think that the path K:\dev\main\bin\mypdbfile.pdb does NOT exist when in fact it DOES. However please note that my K: drive is a SUBST'ed drive.
(System error code reference https://msdn.microsoft.com/en-ca/library/windows/desktop/ms681382(v=vs.85).aspx)
Do you know what the 0x3 error code could possibly mean?
-34284692 0 jquery validate date in range or empty, it is not allowed to submit empty dateI used the jquery validation to check a range of date or allow an empty date with under jquery mask. It is passed on editing, but the empty date field still prompt "Require" on form submit, what can I do?
$.validator.addMethod("daterange", function(value, element) { var ymd = value.split("/"); var d = new Date(ymd[0], ymd[1]-1,ymd[2]); var startDate = Date.parse('2015/01/01'), endDate = Date.parse('2100/12/31'), enteredDate = Date.parse(value); if(value=="____/__/__") return true; else if (isNaN(enteredDate)) return false; else if (d.getFullYear() == ymd[0] && d.getMonth() == ymd[1]-1 && d.getDate() == ymd[2]) return ((startDate <= enteredDate) && (enteredDate <= endDate)); else return false; },"Invalid Date" ); d1_eff_date : { required: false, daterange:true},
-9934852 0 Do you mean a short url something like this: http://snd.sc/abc123? If so, could you include the request which gives you that short_url? Otherwise if it's a 'normal' url like http://soundcloud.com/username/track, you can use the resolve endpoint to get the track (or user, or set, etc) data.
I'd like to load a carousel from a xml file and put it in the middle of a window and below the carousel I have a view that contains the description of each image.
kind when I scroll the images I have every description of this picture that I'm also recovering from an xml file
Can you tell me how I could do?
Thank you
-27383491 0I think your permission should be filtered by the role. Something like this :
var rolePermissions = new HashSet<int>(tDbContext.RoleDetail.Where(rd => rd.RoleId == role.RoleID).Select(rd => rd.PermissionId)); Your passing the role to your function but don't even use it : PopulateAssignedPermissionData(Role role). If i understand properly the code, now the allPermission and the rolePermissions are the same.
THANK YOU SO MUCH FOR INSPIRING ME mark_matters, though it's not just UPDATE fab SET no_sj='SJ000001' WHERE no_fab='FA000005' but i modified it because i actually using vs.net to update the data so i made this simple sub to be called on the button that worked as update button:
Sub update_no_sj_on_fab() Dim xupdate As String Dim x As Integer Dim xmycmd As OdbcCommand xubah = "UPDATE fab SET fab.no_sj=? WHERE no_fab='" & txtno_fab.Text & "'" xmycmd = New OdbcCommand(xupdate, Mycn) xmycmd.Parameters.AddWithValue("no_sj", txtno_sj.Text) xmycmd.Prepare() x = xmycmd.ExecuteNonQuery xmycmd.Dispose() Return End Sub
-39915143 0 Ionic\Cordova : Displaying icons of installed applications (ANDROID) I am trying to develop a Launcher like application using Ionic + Cordova. I have used the AppList plugin and it works well. However I can't get the icon paths it returns to display in my html templates, they just appear as empty <img/>. Is it even possible to display icons from /data/data/my_app in my templates ? If not, is there another way \ plugin to achieve my goal ?
I have a view where i used bootstrap tabpanels. On the first tab(active one), i have the home message. On the second one i have a form with 3 input fields and a submit button. In the model function where i validate the data for those fields, I output form validation errors or success message, and after I reload the view.
$data['table'] = $this -> model_admin -> get_users(); $data['title'] = 'Administrator'; $this -> load -> view('admin_view', $data); What i want to do is to manage, after i click submit button to reload the view, but with the second tab being active. Like I could load instead of ..../admin_view.php, ..../admin_view.php#add.
-14037889 0Not via stdlib. You will have to use some third-party library like ncurses.
-38745120 0you created new object and its property UserTerms is null
-10073081 0JavaScript variables are scoped by function declarations, not by blocks. Thus, you are using two different variables.
-16960390 0class A_Class { Ref<string> link; void A_Class( Ref<string> link) { this.link= link; } void somefunction( string str ) { if(link.Value.Length > 2) link.Value = str; } } public class Ref<T> { private Func<T> getter; private Action<T> setter; public Ref(Func<T> getter, Action<T> setter) { this.getter = getter; this.setter = setter; } public T Value { get { return getter(); } set { setter(value); } } }
-33041779 0 Show page from another URL For, example, if I have this working link:
/test1/index.php?prop1=val1 And I have this HTML tag:
<a href="/test2-val2/">link</a> How can I use this tag for opening the first link with the following content:
/new_link-test1/index.php?prop2=val2 My guess was to use .htaccess:
RewriteRule ^new_link-(.*)/$ /test1/index.php?$1 [L] It works fine until I have the following next URL:
/new_link-(.*)/?other_params=other_values with additional unusable parameters which show after page manipulations.
And when this URL opens, it doesn't show me the content on working link.
How can I change .htaccess to fix this?
There's no "property by index" feature, but one approach that would make consumption easier would be to build an indexer on the class and encapsulate the switch statement there. Maybe something like this:
public class Plan { public int this[int index] { get { switch (index) { case 1: return this.a; ... } } set { switch (index) { case 1: this.a = value; ... } } } } So, now using it looks like this:
planObject[i] = 100; Now, in your case it looks like you have an additional need because you have a key (the index) and a value (e.g. 100), so you need to store your keys and values in a Dictionary. So, in your class that uses Plan create a private field:
private Dictionary<int, int> _values = new Dictionary<int, int> { { 1, 100 }, { 2, 200 }, ... } To use the dictionary you'd do something like this:
planObject[i] = _values[i]; UPDATE: if you can't change the class Plan then you'll need to do something like this. First you need a map from index to property name:
private Dictionary<int, string> _properties = new Dictionary<int, string> { { 1, "a" }, { 2, "b" }, ... } and next you'll need to set that property:
var t = planObject.GetType(); var p = t.GetProperty(_properties[i]); if (p != null) { p.SetValue(planObject, 100); }
-31628880 0 You are right that generator expressions would have been the right choice - especially in multi-configuration environments - but if a certain command or property does not support them, you can't trick them into working.
But there are alternatives:
Setting ARCHIVE_OUTPUT_DIRECTORY Property
You could slightly change your "I guess I am meant to" strategy and place your library outputs you want to merge into a path of your own choosing. The following example is for a multi-configuration environment like Visual Studio:
add_library(lib1 STATIC bar.cc) set_target_properties(lib1 PROPERTIES ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/Libs") file(WRITE dummy.cc "") add_library(merged STATIC dummy.cc) add_dependencies(merged lib1) set_target_properties( merged PROPERTIES STATIC_LIBRARY_FLAGS_DEBUG "${CMAKE_BINARY_DIR}/Libs/Debug/lib1.lib" STATIC_LIBRARY_FLAGS_RELEASE "${CMAKE_BINARY_DIR}/Libs/Release/lib1.lib" ) Using OBJECT Libraries
Or you can work with OBJECT libraries as intermediate grouping targets to prevent having to trick CMake into building your merged library:
add_library(lib1 OBJECT bar.cc) add_library(lib2 OBJECT foo.cc) add_library(merged $<TARGET_OBJECTS:lib1> $<TARGET_OBJECTS:lib2>) I personally prefer the later.
-37448066 01) I recommend that you check to see if this file is being written to already before you attempt to write to it.
void SaveTimer() { try { using (Stream stream = new FileStream(filename, FileMode.Open)) { yourTimer.Stop(); Save(); yourTimer.Start(); } } catch { Thread.Sleep(3000); } } } Try using ICollectionViews in combination with IsSynchronizedWithCurrentItem property when handling lists / ObservableCollection in Xaml. The ICollectionView in the viewmodel can handle all the things needed, e.g. sorting, filtering, keeping track of selections and states.
Xaml:
<Window x:Class="ComboBoxBinding.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <ListBox Grid.Column="0" ItemsSource="{Binding Reports}" DisplayMemberPath="Name" IsSynchronizedWithCurrentItem="True" /> <ComboBox Grid.Column="1" ItemsSource="{Binding CurrentReport.Performances}" DisplayMemberPath="Name" IsSynchronizedWithCurrentItem="True" /> </Grid> </Window> ViewModel:
public class ViewModel : INotifyPropertyChanged { private readonly IReportService _reportService; private ObservableCollection<ReportViewModel> _reports = new ObservableCollection<ReportViewModel>(); private PerformanceViewModel _currentPerformance; private ReportViewModel _currentReport; public ObservableCollection<ReportViewModel> Reports { get { return _reports; } set { _reports = value; OnPropertyChanged("Reports");} } public ReportViewModel CurrentReport { get { return _currentReport; } set { _currentReport = value; OnPropertyChanged("CurrentReport");} } public PerformanceViewModel CurrentPerformance { get { return _currentPerformance; } set { _currentPerformance = value; OnPropertyChanged("CurrentPerformance");} } public ICollectionView ReportsView { get; private set; } public ICollectionView PerformancesView { get; private set; } public ViewModel(IReportService reportService) { if (reportService == null) throw new ArgumentNullException("reportService"); _reportService = reportService; var reports = _reportService.GetData(); Reports = new ObservableCollection<ReportViewModel>(reports); ReportsView = CollectionViewSource.GetDefaultView(Reports); ReportsView.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending)); ReportsView.CurrentChanged += OnReportsChanged; ReportsView.MoveCurrentToFirst(); } private void OnReportsChanged(object sender, EventArgs e) { var selectedReport = ReportsView.CurrentItem as ReportViewModel; if (selectedReport == null) return; CurrentReport = selectedReport; if(PerformancesView != null) { PerformancesView.CurrentChanged -= OnPerformancesChanged; } PerformancesView = CollectionViewSource.GetDefaultView(CurrentReport.Performances); PerformancesView.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending)); PerformancesView.CurrentChanged += OnPerformancesChanged; PerformancesView.MoveCurrentToFirst(); } private void OnPerformancesChanged(object sender, EventArgs e) { var selectedperformance = PerformancesView.CurrentItem as PerformanceViewModel; if (selectedperformance == null) return; CurrentPerformance = selectedperformance; } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } }
-16231375 0 WPF get parent of menuItem I don't know how to get the parent of a menuItem? I searched all arround but can't get a good answer...
My XAML is:
<DockPanel> <Menu DockPanel.Dock="Right" SnapsToDevicePixels="True" Margin="2,0,0,0"> <MenuItem Header="Devices"> <local:MenuItemWithRadioButton x:Name="MenuItemVideoDevices" Header="Video"> </local:MenuItemWithRadioButton> <local:MenuItemWithRadioButton x:Name="MenuItemAudioDevices" Header="Audio"> </local:MenuItemWithRadioButton> </MenuItem> </Menu> </DockPanel> private void MenuItemWithRadioButtons_Click(object sender, System.Windows.RoutedEventArgs e) { MenuItem mi = sender as MenuItem; if (mi != null) { RadioButton rb = mi.Icon as RadioButton; if (rb != null) { rb.IsChecked = true; } //Here I want to get the parent menuItem } } In the code, when I click the submenuItem like "MenuItemVideoDevices", an event process function is triggered, but I don't know how to get the menuItem "Video" in this function.
Anyone knows?
-12977334 0 Multithreading and passing data to new threadsI have some issues with an application I'm coding. It's job is to solve a maze using threads. One thread begins, and for each bifurcation it calls a static method in another class, passing parameters that the other thread needs, and then starts threads for each path. My outputs are all messed up, and I'm not sure if it's a Multithreading problem or maybe a problem with the references. Here's some of the code (Each thread is given a new instance of an Explorer class):
This is the Run() method for each thread:
public void Explore() { while (ImDone == false) { Move(); if (ActualPosition[0] != Labyrinth.ExitPoint[0] || ActualPosition[1] != Labyrinth.ExitPoint[1]) //I'm not at the end.. continue; PrintMyStatus(); //Print in the console my parents and my complete route.. break; } This is the Move() method:
List<int[]> validPaths = CheckSurroundings(); //returns a list of paths switch (validPaths.Count) { case 0: ImDone = true; //No more routes available break; case 1: MarkMyPosition(validPaths); //Change internal variables to the only new path break; default: lock(this) //As this involves thread creating I locked it.. { //Creating deep copies of my "History" so my childs can have them.. List<int[]> DCValidPaths = DeepCopy(validPaths); List<string> DCMyParents = DeepCopy(MyParents); string[,] DCMyExplorationMap = DeepCopy(MyExplorationMap); List<int[]> DCMyPositions = DeepCopy(MyPositions); foreach (var path in validPaths) { DCMyParents.Add(Thread.CurrentThread.Name); //Adding myself as a parent ExplorationManager.ExplorerMaker( DCValidPaths, DCMyParents, DCMyExplorationMap, DCMyPositions, ID); //Threads are created in the static class } } break; } My DeepCopy() method is using is the one in the accepted answer of this question. Any other info needed I'll be more than happy to provide in order to solve the problem. Thanks in advance for your help.
EDITS: My problem consists basically in: I'm having an OutOfMemoryException in the Thread.Start() clause and the Path displayed by the threads contain corrupted data (incorrect positions). I tested the CheckSurroundings() method and by far only returns correct positions (The labyrinth is contained in a two-dimensional string array).
This is the constructor of the Explorer class:
public Explorer(List<string> myParents, int[] actualPosition, string[,] myExplorationMap, List<int[]> myPositions, int ID) { //Here I pass the data specified in Move(); MyParents = myParents; ActualPosition = actualPosition; MyExplorationMap = myExplorationMap; MyPositions = myPositions; this.ID = ID + 1; //An ID for reference //Marking position in my map with "1" so I know I've been here already, //and adding the position given to my list of positions MyExplorationMap[ActualPosition[0], ActualPosition[1]] = "1"; MyPositions.Add(DeepCopy(ActualPosition)); } And this is the class creating the threads:
public static class ExplorationManager { public static void ExplorerMaker(List<int[]> validPaths, List<string> myParents, string[,] myExplorationMap, List<int[]> myPositions, int ID) { foreach (var thread in validPaths.Select (path => new Explorer(myParents, path, myExplorationMap, myPositions,ID)). Select(explorer => new Thread(explorer.Explore))) { thread.Name = "Thread of " + ID + " generation"; thread.Start(); //For each Path in Valid paths, create a new instance of Explorer and assign a thread to it. } } } And the method returning the ValidPaths
private List<int[]> CheckSurroundings() { var validPaths = new List<int[]>(); var posX = ActualPosition[0]; var posY = ActualPosition[1]; for (var dx = -1; dx <= 1; dx++) { if (dx == 0 || (posX + dx) < 0 || (posX + dx) >= Labyrinth.Size || MyExplorationMap[posX + dx, posY] == "1") continue; var tempPos = new int[2]; tempPos[0] = posX + dx; tempPos[1] = posY; validPaths.Add(tempPos); } for (var dy = -1; dy <= 1; dy++) { if (dy == 0 || (posY + dy) < 0 || (posY + dy) >= Labyrinth.Size || MyExplorationMap[posX, posY + dy] == "1") continue; var tempPos = new int[2]; tempPos[0] = posX; tempPos[1] = posY + dy; validPaths.Add(tempPos); } //This method checks up, down, left, right and returns the posible routes as `int[]` for each one return validPaths; } CheckSurroundings uses the deep copy passed to the child (via the constructor) to validate the routes he can take. It is NOT intended to alterate the parent's copy, because he is now in ANOTHER path of the labyrinth. The child only needs the information updated (passed via the constructor) UNTIL the point they "separate". And also EACH child must be independent from the other childs. That's what I'm trying to do. But I'm not sure what's wrong, maybe concurrency problem? Please help. If you need anything else let me know. –
-27406825 0It's not necessary or even mandatory. But is it smart? Yes it is. Android Studio with Gradle and Maven are soooo powerful, that you are losing so much time using Eclipse.
Of course, you will have to pass all these painful steps, like we all did. What is Gradle? What is Maven? How do I import library? Where is my code? Why my Manifest does not work? And so on...
so I strongly advise you find a week of your time and learn new IDE by fixing all those things that will arise when you do conversion.
But in the end, you can still use Eclipse or IntelliJ IDEA the old way and leave learning to some other time.
-19290703 0Can't you just call finish() right after your starActivity call? (you'd have to remove the SINGLE_TOP flag too -- or you'll run into the behaviour you mentioned when going from B -> B)
-25276718 0 How do i create a dbo schema in the h2 sqlserver emulator?I'm getting a
JdbcSQLException: Schema "dbo" not found; SQL statement: create table "dbo"."TableName" when running some boilerplate sql against the h2 sqlserver emulator (ie, with config settings:
db.default.slickdriver=com.typesafe.slick.driver.ms.SQLServerDriver db.default.driver=net.sourceforge.jtds.jdbc.Driver db.default.url="jdbc:h2:file:~/data/test1;MODE=MSSQLServer" running the following:
Database.forDataSource(DB.getDataSource()) withSession { I've tried creating the schema:
Database.forDataSource(DB.getDataSource()) withSession { implicit session => Q.updateNA("CREATE SCHEMA \"dbo\" AUTHORIZATION sa;") } but that doesn't seem to do the trick (or report an error message). Am I missing something?
still unable to create the schema programatically. was able to easily create it via the h2 console, using the exact same query as above.
play.api.UnexpectedException: Unexpected exception[JdbcSQLException: Schema "dbo" not found; SQL statement: create table "dbo"."TestTable" ("TestTableId" CHAR(36)) at play.core.ReloadableApplication$$anonfun$get$1$$anonfun$apply$1$$anonfun$1.apply(ApplicationProvider.scala:148) ~[play_2.10-2.2.3.jar:2.2.3] at play.core.ReloadableApplication$$anonfun$get$1$$anonfun$apply$1$$anonfun$1.apply(ApplicationProvider.scala:112) ~[play_2.10-2.2.3.jar:2.2.3] at scala.Option.map(Option.scala:145) ~[scala-library-2.10.4.jar:na] at play.core.ReloadableApplication$$anonfun$get$1$$anonfun$apply$1.apply(ApplicationProvider.scala:112) ~[play_2.10-2.2.3.jar:2.2.3] at play.core.ReloadableApplication$$anonfun$get$1$$anonfun$apply$1.apply(ApplicationProvider.scala:110) ~[play_2.10-2.2.3.jar:2.2.3] at scala.util.Success.flatMap(Try.scala:200) ~[scala-library-2.10.4.jar:na] Caused by: org.h2.jdbc.JdbcSQLException: Schema "dbo" not found; SQL statement: create table "dbo"."TestTable" ("TestTableId" CHAR(36)) at org.h2.message.DbException.getJdbcSQLException(DbException.java:329) ~[h2-1.3.172.jar:1.3.172] at org.h2.message.DbException.get(DbException.java:169) ~[h2-1.3.172.jar:1.3.172] at org.h2.message.DbException.get(DbException.java:146) ~[h2-1.3.172.jar:1.3.172] at org.h2.command.Parser.getSchema(Parser.java:613) ~[h2-1.3.172.jar:1.3.172] at org.h2.command.Parser.getSchema(Parser.java:620) ~[h2-1.3.172.jar:1.3.172] at org.h2.command.Parser.parseCreateTable(Parser.java:5254) ~[h2-1.3.172.jar:1.3.172]
-20955067 0 This line is throwing the "Ambiguous match found" exception:
var trimMethod = typeof(string).GetMethod("Trim"); Change it to:
var trimMethod = typeof(string).GetMethod("Trim", new Type[0]);
-35525496 0 How does one add a partial index checking for NULL to a JSON column on Postgres? I've got a json column called data on Postgres, and I'd like to add a partial index that applies only to rows where this column is null - I basically need to find all the rows where data is null so I can put some data into them.
Trying to add an index gives an error about missing operator classes, though, because we can't index json types with a btree index. But I'm not trying to index a specific property either, for me to use data->>property. How can I index just the rows which have a json null in them?
Edit: The jsonb suggestion would work, but I'm stuck on 9.3 for this project.
I am using custom shortcodes for my post editor and i now have multiple shortcodes i would like to make a shortode be stylized differently if another shortcode is enabled. Is there a filter or conditional function like is_shortcode('slideshow') if not has anyone written a workaround for this?
-29062441 0Do you need to use JQuery? Why not use CSS?
<span style="color:green;">//I need to color this line</span>
-39905583 0 Mapquest routes using custom icons I'm using Mapquest's Javascript API for leaflet.
My code looks like this:
dir = MQ.routing.directions() .on('success', function (data) { console.log(data); var legs = data.route.legs; var maneuvers; if (legs && legs.length) { maneuvers = $.map(legs[0].maneuvers, function(m) { return new Maneuvers(m); }); self.maneuvers(maneuvers); } }); dir.route({ locations: [ self.from(), self.to() ] }); map.addLayer(MQ.routing.routeLayer({ directions: dir, fitBounds: true })); The results I get looks like this:
Although, this looks good, the icons don't look anything like the Get Direction module on mapquest.com 
How can I change the icons so that they look more modern?
-11532902 0Growing buttons in Excel is a fairly common issue, with several theories about why this happens, including the use of multiple monitors or using proportional fonts. I have yet to see a definitive answer about this, but there are several workarounds that may work for you.
My personal choice is #4. As an alternative to buttons, I either use hyperlinks or shapes with macros assigned to them.
-30364861 0Finaly, I have found out what was the problem. composer.json file in the project I was trying to load - UPS library -was invalid. I was able to download files when I ran:
composer.phar install but it looks like composer.json file was ignored. I found it out when I ran
composer.phar update and got
No valid composer.json was found With option -v I got error that "name" is undefined index. So, I simply added "name" field to the composer.json. Final version is:
{ "name":"KoulSlou/UPS", "autoload": { "files": [ "libraries/Ups/Ups.php", "libraries/Ups/Ups_Base.php", "libraries/Ups/Ups_Base_Response.php", "libraries/Ups/Ups_Live_Rates.php" ] } }
-13452637 0 Unable to Launch Chrome Browser in Selenium I am launching chrome browser using
selenium = new DefaultSelenium("localhost", 4444, "*googlechrome", "https://example.com/"); But i get a popup with following message and it freezes:
An administrator has installed Google Chrome on this system, and it is available for all users. The system-level Google Chrome will replace your user-level installation now.
Console Log till point of freeze:
Server started 16:06:37.792 INFO - Command request: getNewBrowserSession[*googlechrome, https://example.com/, ] on session null 16:06:37.796 INFO - creating new remote session 16:06:38.081 INFO - Allocated session beb925cd0418412dbe6319fedfb28614 for https://example.com/, launching... 16:06:38.082 INFO - Launching Google Chrome... Any suggestions?
-17422450 0The bracket notation returns DOM elements, which do not have a slideToggle method. What you want is .eq, which filters in the same manner but returns jQuery objects instead:
Div.eq(0).slideToggle(...) ;
-5190449 0 How to get Exact day difference between two dates in java or groovy? I am calculating the difference between two sql dates, TripStartDate and TripEndDate.
If TripStartDate= 2011-03-04 09:35:00 and TripEndDate = 2011-03-04 10:35:00 then I should get the number of day is 1 (because trip happened on that day).
Like this:
If TripStartDate = 2011-03-04 09:35:00 and TripEndDate = 2011-03-05 09:35:00 then method should return 2 days (because trip happened on both days).
If TripStartDate = 2011-03-04 09:35:00 and TripEndDate = 2011-04-04 09:35:00 then method should return 32 days. (because 28 days in march and 4 days in April).
Calculation should be based on only dates and month of year (not taking time in consideration). Please help me . Thanks in advance...
-14014283 0 curl: google spreadsheet as .csvI want to download one of my google spreadsheet using curl and save it as a .csv file. Following is the command I am using:
(curl --silent --header "Authorization: GoogleLogin auth=AUTH_KEY" https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=SPREADSHEET_KEY&exportFormat=csv) > a.csv
This is downloading a file which is in pdf format. Can anybody help me in resolving this issue I am stuck with for 1 hr...
-2282867 0Because when you call document.write the first time, it removes all links from the DOM. It replaces the entire innerHTML of document.body with "Hello: ".
You should never use document.write anyway.
I see a few pitfalls in your code, there are a few places where things can go wrong:
First, use of regular statements. Use prepared statements so you won't have problems with SQL injection.
Instead of
statement = connection.createStatement(); use
statement = connection.prepareStatement(String sql); With this, your query becomes
"select distinct group_name From group_members where username= ?" and you set username with
statement.setString(1, username); Next, I don't like use of your myDB class. What if results is null? You're not doing any error checking for that in your public List<InterestGroup> getGroups() method.
public void sendQuery(String query) seems to me like it shouldn't be void, but it should return a ResultSet. Also, search on the net for proper ways to do JDBC exception handling.
Also, this line:
new InterestGroup(results.getString("group_name"), myDB) Why do you have myDB as a parameter?
I'd suggest adding more System.out.println statements in your code so you can see where things can go wrong.
when I try to add a decimal value to a column in voltdb, it always adds extra zeroes to the decimal. The column type is DECIMAL, which equates to Java's BigDecimal type. Even if I format the BigDecimal value in java to a two decimal place BigDecimal before doing the insert, it still shows up with lots of trailing zeroes in the column.
Any idea how to fix this?
Thanks
-5087386 0You should be able to handle that by conditionally adding a #redirect attribute to the form.
-30701507 0 simplify if statement with stored procedurei have a following stored procedure where i am repeating similar code. all i am doing is checking the condition based on Sample id1, sampleid2, and sample id3 to follow in similar fashion. The value of 'y' goes on till about it reaches 10, so it's going to be a big 'if' condition based statements. i was trying to see if a better solution could be put in place. thanks.
@select = 'select * from tbl Sample......' if(x = 1 and y=1) set @where = 'where Sample.id1 >=1 and <=10' if(x = 1 and y=2) set @where = 'where Sample.id1 >=11 and <=20' if(x=2 and y=1) set @where = 'where Sample.id2 >=1 and <= 10' if(x=2 and y=2) set @where = 'where Sample.id2 >=11 and <=20' if(x=3 and y=1) set @where = 'where Sample.id3 >=1 and <=10' if(x=3 and y=2) set @where = 'where Sample.id3 >=11 and <=20' //increment goes on exec(@select+@where)
-2996094 0 # mysql < create_mysql.sql
-22433227 0 Aligning grid lines to axis ticks in lattice graphicsIs there a way to align grid lines if they are chosen custom? By default, panel.grid(h=-1,v=-1) does the job, but I'd like to refine the grid according to the axis ticks. Setting h and v to negative lengths of axis ticks doesn't always work.
Update: Below is an example. I would like to achieve that horizontal grid lines match the y-axis ticks. Currently half of horizontal grid lines are missing.
library(lattice) G <- cut(trees$Girth, seq(8, 22, by = 3)) p <- xyplot(Height ~ Volume | G, data = trees, scales = list(x = list(alternating = 3, at = seq(10, 60, by = 5)), y = list(alternating = 3, at = seq(65, 85, by = 2.5))), panel = function(x, y, ...){ panel.grid(v = -11, h = -9) panel.xyplot(x, y, ...)}) print(p) What I currently get is this:

Links can't technically submit forms. That means you're limited to javascript, check out link_to_function. You'll need the id of the form you want to submit and then you can write some javascript like:
$('the_forms_id').submit(); return false;
-32344156 0 how to make makefiles in unix with vi editor assignment1: treecomp.h treefunction.c assignment1.c gcc -Wall -ansi -o assignment1.c treecomp.h treefunction.c I typed in just the two lines above in unix vi editor.
Is this correct to make makefiles?
When I type in make in the command line, it doesn't make one.
Can anyone tell me how to make makfile?
I've been watching one of the youtube videos that shows you how to make makefilles and followed that but doesn't work.
-33244312 0 Iterating SQL statement By For Loop (MS Access)In my test database, I am attempting to do an iterative UPDATE statement based on multiple criteria.
In my table I am trying to update, tblSales_Language, I have the columns
Sales _LanguageID , Language_ID, Sales_CountryID, SalesID, & CountryID
As a reference table, I am using tblSales_Country, which has Sales_CountryID, CountryID, SalesID.
My goal is to UPDATE the columns in tblSales_Language, which have information but all columns except for Sales_CountryID- this information I am attempting to draw from the reference table tblSales_Country
Without further ado, my current code is as follows:
Dim i as integer Dim SQL As String For i = 1 to 5 SQL = "UPDATE tblSales_Language &_ SET tblSalesLanguage.SalesCountryID = " & DLOOKUP("Sales_CountryID", "tblSales_Country", "[SalesID]" = i)" Exit For My code does not register as syntactically correct, does it have to do with the fact that I do not have a WHERE in my statement?
Thanks.
-1301365 0 PHP/Amazon S3: Query string authenticationI have been using the Zend_Service_Amazon_S3 library to access Amazon S3, but have been unable to find anything that correctly deals with generating the secure access URLs.
My issue is that I have multiple objects stored in my bucket with an ACL permission of access to owner only. I need to be able to create URLs that allow timed access. However, the documentation for Amazon S3 is very brief on the subject.
Could someone elaborate, or provide a link to something that explains how I might achieve this in PHP?
-11269893 0Unfortunately no one has made a plugin for it yet. It's possible, it would just involve you figuring out how to do it. Might be worth a try. I'm sure a lot of people would use it/find it helpful since there is no plugin that does the job at the moment.
-26009744 0 Matlab Substring as function call?I am trying to figure out this substring feature and whether there exists a function call for it or not. As far as I can find, here and here along with various other places, there simply is no related function for this since strings are char arrays, and so they settled for only implementing the indexing feature.
MWE:
fileID = fopen('tryMe.env'); outDate = fgetl(fileID); Where the file 'tryMe.env' only consists of 1 line like so:
2014/9/4 My wanted result is:
outDate = '14/9/4' I am trying to find a clean, smooth one liner to go with the variable definition of outDate, something along the lines of outDate = fgetl(fileID)(3:end);, and not several lines of code.
Thank you for your time!
-22271821 0If Scala / Java interoperability is not too much of an issue for you, and if you're willing to use an internal DSL with a couple of syntax quirks compared to the syntax you have suggested, then jOOQ is growing to be a popular alternative to Slick. An example from the jOOQ manual:
for (r <- e select ( T_BOOK.ID * T_BOOK.AUTHOR_ID, T_BOOK.ID + T_BOOK.AUTHOR_ID * 3 + 4, T_BOOK.TITLE || " abc" || " xy" ) from T_BOOK leftOuterJoin ( select (x.ID, x.YEAR_OF_BIRTH) from x limit 1 asTable x.getName() ) on T_BOOK.AUTHOR_ID === x.ID where (T_BOOK.ID <> 2) or (T_BOOK.TITLE in ("O Alquimista", "Brida")) fetch ) { println(r) }
-28291534 0 if(!empty($_SESSION['c_id']) || !empty($_SESSION['c_id'])) { //Login here } else { //Please Login }
-36824585 0 Does RTCPeerConnection work in Microsoft Edge? I am currently working on VoIP using WebRTC. It's going to be a UWP application written in JavaScript.
Now, I am trying to check whether it works or not by testing samples from https://webrtc.github.io/samples on Microsoft Edge.
It turns out that it works fine except RTCPeerConnection.
For example, when I opened https://webrtc.github.io/samples/src/content/peerconnection/audio in Edge, it gave me getUserMedia() error: NotFoundError when I clicked the call button. On Chrome, it works fine.
Another example is when I tried https://apprtc.appspot.com, it gave me
Messages: Error getting user media: null getUserMedia error: Failed to get access to local media. Error name was NotFoundError. Continuing without sending a stream. Create PeerConnection exception: InvalidAccessError Version: gitHash: c135495bc71e5da61344f098a8209a255f64985f branch: master time: Fri Apr 8 13:33:05 2016 +0200 So, how should I fix that? Adapter.js is also called. I also allow everything it needs.
Or I shouldn't use WebRTC for this project. If so, what should I use?
Cheers!
-17368457 0if you want them as you've described them, just tack on some zero's to the front, it won't change the binary value
private static string AddZeros(string r) { while (r.Length < 8) r = "0" + r; return r; }
-20443262 0 "A reference may be bound only to an object", why is "const int &ref = 3;" valid? I am just starting learning c++. I found an advice on Internet: "Learn with a good book, it is better than videos on youtube." So as I am motivated and I have time I learn with c++ Primer 5th Ed.
In this book, they say: Note: "A reference is not an object. Instead, a reference is just another name for an already existing object."
and: "a reference may be bound only to an object, not to a literal or to the result of a more general expression"
I understand:
int i = 3; int &ri = i; // is valid: ri is a new name for i int &ri2 = 2; // is not valid: 2 is not an object Then I don't understand why:
const int &ri3 = 2; // is valid They write: "It can be easier to understand complicated pointer or reference declarations if you read them from right to left."
Ok, it is not very complicated. I understand: I declare a variable named ri3, it is a reference (a reference when & is after the type, an address when & is in an expression) to an object of type int and it is a constant.
I think it has already been explained many times but when I search on forums I find complicated (to me) answers to complicated problems, and I still don't understand.
Thank you for your help.
-12250455 0Give each route a name when you are defining it. Then inject $route into the controller, then have the controller publish it into the current scope. You can then bind the ng-switch to $route.current.name
-26867796 0 Generic mobile tests with appiumI'm new to mobile testing , and currently I research for an automation framework for mobile testing. I've started to look into Appium, and created some tests for the demo app I've made (one for IOS and the other for Android). I've managed to write a test for each of the platforms , but I was wondering , how difficult it might be to write a one generic test which will be executed on the both platforms with minimum adjustments ?
Thanks
-36256635 0 mongoose right usage of multiple databases?I have multiple mongodb connections in my project:
// db.coffee conn1 = mongoose.createConnection "mongodb://192.168.1.193/test" conn2 = mongoose.createConnection "mongodb://92.168.1.81/position" I have a model named PositionNoCity which belongs to conn2 and a model named A which belongs to conn1:
// a.coffee ASchema = new Schema { a: Number }, {collection: 'test'} mongoose.model 'A', ASchema // pos.coffee PositionNoCitySchema = new Schema { position_id: String, job_forward_stats: [{forward_position_num: Number, forward_position: String, forward_position_ratio: Number}], }, {collection: 'position_indicators_no_city'} mongoose.model 'PositionNoCity', PositionNoCitySchema Now I want to use these models:
require './db' require './pos' require './a' mongoose = require 'mongoose' // I have to point out which connection to use here, but with index the code is very very bad A = mongoose.connections[1].model('A') PositionNoCity = mongoose.connections[2].model('PositionNoCity') PositionNoCity.findOne({position_id: "aaa"}).then(console.log).catch(console.log) A.findOne({'a': 1}).then(console.log).catch(console.log) I have two questions:
mongoose.connections[2].model with mongoose.model, I run failed. Anyway, mongoose.connections[2].model must be replaced somehow, so how to replace?In the html code, replace:
<a href="whatsapp://send?text=Hello"> with:
<a href="intent://send?text=Hello#Intent;scheme=whatsapp;package=com.whatsapp;end"> See Chrome's docs about this here: https://developer.chrome.com/multidevice/android/intents#example
-15923075 0 The best way to use VBOsWhat are the fastest and the most flexible (applicable in most situations) ways to use VBOs?
I am developing an openGL application and i want it to get to the best performance, so i need someone to answer these questions. I read many questions and anwers but i guess there's to much information that i don't need which messes up my brain...
The problems are caused by this:
{ (char) c = (int) c - 32 + key + 127; System.out.println(c); } The (char) c = ...; is completely invalid syntax.
An assignment is supposed to look like this c = ...;.
If you want / need to do a type cast before assigning, the type cast belongs on the right hand side of the assignment operator; i.e. c = (char)(...).
Anyway, what you have written has cause the Java parser (in your IDE) to get thoroughly confused ... and spectacularly misdiagnose the error as an attempt to declare a constructor, it the wrong context.
Unfortunately, this happens sometimes ... though it is compiler dependent. The compiler was trying to be helpful, but the compiler / compiler writer "guessed wrong" about what you were trying to write at that point.
Then it appears that the compiler's syntax recovery has inserted a { symbol into its symbol stream in an attempt to fix things. The second error complains that there is no } to match the phantom { that it inserted. Again, it has guessed wrong.
But the root cause of this was your original syntax error.
For the record, the int cast in your original expression is not necessary. You could (and IMO should) write the assignment as this:
c = (char) (c - 32 + key + 127); Explanation: in Java, the arithmetic operators always promote their operands to int (or long) before performing the operation, and the result is an int (or long). That means that your explicit cast of c to an int is going to happen anyway.
I've just put a rails 4 app into production, and I've noticed what look like a number of scripted attacks, mostly on urls that end with .php. They look like this:
I, [2015-05-11T22:03:01.715687 #18632] INFO -- : Started GET "/MyAdmin/scripts/setup.php" for 211.172.232.163 at 2015-05-11 22:03:01 +0100 F, [2015-05-11T22:03:01.719339 #18632] FATAL -- : ActionController::RoutingError (No route matches [GET] "/MyAdmin/scripts/setup.php"): actionpack (4.1.0) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call' I'd like to collect thee url from these RoutingError messages, mostly so I can set up routes for them, probably to simply render nothing.
I'd also like to redirect to a site which might keep script runners busy.
Anyway, here's the question. Is there any way I can intercept ActionController::RoutingError to run some code?
Bonus question: Does anyone know if there's actually a lot of php apps out there which can be broken into with urls like the one above?
-33097912 0 Select items from one ListBox into anotherI have a two ListBoxes listbox1 and listbox2. I want to get all the duplicate items in ListBox1 that i'd search in a TextBox and put in into ListBox2 and when all the duplicate item's that i'd search is in ListBox2 its automatically count please help me.
For example, items in ListBox1
DOG DOG DOG CAT CAT When I type DOG in TextBox all the DOG in ListBox1 will be copied to ListBox2. How can I do it?
I tried this
Dim check As Boolean For Each item In ListBox1.Items check = ListBox1.FindStringExact(item) ListBox2.Items.Add(item) Next i also try this but its wrong it count's the line before the exact word that i'd search. for example DOG DOG DOG CAT CAT i'd search CAT in textbox the output in listbox2 is 3 here's my code :
Dim check As String
check = ListBox1.FindStringExact(TextBox1.Text) ListBox2.Items.Add(check)
-5102533 0 You´ll want to use NSWindowLevel, in specific kCGDesktopWindowLevel. A short overview on NSWindowLevel can be found here, and a more elaborate solution has been posted to a similar stackoverflow question before.
-26662283 0In order to compute the rmse it is neccessary to have a maximum of 1 y value per x value, mathematically speaking a "function". You can plot later again the way your sketch shows it. But for the computation: rotate by 90 degree.
For the optimization, you need an initiall guess (your Alpha), which is not defined. However, with some minor changes in the code below, one can get the optimal parameters. Also it might be better readable. The plot is shown below.
plot(r, XMean ,'ko', 'markerfacecolor', 'black') % // need a "function" (max 1y value for 1x-value) Eqn = @(par, x) par(1).*( 1 - ( (par(2) - x) / par(3) ).^2 ); par0 = [1, 1, 1]; % // an initial guess as start for optimization par_fit = nlinfit(r, XMean, Eqn, par0 ); % // optimize hold on r_fit = linspace(min(r), max(r)); % // more points for smoother curve plot(r_fit, Eqn(par_fit, r_fit), 'r')
The optimal parameters i get returned are
par_fit = 0.1940 -0.4826 9.0916 You might want to rotate the plot again to get it into the right orientation, as in your sketch.
Since one can compute this flow profile analytically, one knows in advance that is is a parabola. You can also use polyfit to fit a parabola.
par_poly_fit = polyfit(r, XMean, 2) % // it yields the values: par_poly_fit = -0.0023 -0.0023 0.1934 Plotting that paraobla gives a line pretty much identical to the line, which we got with the optimizer, but it is just more stable since it does not depend on an initial value.
plot(r_fit, polyval(par_poly_fit, r_fit),'g--'
-1749604 0 Multi-dispatch is the ability to choose which version of a function to call based on the runtime type of the arguments passed to the function call.
Here's an example that won't work right in C++ (untested):
class A { }; class B : public A { }; class C : public A { } class Foo { virtual void MyFn(A* arg1, A* arg2) { printf("A,A\n"); } virtual void MyFn(B* arg1, B* arg2) { printf("B,B\n"); } virtual void MyFn(C* arg1, B* arg2) { printf("C,B\n"); } virtual void MyFn(B* arg1, C* arg2) { printf("B,C\n"); } virtual void MyFn(C* arg1, C* arg2) { printf("C,C\n"); } }; void CallMyFn(A* arg1, A* arg2) { // ideally, with multi-dispatch, at this point the correct MyFn() // would be called, based on the RUNTIME type of arg1 and arg2 pFoo->MyFn(arg1, arg2); } ... A* arg1 = new B(); A* arg2 = new C(); // Using multi-dispatch this would print "B,C"... but because C++ only // uses single-dispatch it will print out "A,A" CallMyFn(arg1, arg2);
-7592747 0 how to remove namespace and retain only some of the elements from the original XML document using XSL? Below is my XML. I wanted to parse this using XSL. What I want to achieve is to remove the namespace (xmlns) then just retain some of the elements and their attributes. I found a way to remove the namespace but when I put it together with the code to retain some of the elements, it doesn't work. I already tried the identity but still didn't work.
I hope someone out there could share something. Thank you very much in advance.
XML Input:
<Transaction xmlns="http://www.test.com/rdc.xsd"> <Transaction> <StoreName id="aa">STORE A</StoreName> <TransNo>TXN0001</TransNo> <RegisterNo>REG001</RegisterNo> <Items> <Item id="1"> <ItemID>A001</ItemID> <ItemDesc>Keychain</ItemDesc> </Item> <Item id="2"> <ItemID>A002</ItemID> <ItemDesc>Wallet</ItemDesc> </Item> </Items> <IDONTLIKETHIS_1> <STOREXXX>XXX-</STOREXXX> <TRANSXXX>YYY</TRANSXXX> </IDONTLIKETHIS_1> <IDONTLIKETHIS_2> <STOREXXX>XXX-</STOREXXX> <TRANSXXX>YYY</TRANSXXX> </IDONTLIKETHIS_2> </Transaction> <Transaction> Expected XML Output:
<Transaction> <Transaction> <StoreName id="aa">STORE A</StoreName> <TransNo>TXN0001</TransNo> <RegisterNo>REG001</RegisterNo> <Items> <Item id="1"> <ItemID>A001</ItemID> <ItemDesc>Keychain</ItemDesc> </Item> <Item id="2"> <ItemID>A002</ItemID> <ItemDesc>Wallet</ItemDesc> </Item> </Items> </Transaction> <Transaction> Code used to remove the namespace (xmlns):
<xsl:template match="*"> <xsl:element name="{local-name()}"> <xsl:apply-templates select="@*|node()"/> </xsl:element> </xsl:template> <xsl:template match="@*"> <xsl:attribute name="{local-name()}"> <xsl:value-of select="."/> </xsl:attribute> </xsl:template>
-9577940 0 Yes,thats possible to download and save the .mp3(or any kind of file)into NSDocument directory and then you can retrive from that and play by using AVAudioPlayer.
NSString *downloadURL=**your url to download .mp3 file** NSURL *url = [NSURLURLWithString:downloadURL]; NSURLConnectionalloc *downloadFileConnection = [[[NSURLConnectionalloc] initWithRequest: [NSURLRequestrequestWithURL:url] delegate:self] autorelease];//initialize NSURLConnection NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *fileDocPath = [NSStringstringWithFormat:@"%@/",docDir];//document directory path [fileDocPathretain]; NSFileManager *filemanager=[ NSFileManager defaultManager ]; NSError *error; if([filemanager fileExistsAtPath:fileDocPath]) { //just check existence of files in document directory } NSURLConnection is used to download the content.NSURLConnection Delegate methods are used to support downloading. (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { } -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { NSFileManager *filemanager=[NSFileManagerdefaultManager]; if(![filemanager fileExistsAtPath:filePath]) { [[NSFileManagerdefaultManager] createFileAtPath:fileDocPath contents:nil attributes:nil]; } NSFileHandle *handle = [NSFileHandlefileHandleForWritingAtPath:filePath]; [handle seekToEndOfFile]; [handle writeData:data]; [handle closeFile]; } -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { UIAlertView *alertView=[[UIAlertViewalloc]initWithTitle:@”"message: [NSStringstringWithFormat:@"Connection failed!\n Error - %@ ", [error localizedDescription]] delegate:nilcancelButtonTitle:@”Ok”otherButtonTitles:nil]; [alertView show]; [alertView release]; [downloadFileConnectioncancel];//cancel downloding } Retrieve the downloaded Audio and Play:
NSString *docDir1 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *myfilepath = [docDir1 stringByAppendingPathComponent:YourAudioNameinNSDOCDir]; NSLog(@”url:%@”,myfilepath); NSURL *AudioURL = [[[NSURLalloc]initFileURLWithPath:myfilepath]autorelease]; Just write your code to play Audio by using AudioURL
I Like to know if u have any clarification in this regard.
Thank you
-4880992 0Actually I did that in visual studio and it worked well in preview (display the current date by default for the parameter and allow people to select other date) .
But for some reason, the subscription setting still asked me for the parameter value (as in the early post "Report Parameter Values").
-29503773 0From what I learned from the forums(https://www.millennium.berkeley.edu/pipermail/tinyos-help/2007-July/026348.html) TOSSIM always sends at 0dbm and doesn't give dynamic change in the signal strength. Remember simulators have the limitations and Tossim assumes everything runs smoothly. But if you are interested in estimating quality you should consider some other parameter such as gain which can be programmed using the TOSSIM.
-14841031 0All you have to do is correct your signatures like so:
const T& operator [](char* b) const; T& operator [](char* b); I've removed the const qualifier from the second operator.
if I use
AssArray["llama"]=T, how am I supposed to get the value of T into the operator overloading-function?
You don't. You just return a reference to where the new value should be stored, and the compiler will take care of the rest. If "llama" does not exist in the array, you need to create an entry for it, and return a reference to that entry.
you need to install an event filter, there is a nice example in documentation.
-12666182 0Math expressions can be very complex, I presume you are referring to arithmetic instead. The normal form (I hope my wording is appropriate) is 'sum of monomials'.
Anyway, it's not an easy task to solve generally, and there is an ambiguity in your request: 2 expressions can be syntactically different (i.e. their syntax tree differ) but still have the same value. Obviously this is due to operations that leave unchanged the value, like adding/subtracting 0.
From your description, I presume that you are interested in 'evaluated' identity. Then you could normalize both expressions, before comparing for equality.
To evaluate syntactical identity, I would remove all parenthesis, 'distributing' factors over addends. The expression become a list of multiplicative terms. Essentially, we get a list of list, that can be sorted without changing the 'value'.
After the expression has been flattened, all multiplicative constants must be accumulated.
a simplified example:
a+(b+c)*5 will be [[1,a],[b,5],[c,5]] while a+5*(c+b) will be [[1,a],[5,c],[5,b]]
edit after some improvement, here is a very essential normalization procedure:
:- [library(apply)]. arith_equivalence(E1, E2) :- normalize(E1, N), normalize(E2, N). normalize(E, N) :- distribute(E, D), sortex(D, N). distribute(A, [[1, A]]) :- atom(A). distribute(N, [[1, N]]) :- number(N). distribute(X * Y, L) :- distribute(X, Xn), distribute(Y, Yn), % distribute over factors findall(Mono, (member(Xm, Xn), member(Ym, Yn), append(Xm, Ym, Mono)), L). distribute(X + Y, L) :- distribute(X, Xn), distribute(Y, Yn), append(Xn, Yn, L). sortex(L, R) :- maplist(msort, L, T), maplist(accum, T, A), sumeqfac(A, Z), exclude(zero, Z, S), msort(S, R). accum(T2, [Total|Symbols]) :- include(number, T2, Numbers), foldl(mul, Numbers, 1, Total), exclude(number, T2, Symbols). sumeqfac([[N|F]|Fs], S) :- select([M|F], Fs, Rs), X is N+M, !, sumeqfac([[X|F]|Rs], S). sumeqfac([F|Fs], [F|Rs]) :- sumeqfac(Fs, Rs). sumeqfac([], []). zero([0|_]). mul(X, Y, Z) :- Z is X * Y. Some test:
?- arith_equivalence(a+(b+c), (a+c)+b). true . ?- arith_equivalence(a+b*c+0*77, c*b+a*1). true . ?- arith_equivalence(a+a+a, a*3). true . I've used some SWI-Prolog builtin, like include/3, exclude/3, foldl/5, and msort/2 to avoid losing duplicates.
These are basic list manipulation builtins, easily implemented if your system doesn't have them.
edit
foldl/4 as defined in SWI-Prolog apply.pl:
:- meta_predicate foldl(3, +, +, -). foldl(Goal, List, V0, V) :- foldl_(List, Goal, V0, V). foldl_([], _, V, V). foldl_([H|T], Goal, V0, V) :- call(Goal, H, V0, V1), foldl_(T, Goal, V1, V). handling division
Division introduces some complexity, but this should be expected. After all, it introduces a full class of numbers: rationals.
Here are the modified predicates, but I think that the code will need much more debug. So I allegate also the 'unit test' of what this micro rewrite system can solve. Also note that I didn't introduce the negation by myself. I hope you can work out any required modification.
/* File: arith_equivalence.pl Author: Carlo,,, Created: Oct 3 2012 Purpose: answer to http://stackoverflow.com/q/12665359/874024 How to check if two math expressions are the same? I warned that generalizing could be a though task :) See the edit. */ :- module(arith_equivalence, [arith_equivalence/2, normalize/2, distribute/2, sortex/2 ]). :- [library(apply)]. arith_equivalence(E1, E2) :- normalize(E1, N), normalize(E2, N), !. normalize(E, N) :- distribute(E, D), sortex(D, N). distribute(A, [[1, A]]) :- atom(A). distribute(N, [[N]]) :- number(N). distribute(X * Y, L) :- distribute(X, Xn), distribute(Y, Yn), % distribute over factors findall(Mono, (member(Xm, Xn), member(Ym, Yn), append(Xm, Ym, Mono)), L). distribute(X / Y, L) :- normalize(X, Xn), normalize(Y, Yn), divide(Xn, Yn, L). distribute(X + Y, L) :- distribute(X, Xn), distribute(Y, Yn), append(Xn, Yn, L). sortex(L, R) :- maplist(dsort, L, T), maplist(accum, T, A), sumeqfac(A, Z), exclude(zero, Z, S), msort(S, R). dsort(L, S) :- is_list(L) -> msort(L, S) ; L = S. divide([], _, []). divide([N|Nr], D, [R|Rs]) :- ( N = [Nn|Ns], D = [[Dn|Ds]] -> Q is Nn/Dn, % denominator is monomial remove_common(Ns, Ds, Ar, Br), ( Br = [] -> R = [Q|Ar] ; R = [Q|Ar]/[1|Br] ) ; R = [N/D] % no simplification available ), divide(Nr, D, Rs). remove_common(As, [], As, []) :- !. remove_common([], Bs, [], Bs). remove_common([A|As], Bs, Ar, Br) :- select(A, Bs, Bt), !, remove_common(As, Bt, Ar, Br). remove_common([A|As], Bs, [A|Ar], Br) :- remove_common(As, Bs, Ar, Br). accum(T, [Total|Symbols]) :- partition(number, T, Numbers, Symbols), foldl(mul, Numbers, 1, Total), !. accum(T, T). sumeqfac([[N|F]|Fs], S) :- select([M|F], Fs, Rs), X is N+M, !, sumeqfac([[X|F]|Rs], S). sumeqfac([F|Fs], [F|Rs]) :- sumeqfac(Fs, Rs). sumeqfac([], []). zero([0|_]). mul(X, Y, Z) :- Z is X * Y. :- begin_tests(arith_equivalence). test(1) :- arith_equivalence(a+(b+c), (a+c)+b). test(2) :- arith_equivalence(a+b*c+0*77, c*b+a*1). test(3) :- arith_equivalence(a+a+a, a*3). test(4) :- arith_equivalence((1+1)/x, 2/x). test(5) :- arith_equivalence(1/x+1, (1+x)/x). test(6) :- arith_equivalence((x+a)/(x*x), 1/x + a/(x*x)). :- end_tests(arith_equivalence). running the unit test:
?- run_tests(arith_equivalence). % PL-Unit: arith_equivalence ...... done % All 6 tests passed true.
-1023374 0 NSURLConnection is great for getting a file from the web... It doesn't "wait" per se but its delegate callbacks:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data - (void)connectionDidFinishLoading:(NSURLConnection *)connection ...allow you to be notified when data has been received and when the data has been completely downloaded. This way you can have the App show (if you like) a UIProgressBar as the data comes in and then handle the file as you please when it is completely received.
-24579128 0 R slow assignment in setRefClassPerhaps this question should be in some programming forum, but I thought I would ask it in the statistics community. The following code illustrates the problem when performing global assignment in R's setRefClass:
class <- setRefClass("class", fields = list( params = "numeric" ), methods = list( initialize = function() { params <<- 5 }, do.stuff = function() { for (i in 1:1e5) params <<- 2 } )) # FAST: params <- 5 time <- Sys.time(); for (i in 1:1e5) params <- 2; time <- Sys.time() - time print(time) # SLOW: newclass <- class$new() time <- Sys.time(); newclass$do.stuff(); time <- Sys.time() - time print(time) And pqR shows a slight improvement in runtime, but nothing drastic.
I would like to know why this is happening... in my mind, assigning a variable should be fast. Maybe this has something to do with locating an object "slot" (variable location), similar to S3/S4 classes. I bet I can only observe such behavior with R, and not C++.
-24333969 0 Android calculate the area of polygon using canvas drawing(not maps)I use this codes for draw a polygon on a canvas. But I want to calculate the area of polygon. Of course give the measurements of each line. I see a lot of example on maps but ı don't convert/adapt on canvas. Can anyone showing a way or method ?
Thanks in advance.
import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Point; import android.os.Bundle; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new DrawingView(MainActivity.this)); } class DrawingView extends SurfaceView { private SurfaceHolder surfaceHolder; private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); private List<Point> pointsList = new ArrayList<Point>(); public DrawingView(Context context) { super(context); surfaceHolder = getHolder(); paint.setColor(Color.BLACK); paint.setStyle(Style.FILL); } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { if (surfaceHolder.getSurface().isValid()) { // Add current touch position to the list of points pointsList.add(new Point((int) event.getX(), (int) event.getY())); // Get canvas from surface Canvas canvas = surfaceHolder.lockCanvas(); // Clear screen canvas.drawColor(Color.WHITE); // Iterate on the list for (int i = 0; i < pointsList.size(); i++) { Point current = pointsList.get(i); Point first = pointsList.get(0); // Draw points canvas.drawCircle(current.x, current.y, 5, paint); // Draw line with next point (if it exists) if (i + 1 < pointsList.size()) { Point next = pointsList.get(i + 1); canvas.drawLine(current.x, current.y, next.x, next.y, paint); canvas.drawLine(next.x, next.y, first.x, first.y, paint); c } } // Release canvas surfaceHolder.unlockCanvasAndPost(canvas); } } return false; } } }
-32263667 0 const char& operator[](std::size_t position) const would prevent that, except if the user of the code used const_cast to remove the const.
Adding const means that the data that the reference refers to can't be changed
If this is only a timeout error, try putting set_time_limit(xx); on top of your code. With xx corresponding to the time to wait in seconds.
Putting 0 means no time limit, but it may be endless if your script enters an infinite loop, of if it is waiting a feedback from your encoding command that never arrives...
-28789665 0The following samples are all matched.
$samples = Array( 'what is 4+3', 'what is 2 plus 7', 'what is 3 * 2', 'what is 3x2', 'what is 4 times 2' ); foreach($samples as $sample) { $sample = preg_replace('/(times)|\*/', 'x', $sample); $sample = str_replace('plus', '+', $sample); preg_match('/what is \d ?[+x] ?\d/', $sample, $matches); var_dump($matches[0]); } A bit nicer in JavaScript. Just including this for the fun of it.
var samples = [ 'what is 4+3', 'what is 2 plus 7', 'what is 3 * 2', 'what is 3x2', 'what is 4 times 2' ]; samples.forEach(function(sample) { sample = sample .replace(/(times)|\*/, 'x') .replace('plus', '+') ; var match = sample.match(/what is \d ?[+x] ?\d/); console.log(match); }); 
When I swipe slightly down on the card in my swiperefreshlayout, it thinks I'm trying to refresh. How do I avoid this?
-30384264 0 PHP, SQL Code not workingim ranning into some problems agian, and hope that your guys can help me.
I have this code, that i can't get to work.
see, the strange thing is, if i change
$query2 = mysqli_query($dblogin, "SELECT * FROM devices RIGHT JOIN repair ON devices.name = repair.modelid WHERE repair.modelid=$check"); to
$query2 = mysqli_query($dblogin, "SELECT * FROM devices RIGHT JOIN repair ON devices.name = repair.modelid WHERE repair.modelid LIKE %iPad%"); i will work, just fine :-/
im really lost, and i tryed, to echo the $check, to see if there was an error in the $check variable. but thats works just fine.
<div id="slidingDiv<?=$row["id"] ?>" class="toggleDiv row-fluid single-project"> <div class="span6"> <img src="adm/images/<?=$row["image"] ?>" alt="project <?=$row["id"] ?>" /> </div> <div class="span6"> <div class="project-description"> <div class="project-title clearfix"> <h3><?=$row["name"] ?></h3> <span class="show_hide close"> <i class="icon-cancel"></i> </span> </div> <div class="project-info"> <?php $check = $row["name"]; $query2 = mysqli_query($dblogin, "SELECT * FROM devices RIGHT JOIN repair ON devices.name = repair.modelid WHERE repair.modelid=$check"); while($row = mysqli_fetch_assoc($query2)) { ?> <div> <span><?=$row["price"] ?> ,-</span><?=$row["name"] ?> </div> <?php } ?> <div> <span>Client</span>Some Client Name </div> <div> <span>Date</span>July 2013 </div> <div> <span>Skills</span>HTML5, CSS3, JavaScript </div> <div> <span>Link</span>http://examplecomp.com </div> </div> <p>Believe in yourself! Have faith in your abilities! Without a humble but reasonable confidence in your own powers you cannot be successful or happy.</p> </div> </div> </div> If i changes it, to this, it runs just fine
<? $query = mysqli_query($dblogin, "select * from brands ORDER BY id"); while($row = mysqli_fetch_assoc($query)) { ?> <li class="filter" data-filter="<?=$row["name"] ?>"> <a href="#noAction"><img class="aimg" style="height:50px;" src="adm/images/<?=$row["image"] ?>" /></a> </li> <? } ?> </ul> <!-- Start details for portfolio project 1 --> <div id="single-project"> <? $query = mysqli_query($dblogin, "select * from devices ORDER BY name DESC"); while($row = mysqli_fetch_assoc($query)) { ?> <div id="slidingDiv<?=$row["id"] ?>" class="toggleDiv row-fluid single-project"> <div class="span6"> <img src="adm/images/<?=$row["image"] ?>" alt="project <?=$row["id"] ?>" /> </div> <div class="span6"> <div class="project-description"> <div class="project-title clearfix"> <h3><?=$row["name"] ?></h3> <span class="show_hide close"> <i class="icon-cancel"></i> </span> </div> <div class="project-info"> <?php $check = $row["name"]; $query2 = mysqli_query($dblogin, "select * from devices right join repair on devices.name = repair.modelid WHERE repair.modelid LIKE '%iPhone 6%'"); while($row = mysqli_fetch_assoc($query2)) { ?> <div> <span><?=$row["price"] ?> ,-</span><?=$row["name"] ?> </div> <?php } ?> </div> </div> </div> </div> <? } ?> EDIT
SELECT * FROM devices RIGHT JOIN repair ON devices.name = repair.modelid WHERE repair.modelid LIKE '%iPhone 6%' LIMIT 0 , 30 Gives this result
id name brand image model-id id name modelid price brand date 7 iPhone 6 Apple iphone6_small.jpg 217 Front Glas Udskiftning iPhone 6 1300 1432215986 7 iPhone 6 Apple iphone6_small.jpg 218 Bagside (komplet) iPhone 6 2500 1432216016 7 iPhone 6 Apple iphone6_small.jpg 219 Tænd/sluk Udskiftning iPhone 6 500 1432216041 7 iPhone 6 Apple iphone6_small.jpg 220 Homeknap iPhone 6 500 1432216064 7 iPhone 6 Apple iphone6_small.jpg 221 Ørehøjtaler iPhone 6 500 1432216085 7 iPhone 6 Apple iphone6_small.jpg 222 Ladestik iPhone 6 500 1432216107 7 iPhone 6 Apple iphone6_small.jpg 223 Batteri iPhone 6 500 1432216124 7 iPhone 6 Apple iphone6_small.jpg 224 Vibrator iPhone 6 500 1432216136 7 iPhone 6 Apple iphone6_small.jpg 225 Mikrofon iPhone 6 500 1432216165 7 iPhone 6 Apple iphone6_small.jpg 226 Kamera iPhone 6 500 1432216177 7 iPhone 6 Apple iphone6_small.jpg 227 Højtaler (musik/lyd) iPhone 6 500 1432216191 7 iPhone 6 Apple iphone6_small.jpg 228 WIFI Antenne iPhone 6 500 1432218537 7 iPhone 6 Apple iphone6_small.jpg 229 Jackstik iPhone 6 500 1432218564 7 iPhone 6 Apple iphone6_small.jpg 230 Jailbreak iPhone 6 500 1432218593 7 iPhone 6 Apple iphone6_small.jpg 231 Bagside (komplet) iPhone 6 2500 1432218612
-38486591 0 SharePoint 2013 get Group Owner Login Name and set Group Owner via JavaScript I'm try to first find out an owner of a Group in SharePoint 2013, and then I would like to try and set the owner of a Group using JavaScript, I am will to try either JSOM, or REST API. (if I understand how that, JSOM vs. REST works)
I have tried with JSOM:
function getGroupOwner (desiredGroupName) { var clientContext = new SP.ClientContext.get_current(); var web = clientContext.get_web(); var groups = web.get_groups(); var group = groups.getByName(desiredGroupName); var groupOwner = group.get_owner(); clientContext.load(web); clientContext.executeQueryAsync( function() { console.log('Success'); var ownerLoginName = groupOwner.get_loginName(); console.log('ownerLoginName: ' + ownerLoginName); }, function (sender, args) { console.log('Error: ' + args.get_message()); } } I at least get a "Success", but it then gives me an error of:
The property or field 'LoginName' has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.
Once I solve this, I was going to move onto the set_owner() function.
Any advice on this would be appreciated.
-10283066 0First of all, if I understood you, for what you want you are going to need jQuery, why? Because javascript doesn't know what CSS properties are affecting to an specific element.
Second, the way you are using CSS is not the correct one, you are mixing desing and functionality and for the easiest task like this one you will encounter problems like this one. CSS is not intended to show or hide menus even if you can, CSS is to style things even dinamically but when the user interaction gets involved you are screwed. So be careful :P
In jQuery should be something like this:
$(document).ready(function() { $('ul').on('click', 'li a', function() { $(this.parentElement.parentElement).hide(); }); });
-20771147 0 Just add below code in your edit-text
android:hint="Your Text"; // XML or even you can set it run time by using following code
EditText text = new (EditText) findviewbyid (R.id.text1); text1.setHint("Enter your message here");
-24805623 0 $list = ['a', 'b', 'c', 'd', 'e', 'f', '1', '2', '3', '4', '5', '6', '7', '8', '9']; $list2 = []; $c = 0; $temp_array = []; for ($i = 0; $i < Count($list); $i++) { $c++; array_push($temp_array, $list[$i]); if ($c >= 2) { array_push($list2, $temp_array); $temp_array = []; $c = 0; } } print_r($list2); echo '<br />List2: ' . count($list2) . '<br />List: ' . count($list); EDIT: or the solution which Mark Baker provided with the array_chunk() function. It's less code.
-25779194 0 Stored procedure if record exists then updateI'm trying to check if a record exists and then update it if it does
Here is what I current have: (Which obviously does not work)
CREATE PROCEDURE dbo.update_customer_m @customer_id INT , @firstname VARCHAR(30) , @surname VARCHAR(30) , @gender VARCHAR(6) , @age INT , @address_1 VARCHAR(50) , @address_2 VARCHAR(50) , @city VARCHAR(50) , @phone VARCHAR(10) , @mobile VARCHAR(11) , @email VARCHAR(30) , AS IF EXISTS ( SELECT * FROM dbo.Customer WHERE CustID = @customer_id ) BEGIN UPDATE dbo.Customer SET Firstname = @firstname, Surname = @surname, Age = @age, Gender = @gender, Address1 = @address_1, Address2 = @address_2, City = @city, Phone = @phone, Mobile = @mobile, Email = @email WHERE CustID = @customer_id END Is there a better way of doing this that works?
-8562314 0There are 3 types of javascript popups:
You need to make sure which type of popup is shown and act accordingly.
-9701381 0Look at the Pinax project's account auth_backends , there it replaces with own one. I think Pinax code helps you while changing Django's authentication backend.
-18886672 0 How do I match the root of a content URI in Android 4.3?I'd like to return some results when someone hits the root of my ContentProvider, which has worked fine up until now. As of Android 4.3, however, I cannot match the root! Here's everything I've tried, and nothing will work. This returns -1 under 4.3, but not under earlier versions.
How do I match that URI?
private int testMatch(){ UriMatcher mUriMatcher = new UriMatcher(0); mUriMatcher.addURI("com.someone.app.provider.thingy", "/#", 0); mUriMatcher.addURI("com.someone.app.provider.thingy", "/", 1); mUriMatcher.addURI("com.someone.app.provider.thingy", "", 2); mUriMatcher.addURI("com.someone.app.provider.thingy", "/*", 3); mUriMatcher.addURI("com.someone.app.provider.thingy", "#", 4); mUriMatcher.addURI("com.someone.app.provider.thingy", "*", 5); mUriMatcher.addURI("com.someone.app.provider", "thingy", 6); Uri uri=Uri.parse("content://com.someone.app.provider.thingy"); return mUriMatcher.match(uri); }
-36919775 0 Data Between Two Tables Excuse any novice jibberish I may use to explain my conundrum but hopefully someone here will be able to look past that and provide me with an answer to get me unstuck.
SESSIONS
+--------+---------+----------+ | id | appID | userID | +--------+---------+----------+ | 1 | 1 | 96 | +--------+---------+----------+ | 2 | 2 | 97 | +--------+---------+----------+ | 3 | 1 | 98 | +--------+---------+----------+ USERS
+--------+---------+ | id | name | +--------+---------+ | 96 | Bob | +--------+---------+ | 97 | Tom | +--------+---------+ | 98 | Beth | +--------+---------+ For each session in the Sessions table that has an appID of 1, I want to get the users name from the Users table. The Sessions userID column is linked with the Users tables id column.
So my desired result would be:
["Bob", "Beth"] Any suggestions/help?
-36640380 0 How to make my android app downloadable from Facebook pageI am making one android app and I want to post one advertisement on Facebook page that will have one video regarding my app and a link to download my android app. The user should be able to see the advertisement with video and if he wish to download my android app then after click on given link it should go to Play Store and will be able to download the app.
Anyone please help me to do this. How I can do this ?. I don't have any idea.
Thanks in advance.
-19974279 0no there isn't ready made code. we wrote our own solution and I know of a few other ones.. the MAP you use really doesn't matter.
the grouping can happen 'on the model'
-26119309 0A validation is a check that the value entered is legitimate for the context of its field (from technical perspective), for example: is 5 as a numeric value acceptable for Age(v.s. -5)?, while -5 is acceptable as Temperature for example.
The business rule is more of a business perspective. It is a check that the values (that passed the validation) are acceptable by the policies and procedures of the business. E.g. the person who is allowed to register has to be a resident, and 18 years old or more..etc. The business rule might check one (or more) field(s) value(s), and might consult data stored in a database and/or do some calculation(s) to ensure that the value(s) pass the business rules.
So, for the example posted above by hanna, the value 15 should pass the field validation (as it is a valid value for Age), but it will not pass the business rule check that the married person's age must be >15.
-14778895 0There are a set of several templates that control the checkout page. They can be found in the WooCommerce plugin folder in templates/checkout.
You can put a woocommerce/templates/checkout folder inside your theme's folder and copy the templates you want to alter into it. Those will override the normal templates without altering the plugin itself. That way your changes won't get overwritten when WooCommerce is updated.
-16535929 0Any document can have only one XML declaration and it must be at the very beginning of the document.
The parser will see this as either nesting of documents or improper placement of the XML declaration, both of which will cause an error.
**<?xml version="1.0" encoding="utf-8"?>** <soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope"> <soapenv:Body> <return> **<?xml version="1.0"?>** <catalog>
-31014241 0 You can do this with
+ (NSArray<ObjectType> * nullable)arrayWithContentsOfFile:(NSString * nonnull)aPath and
- (BOOL)writeToFile:(NSString * nonnull)path atomically:(BOOL)flag
-21907263 0 Should I even be using ImageView? I've seen some answers suggesting that a WebView is a better starting point.
This is the way I solved it in the end. I simply wrapped the image filename in some HTML and gave it to a webview.
This gave me the following specific benefits:-
Here is the code I ended up with.
File imgFile = new File(FILESDIR,FILENAME); if(imgFile.exists()){ WebView wv = (WebView) rootView.findViewById(R.id.imageView1); wv.getSettings().setBuiltInZoomControls(true); wv.getSettings().setDisplayZoomControls(true); String html = ("<html><img src='"+imgFile.getName()+"'></html>" ); wv.loadDataWithBaseURL("file://"+imgFile.getAbsolutePath(), html, "text/html", "utf-8", ""); }
-34525971 0 The first seed node is special, as documented in the Cluster documentation: http://doc.akka.io/docs/akka/snapshot/java/cluster-usage.html
It must be the same 1st configured node on all nodes, in order for all of them to be really sure that they join the same cluster.
Quote:
The seed nodes can be started in any order and it is not necessary to have all seed nodes running, but the node configured as the first element in the seed-nodes configuration list must be started when initially starting a cluster, otherwise the other seed-nodes will not become initialized and no other node can join the cluster. The reason for the special first seed node is to avoid forming separated islands when starting from an empty cluster. It is quickest to start all configured seed nodes at the same time (order doesn't matter), otherwise it can take up to the configured seed-node-timeout until the nodes can join.
Once more than two seed nodes have been started it is no problem to shut down the first seed node. If the first seed node is restarted, it will first try to join the other seed nodes in the existing cluster.
-26739299 0 Rails - How can I display one nested attributes (Solved)I have a new problem, I Create a web where I upload many images, using nested attributes and polymorphic table, in my index.html I want to show only one image, but I can't find how. But I'm new in rails.
photography.rb
class Photography < ActiveRecord::Base validates :title, :description, presence: true belongs_to :user has_many :images, as: :imageable, dependent: :destroy accepts_nested_attributes_for :images, :reject_if => lambda { |a| a[:img_str].blank? }, :allow_destroy => true end image.rb
class Image < ActiveRecord::Base belongs_to :imageable, polymorphic: true mount_uploader :img_str, AssetUploader end index.html.erb
<% for photo in @photo %> <%= link_to photo.title, photography_path(photo) %> <% photo.images.each do |images| %> <%= images.img_str %> <% end %> <% end %> With the for method I show all the image, try add .first, but says undefined method first for 5:Fixnum. I think that I have to create a helper method, but I not sure. Can anyone help me?. Thanks
I am trying to assign values to a 2D array in VBA but its not working. Here is what I have tried:
Sub UpdateCustomName() Dim CellTags() As String Dim temp() As String Dim ControlName As String Dim CellValue As String Dim CustomName(1 To 2, 1 To 2) As String For Each Cell In ActiveSheet.UsedRange.Cells If Not Cell.Value = "" Then CellTags() = Split(Cell.Value, "*") ' here in CellTags(2) value is like ABC_E34 CustomName() = Split(CellTags(2), "_") MsgBox CustomName(1, 2) End If Next End Sub
-15942675 0 After struggling some times, I managed to figured out the solution by inserting new view below the tabbar.
This thread really helped me much about the case;
Tab bar controller inside a navigation controller, or sharing a navigation root view
Cheers;
-3805369 0The Array.Clear method will let you clear (set to default value) all elements in a multi-dimensional array (i.e., int[,]). So if you just want to clear the array, you can write Array.Clear(myArray, 0, myArray.Length);
There doesn't appear to be any method that will set all of the elements of an array to an arbitrary value.
Note that if you used that for a jagged array (i.e. int[][]), you'd end up with an array of null references to arrays. That is, if you wrote:
int[][] myArray; // do some stuff to initialize the array // now clear the array Array.Clear(myArray, 0, myArray.Length); Then myArray[0] would be null.
I'm not sure why you are trying to get that string since to my knowledge most ssl functions will take the whole cert to verify.
Have you seen this post? It looks like what you want.
Hope that helps.
EDIT:
I think this example will help you understand what's every argument and in what format should it be.
-17054522 0As said, you're asking about regular expressions commonly called a "regex". Take a look at Regular-Expressions.info for tons of good information. The page you're probably most interested in is the Literal Characters and Special Characters, which largely answers your OP. A great site to test your regex is Rubular.com. It's designed for Ruby, but works great for nearly anything I've thrown at it (sed expressions, C# replace, JS replace, etc.).
HTH
-4728422 0you can use the following
<?php $timezone = 'Pacific/Nauru'; $time = new \DateTime('now', new DateTimeZone($timezone)); $timezoneOffset = $time->format('P'); ?>
-872981 0 Here you go:
Example page - footer sticks to bottom
this will have the content right
between the footer and the header.
no overlapping.
<header>HEADER</header> <article> <p>some content here (might be very long)</p> </article> <footer>FOOTER</footer> html{ height:100%; } body{ min-height:100%; padding:0; margin:0; position:relative; } body:after{ content:''; display:block; height:100px; // compensate Footer's height } header{ height:50px; } footer{ position:absolute; bottom:0; width:100%; height:100px; // height of your Footer (unfortunately it must be defined) }
-2994255 0 :: = Scope resolution operator: http://www.php.net/manual/en/language.oop5.paamayim-nekudotayim.php
The __-prefix is a convention surrounded by built-in magic: http://www.php.net/manual/en/userlandnaming.rules.php, never start a function or variable with this if you can avoid it.
The first is a token, the second a convention.
If you really want to know most tokens, see: http://www.php.net/manual/en/tokens.php If you want to know more about naming conventions, see: http://www.php.net/manual/en/userlandnaming.php
When starting out with PHP it would hurt to read Zend coding conventions, although it's not a must and not the only way by a long shot: http://framework.zend.com/manual/en/coding-standard.html
-31348163 0You can use Mockito to mock out interface A.
@Test public void test () { //given: we have our expected and actual lists. List<String> expectedResult = Arrays.asList("id1","id2","id3"); //build our actual list of mocked interface A objects. A a1 = mock(A.class); when(a1.getId()).thenReturn("id1"); A a2 = mock(A.class); when(a2.getId()).thenReturn("id2"); A a3 = mock(A.class); when(a3.getId()).thenReturn("id3"); B b = mock(B.class); Collection<A> actualResult = Arrays.asList(a1, a2,a3); //when: we invoke the method we want to test. when(b.getCollection()).thenReturn(actualResult); //then: we should have the result we want. assertNotNull(actualResult); assertEquals(3, actualResult.size()); for (A a : actualResult) assertTrue(expectedResult.contains(a.getId())); }
-17119796 0 While there is a file system provider s3fs build on fuse. Is not always a good idea to try to mount it to the file system. Instead you should either use command line tools s3cmd or build in access to s3 into your filesystem.
The reason why I would recommend against it is that s3 is not a block device while the rest of your file system is. Everything on s3 is treated as a complete object. You can't read or write to a block of the object.
If all your are doing with the mount is copying files in its entirety to and from s3, a file system mount may work reasonably well. But you can't run anything that would expect block level acccess to files on that mount.
-14851929 0 External JavaScript working on localhost but not in remote host?This is the site: http://www.hfwebdesign.com/
I'm getting this error: Uncaught TypeError: Object [object Object] has no method 'flexslider'
But in my localhost it works perfectly.
This is the <head> (where the script is being called):
<head> <meta charset="<?php bloginfo( 'charset' ); ?>" /> <meta name="viewport" content="width=device-width" /> <title><?php wp_title( '|', true, 'right' ); ?></title> <link rel="profile" href="http://gmpg.org/xfn/11" /> <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" /> <link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo( 'template_url' ); ?>/js/flexslider/flexslider.css" /> <link rel="icon" type="image/png" href="<?php bloginfo( 'template_url' ); ?>/favicon.ico" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script src="<?php bloginfo( 'template_url' ); ?>/js/flexslider/jquery.flexslider-min.js"></script> <?php // Loads HTML5 JavaScript file to add support for HTML5 elements in older IE versions. ?> <!--[if lt IE 9]> <script src="<?php echo get_template_directory_uri(); ?>/js/html5.js" type="text/javascript"></script> <![endif]--> <?php wp_head(); ?> </head> footer:
<script type="text/javascript"> var $j = jQuery.noConflict(); $j(document).ready(function() { $j('.flexslider').flexslider({ animation: "slide" }); }); </script> </body> Could it be that the code is breaking in the web server in the remote host and not in my localhost (e.g. they are different version of LAMP/APACHE?)
-18518700 0You specify the size in your xml layout file using DP (DIP: Density Independent Pixels) instead of Pixels, you can also use wrap_content and match_parent.
For more info, http://developer.android.com/guide/practices/screens_support.html
-35549114 0The problem is not that the class is a partial class. The problem is that you try to derive a static class from another one. There is no point in deriving a static class because you could not make use Polymorphism and other reasons for inheritance.
If you want to define a partial class, create the class with the same name and access modifier.
I'm developing a material design app & for applying activity transition I have written the following code in my MainActivity.java
My MainActivity.java file's code:
public class MainActivity extends AppCompatActivity { public Toolbar toolbar; public TabLayout tabLayout; public ViewPager viewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // Call some material design APIs here // enable transitions getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS); } else { } setContentView(R.layout.activity_main); SpannableString s = new SpannableString("abc"); s.setSpan(new TypefaceSpan(this, "Pacifico.ttf"), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(false); getSupportActionBar().setTitle(s); viewPager = (ViewPager) findViewById(R.id.viewpager); setupViewPager(viewPager); tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); customTabFont(); } private void customTabFont() { String fontPath = "fonts/Pacifico.ttf"; Typeface tf = Typeface.createFromAsset(getAssets(), fontPath); TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null); tabOne.setText("Accept a Request"); tabOne.setTypeface(tf); tabLayout.getTabAt(0).setCustomView(tabOne); TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null); tabTwo.setText("Post a Request"); tabTwo.setTypeface(tf); tabLayout.getTabAt(1).setCustomView(tabTwo); } private void setupViewPager(ViewPager viewPager) { ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); adapter.addFragment(new AcceptARequest(), "Accept a Request"); adapter.addFragment(new PostARequest(), "Post a Request"); viewPager.setAdapter(adapter); } class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mFragmentList = new ArrayList<>(); private final List<String> mFragmentTitleList = new ArrayList<>(); public ViewPagerAdapter(FragmentManager manager) { super(manager); } @Override public Fragment getItem(int position) { return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } public void addFragment(Fragment fragment, String title) { mFragmentList.add(fragment); mFragmentTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitleList.get(position); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_profile) { // Check if we're running on Android 5.0 or higher if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // Call some material design APIs here getWindow().setExitTransition(new Explode()); Intent profileIntent = new Intent(MainActivity.this, ProfileActivity.class); startActivity(profileIntent, ActivityOptions .makeSceneTransitionAnimation(this).toBundle()); } else { // Implement this feature without material design Intent profileIntent = new Intent(MainActivity.this, ProfileActivity.class); startActivity(profileIntent); } } else if (id == R.id.action_settings) { Intent settingsIntent = new Intent(MainActivity.this, SettingsActivity.class); startActivity(settingsIntent); } else if (id == R.id.action_help) { Intent helpIntent = new Intent(Intent.ACTION_SEND); Intent chooser = Intent.createChooser(helpIntent, "Choose an app"); helpIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"help@abcxyz123.com"}); helpIntent.setType("message/rfc822"); startActivity(chooser); } else if (id == R.id.action_faqs) { Intent faqsIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.abcxyz123.com/faqs")); startActivity(faqsIntent); } else if (id == R.id.action_about) { Intent aboutIntent = new Intent(MainActivity.this, AboutActivity.class); startActivity(aboutIntent); } return super.onOptionsItemSelected(item); } } After running the app, I'm getting following error:
android.util.AndroidRuntimeException: requestFeature() must be called before adding content must be called before adding content. I do not understand why am I getting this error when I have added the requestFeature() before adding the content?
Please let me know.
I'm new to StackOverflow, so please cooperate.
Thanks in advance.
-35821657 0You can set a background-color on the :before element instead of a border-top to make it work. The pseudo-element can have a height of just 1px and a width: 100px;.
p { position: relative; margin: 50px auto; font-size: 1.5em; } p:before { content: ""; position: absolute; top: 50px; width: 100px; margin: 0 auto; height: 1px; background-color: black; /*Removed border, added background-color */ } <p> this is some text </p> i am trying to delete a table, and i followed this link http://www.techonthenet.com/sqlite/truncate.php as a tutorial. but when i execute the below code, for the first run, i expected the sqliteFactory.getRowCount() method will return 0 rows as the method sqliteFactory.deleteTable(SysConsts.SQLITE_DATABASE_TABLE_NAME); was just called before it, but what i received is a rowCount which is not zero.
in the second run of the same code, i expected the sqliteFactory.CreateTable(SysConsts.SQLITE_DATABASE_TABLE_NAME); to display Log.i(TAG, "CreateTable", "table: ["+tableName+"] does not exist, will be created"); as the table should have been deleted, but i received Log.i(TAG, "CreateTable", "table: ["+tableName+"] already exists.");
kindly please let me know how why the table is not deleted? and should i do commit after deletion?
main code:
public static void main(String[] args) throws SQLException, ClassNotFoundException { SQLiteFactory sqliteFactory = new SQLiteFactory(); sqliteFactory.newSQLiteConn(SysConsts.SQLITE_DATABASE_NAME); sqliteFactory.CreateTable(SysConsts.SQLITE_DATABASE_TABLE_NAME); sqliteFactory.insertRecord(new Record("001", "55.07435", "8.79047", "c:\\bremen_0.xml")); Log.d(TAG, "main", "rowCount: "+sqliteFactory.getRowCount()); //sqliteFactory.selectAll(); //sqliteFactory.getNodeID("53.074415", "8.788047"); sqliteFactory.selectXMLPathFor("53.074415", "8.788047"); Log.d(TAG, "", ""+sqliteFactory.getRowCountLatLngFor("53.074415", "8.788047")); Log.d(TAG, "", ""+sqliteFactory.getRowCountNodeIDFor("001")); Log.d(TAG, "", ""+sqliteFactory.getRowCountXMLPathFor("c:\\brem_0.xml")); sqliteFactory.deleteTable(SysConsts.SQLITE_DATABASE_TABLE_NAME); Log.d(TAG, "main", "rowCount: "+sqliteFactory.getRowCount()); } CreateTable:
public void CreateTable(String tableName) throws SQLException, ClassNotFoundException { if (!this.isTableExists(tableName)) { Log.i(TAG, "CreateTable", "table: ["+tableName+"] does not exist, will be created"); Connection conn = this.getConnection(); Statement stmt = conn.createStatement(); stmt.executeUpdate(this.sqlTable); stmt.close(); conn.close(); } else { Log.i(TAG, "CreateTable", "table: ["+tableName+"] already exists."); return; } } isTableExists:
private boolean isTableExists(String tableName) throws ClassNotFoundException, SQLException { Connection conn = this.getConnection(); DatabaseMetaData dbMeta = conn.getMetaData(); ResultSet resSet = dbMeta.getTables(null, null, tableName, null); boolean exists = false; if (resSet.next()) { exists = true; } else { exists = false; } resSet.close(); conn.close(); return exists; } deleteTable:
public void deleteTable(String tableName) throws ClassNotFoundException, SQLException { if (this.isTableExists(tableName)) { Log.i(TAG, "deleteTable", "table: ["+tableName+"] already exists, and will be deleted."); Connection conn = this.getConnection(); PreparedStatement ps = conn.prepareStatement("delete from "+this.TABLE_NAME); ps.close(); conn.close(); } else { Log.i(TAG, "deleteTable", "table: ["+tableName+"] does not exist, can't be deleted."); return; } } getRowCount:
public int getRowCount() throws SQLException, ClassNotFoundException { Connection conn = this.getConnection(); Statement stmt= conn.createStatement(); ResultSet resSet = stmt.executeQuery("SELECT COUNT(*) AS rowCount FROM "+TABLE_NAME+";"); int cnt = resSet.getInt("rowCount"); resSet.close(); stmt.close(); conn.close(); return cnt; }
-4191521 0 how to forbidden page cache on rails i'm design a shopping cart,there are two web page,
first is checkout page,and the second is order_success page
if user use the go back button on webbrowser then it will go back to checkout page after user have go to order_success page.
so i want to find some way to forbidden let use go back,
is there some way on rails to archieve this?
-33535237 0 Using ng-show with a required attributeSo is there a way that if I have a HTML 5 'required' attribute on an input, that if that input is not shown due to ng-show not triggering it, that this will not fire the 'required' attribute?
-1495880 0This usually means you are blocking the UI thread (e.g. running a long operation inside a button click handler). Instead of using the UI thread, you will generally need to offload long I/O operations to the ThreadPool or your own worker threads. This is not always easy to do and requires careful design and a good understanding of concurrency, etc.
-22510975 0 How do I get the class of a Matcher in Hamcrest?I've got a matcher, and I want to make sue the object I have is the right type. E.g. a long or a String.
void expect(String xpath, Matcher matcher) { String actual = fromXpath(xpath); // convert actual into correct type for matcher assertThat(actual, matcher); } I want method like Matcher.getType. So I could do something like
if (matcher.getType().equals(Long.class)) { long actual = Long.parseString(fromXpath(xpath)); } But I cannot see for the life of me how I get the of the matcher.
-24840578 0You need to send the data out from the server code:
app.get('/content.json',function(req, res) { request("http://www.google.com", function(error, response, body) { res.send(body); }); }); Edit: As the JS client is expecting appication/json, you should set the response header sent from server as well:
res .header('Content-Type', 'application/json') .send(body);
-39329146 0 When a server listens on a computer, it specifies a port it wants it's connections coming in from , so ports are important for setting up servers. This is useful as you can have multiple applications listening on different ports without the different applications accidentally talking to eachother. So you should decide on a port that isn't a standard( 80 is for HTTP for example) to exclusively use for you gameserver so the client knows which port to send the requests to.
If you want to handle multiple connections at once the best thing to do is threading.
-19518717 0A simple way of generating a printable report from a Datagridview is to place the datagridview on a Panel object. It is possible to draw a bitmap of the panel.
Here's how I do it.
'create the bitmap with the dimentions of the Panel Dim bmp As New Bitmap(Panel1.Width, Panel1.Height)
'draw the Panel to the bitmap "bmp" Panel1.DrawToBitmap(bmp, Panel1.ClientRectangle)
I create a multi page tiff by "breaking my datagridview items into pages. this is how i detect the start of a new page:
'i add the rows to my datagrid one at a time and then check if the scrollbar is active. 'if the scrollbar is active i save the row to a variable and then i remove it from the 'datagridview and roll back my counter integer by one(thus the next run will include this 'row.
Private Function VScrollBarVisible() As Boolean Dim ctrl As New Control For Each ctrl In DataGridView_Results.Controls If ctrl.GetType() Is GetType(VScrollBar) Then If ctrl.Visible = True Then Return True Else Return False End If End If Next Return Nothing End Function I hope this helps
-6892869 0I haven't found a way to do this that isn't a hack, but here's the simplest hack I could think of:
<script type="text/javascript"> function tweakWidthForScrollbar() { var db = document.body; var scrollBarWidth = db.scrollHeight > db.clientHeight ? db.clientWidth - db.offsetWidth : 0; db.style.paddingRight = scrollBarWidth + "px"; } </script> ... <body onresize="tweakWidthForScrollbar()"> The idea is to detect whether the vertical scrollbar is in use, and if it is, calculate its width and allocate just enough extra padding for it.
-18704738 0You want to be using the right shift operators (there are two) and shift thevalue right:
if ((input >>> 24) == 0) { // high-order 40 bits are all 0. } Alternatively, you can simply bit-mask with:
if ((input & 0xFFFFFFFFFF000000L) == 0) { // high-order 40 bits are all 0. } Note that >>> will put 0 in the high-order bits, and >> will put 0 for positive numbers, and 1 for negative.
you don't need to create a thread just to start timer in it. You can just start timer in your main thread. Its function will run on a thread from threadpool.
I don't see why you need to create a thread for start() function. It needs to be run at least partially before your timer first work. So, you may execute RegKeys = load.read(RegKeys); (and probably other code from start) in main thread. if you insist on running it in separate thread, ensure that RegKeys is initialized. It can be done by, e.g. setting ManualResetEvent after initializing RegKeys and waiting for this ManualResetEvent in timer callback.
You should stop timer on process exit.
you need to wait for started thread's stopping using Thread.Join method or by waiting on some WaitHandle (ManualResetEvent e.g.) being set in thread on finish.
It's depend on what you exactly mean under "deleting of all rows". The method GridUnload could be very helpful in many cases, but it delete more as only grid contain.
Another method used intern in jqGrid is:
var trf = $("#list tbody:first tr:first")[0]; $("#list tbody:first").empty().append(trf); Probably it is what you need. It delete all grid rows excepting of the first one. You can overwrite the code also as the following
var myGrid = $("#list"); // the variable you probably have already somewhere var gridBody = myGrid.children("tbody"); var firstRow = gridBody.children("tr.jqgfirstrow"); gridBody.empty().append(firstRow);
-31918497 0 How to verify a contextual condition when a method is called with Moq I'm using Moq and I need to check a condition when a mock method is called. Into following example i try to read the Property1 property, but this could be any expression:
var fooMock = new Mock<IFoo>(); fooMock.Setup(f => f.Method1()) .Returns(null) .Check(f => f.Property1 == true) // Invented method .Verifiable(); My final objective is to check if a condition is true when the method is called. How can I perform this?
-10068013 0 Django-users is the user authentication api of Django. -8822764 0 Why will a Range not work when descending?Why will (1..5).each iterate over 1,2,3,4,5, but (5..1) will not? It returns the Range instead.
1.9.2p290 :007 > (1..5).each do |i| puts i end 1 2 3 4 5 => 1..5 1.9.2p290 :008 > (5..1).each do |i| puts i end => 5..1
-37626479 0 I used Filype's answer and changed to a correct one as because it's showing error if you try to uncheck the last one. Here it is..
$(document).ready(function() { //append the total dollars display under activities and hide it until clicked var $TotalDollars = 0; var $TotalDollarsDisplay = $('<div></div>'); $('.activities').append($TotalDollarsDisplay); $($TotalDollarsDisplay).hide(); function updateTotal() { var total = $(".activities input:checkbox:checked"); if(total.length){ // Get the text from the parent total = total.map(function(idx, el) { return $(el).parent().text(); }) // convert the jquery object to an array .toArray() // extract the value from the string using regex .map(function(item) { var match = item.match(/\$(\d+)/); return parseInt(match[1]); }) // calculate the total with reduce .reduce(function(cur, next) { return cur + next; }); console.log(total); $TotalDollarsDisplay.text(total); $TotalDollarsDisplay.show(); } else{ $($TotalDollarsDisplay).hide(); } } //checkbox needs to show unique dates and times and disable duplicates $(".activities").find("input:checkbox").change(function() { //variables for activity input names var $jsFrameworks = $("input[name='js-frameworks']"); var $Express = $("input[name='express']"); var $jsLibs = $("input[name='js-libs']"); var $Node = $("input[name='node']"); var $MainConf = $("input[name='all']"); var $Npm = $("input[name='npm']"); var $BuildTools = $("input[name='build-tools']"); var $CheckedActivities = $(".activities").find('input:checkbox:checked').length; console.log($CheckedActivities); //Disable duplicate times scheduled if (($jsFrameworks).is(':checked')) { ($Express).prop('disabled', true); } else { ($Express).prop('disabled', false); } if (($Express).is(':checked')) { ($jsFrameworks).prop('disabled', true); } else { ($jsFrameworks).prop('disabled', false); } if (($jsLibs).is(':checked')) { ($Node).prop('disabled', true); } else { ($Node).prop('disabled', false); } if (($Node).is(':checked')) { ($jsLibs).prop('disabled', true); } else { ($jsLibs).prop('disabled', false); } //add up the total dollars for each activity //Adding the non duplicate workshops to the total updateTotal(); }); });
-34540856 0 Length is taken into account, but not in the way you expect. In string comparison, the first characters of each string are compared to each other first. If they are equal, then the second characters are compared and so on. So in your example, the first characters to be compared are '1' and '8'. '8' is larger.
If you had compared "10.72" against "1.87", the first characters would be equal, so the next thing would be to compare "0" against ".".
If you want to compare numeric values, you have to convert the strings to their numeric representation, or else you would have to write your own comparator that would treat strings as numerics. I hope that sheds some light on it.
-1668678 0You have to notify the OS that you've made the changes - it doesn't constantly watch or load the values. Simply broadcast a WM_SETTINGCHANGE:
SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, NULL,NULL);
-27831529 0 You need to find the CrefSyntax node that corresponds to the type name and then you can use SemanticModel.GetSymbolInfo() to get the ISymbol you want:
string code = @"namespace Foo { /// <summary>This is an xml doc comment <see cref=""MyClass"" /></summary> class MyClass {} }"; var tree = SyntaxFactory.ParseSyntaxTree(code); CrefSyntax cref = tree.GetRoot() .DescendantNodes(descendIntoTrivia: true) .OfType<CrefSyntax>() .FirstOrDefault(); var compliation = CSharpCompilation.Create("foo").AddSyntaxTrees(tree); var model = compliation.GetSemanticModel(tree); ISymbol symbol = model.GetSymbolInfo(cref).Symbol;
-32827365 0 I had the same issue. And so starts a search of SO. So the above helped me out, but the whole, "if iOS9 thing" might be best framed like this:
if ([self respondsToSelector:@selector(inputAssistantItem)]) { // iOS9. UITextInputAssistantItem* item = [self inputAssistantItem]; item.leadingBarButtonGroups = @[]; item.trailingBarButtonGroups = @[]; } Happily, I'd created a sub-class of a UITextField, (CHTextField) and was in use everywhere. So it was a very easy fix to whack this in the over-ridden "init" method.
Hope it helps.
-1645122 0 Is there an Alpha matcher for .NET Regex?The usual alpha symbol for regular expressions \w in the .NET Framework matches alphanumeric symbols, and thus is equivalent to [a-zA-Z0-9], right? There is any [a-zA-Z] equivalent in .NET?
I'm look for vim command which will exit from Glog'ed file view back to the normal (original) file.
EXAMPLE:
Let say I'm viewing a file with vim.
After entering :Glog I'm able to browse through all git versions of this file.
I'm looking for command (or something) which let's me go back to viewing current file version so I can modify and save this file.
Is it possible?
-6571350 0You can use events to update the Combobox SourceItems on a parent page that displays
ie in your custom control or form that handles creating the new item
public static readonly RoutedEvent NewItemAddedEvent = EventManager.RegisterRoutedEvent("NewItemAdded", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(CloseableTabItem)); public event RoutedEventHandler NewItemAdded { add { AddHandler(NewItemAddedEvent, value); } remove { RemoveHandler(NewItemAddedEvent, value); } } private void SaveButton_Click(object sender, RoutedEventArgs e) { ProActive.Contact currentContact = (ProActive.Contact)ItemsListBox.Items.CurrentItem;
switch (MessageBox.Show("Are you sure?", "Save Changes", MessageBoxButton.YesNoCancel)) { case MessageBoxResult.Yes: if (currentContact.EntityState == System.Data.EntityState.Detached) ProActive.App.ProActiveDatabaseEntities.Contacts.AddObject(currentContact); ProActive.App.ProActiveDatabaseEntities.SaveChanges(); this.RaiseEvent(new RoutedEventArgs(NewItemAddedEvent, this)); break; } then in the master page that displays the combo box, attach the event that fired after you 'save' the new item
ProActive.TabPagesControls.AllContactsDetailsControl cdc = new AllContactsDetailsControl(); cdc.NewItemAdded += AllContactsDetailsNewItemAdded; then handle the event on the parent page after it gets fired to re-load the itemssource
private void AllContactsDetailsNewItemAdded(object sender, RoutedEventArgs e) { // New item added so refresh the items listbox AllContactListItemsListBox.ItemsSource = from c in ProoActive.App.ProActiveDatabaseEntities.Contacts select c; }
-8315444 0 You are explicitly setting receiver to null inside toggleButton.setOnClickListener and in onPause:
receiver = null; Try removing those lines and see if it fixes the issue
-10177801 0You should try QT. It is pretty good framework for cross-platform development. The opensource version is free and very well maintained and has the LGPL license. That means you can sell your product as closed source but then you have to dynamically link to QT libraries.
-22638499 0simply use the Out-File cmd but DON'T forget to give an encoding type: -Encoding UTF8 so use it so:
$log | Out-File -Append C:\as\whatever.csv -Encoding UTF8
-Append is required if you want to write in the file more then once.
-11501002 0 django template content not showing upIn my views i have pointed my code to login.html >But the alert in the ready function or the content so f the body are not seen on the UI.What am i doing wrong here
{% extends "base/base.html" %} <script> $(document).ready(function() { alert('1'); }); </script> some code here some code here some code here some code here some code here some code here <b>{{response_dict.yes}} testing and testing and testinf</b> <b>{{a}}</b> <form action="/logon/" method="post" name="myform"> {% csrf_token %} <b>Username</b><input type="text" name="username" id="username"></input> <br><b>Password</b><input type="password" name="password" id="password"></input> <b></b><input type="submit" value="Submit"></input> <img src="/media/img/hi.png" alt="Hi!" /> <!-- This is working dude --> <img alt="Hi!" src="/opt/labs/lab_site/media/img/hi.png"> </form>
-22826596 0 I know these kind of insertions (and their differences):
Map[key] = value;
Map[key] is not strictly for insertions. You can assign to that value as well. The postincr/postdecr operators do modify those values, as a side effect.
So Map[key]++ is legal, and does what you might expect -- increments the value stored at Map[key]. Equivalent to:
Map[key] = Map[key] + 1
-34632070 0 Kotlin documentation doesn't support tags like '' well
I'm writing doc comments to describe a method.
/** * <p>necessary * <p>setType is to set the PendingIntend's request code</p> */ But it won't show the paragraphs. If I don't use the <p>, all the documentation is in a line without any break. It works in Java class but when it comes to Kotlin, I don't know how to deal with it.
Found the solution here works well: iOS 6 address book empty kABPersonPhoneProperty "To retrieve all phone numbers you need to get all linked contacts and then look for phone numbers in that contacts."
-23979407 1 Json module error for saving dictionaryI'm coding a program to oraganise my homework. I got an error while trying to save my dicts with json and i have no idea what to do. I'm really lost. Also I'm kind of a noob so don't post anything to complex if you can. Thanks Here's the error
Traceback (most recent call last): File "Homework.py", line 12, in <module> json.load(f1) File "F:\Software\Python\lib\json\__init__.py", line 268, in load parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw) File "F:\Software\Python\lib\json\__init__.py", line 318, in loads return _default_decoder.decode(s) File "F:\Software\Python\lib\json\decoder.py", line 343, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "F:\Software\Python\lib\json\decoder.py", line 361, in raw_decode raise ValueError(errmsg("Expecting value", s, err.value)) from None ValueError: Expecting value: line 1 column 1 (char 0) If you want my whole code (not finished yet, it's missing a lot)
#insert date to rate urgency of the tasks #BLOCK 1:1 print("today's date, month(insert month number)") ThisMonth = input(">>>") print("today's date, day(insert day number)") ThisDay = input(">>>") #BLOCK 1:2 #import dictionaries import json with open('LessonOut.txt', 'r') as f1: json.load(f1) with open('ExercisesOut.txt', 'r') as f2: json.load(f2) with open('AssignmentOut.txt', 'r') as f3: json.load(f3) #BLOCK 1:5 #everything will be in a while true loop for it to run smoothly until stopped while True: Input = input('>>>') #This is used to add a task #BLOCK 2:1 if Input == 'add': print('Name of task?') Name = input('>>>') print('Description of task?') Desc = input('>>>') print('Rate the time it takes you to do the task on a scale from 1 to 20') Time = input('>>>') print('>>>') Imp = input('>>>') print("Rate how much you want to do it on a scale from 1 to 5 (1= want to do it, 5= don't want to") Want = input(">>>") print("enter deadline (month)") TimeMonth = input(">>>") print("enter deadline (day)") TimeDay = input(">>>") print("what type of homework is it? (Lesson/Exercises/Assignment)") Type = input(">>>") #determines what type of task it is and puts it in the right dictionary #BLOCK 2:2 #Used to calculate time left to finish assignment DayLeft = 0 if ThisMonth > TimeMonth: TimeMonth = TimeMonth + 12 if ThisMonth == ( 1 or 3 or 5 or 7 or 8 or 10 or 12 ) and TimeDay < ThisDay: ThisMonth = ThisMonth + 1 DayLeft = DayLeft + ( 31 - ThisDay ) elif ThisMonth == 1 or 3 or 5 or 7 or 8 or 10 or 12: ThisMonth = ThisMonth + 1 DayLeft = DayLeft + ( TimeDay - ThisDay ) #BLOCK 2:3 while ThisMonth < TimeMonth: if ThisMonth == 1 or 3 or 5 or 7 or 8 or 10 or 12: ThisMonth = ThisMonth + 1 DayLeft = DayLeft + 31 elif ThisMonth == 4 or 6 or 9 or 11 or 16 or 18 or 21 or 23: ThisMonth = ThisMonth + 1 DayLeft = DayLeft + 30 elif ThisMonth== 2 or 14: ThisMonth = ThisMonth + 1 DayLeft = DayLeft + 28 #BLOCK 2:4 if Type == Lesson: Rating = Time + Imp + Want Lesson.update = {DayLeft:(Name,Desc,Rating,TimeDay,TimeMonth)} if Type == Exercises: Rating = Time + Imp + Want Exercises.update = {DayLeft:(Name,Desc,Rating,TimeDay,TimeMonth)} if Type == Assignment: Rating = Time + Imp + Want Assignment.update = {DayLeft:(Name,Desc,Rating,TimeDay,TimeMonth)} #BLOCK 5:1 if Input == 'quit': print ("are you sure you want to quit?") Input = input('>>>') if Input == 'Yes' or 'yes' or 'y' or 'Y' or 'Yse' or 'yse': #BLOCK 5:2 #Save an output dictionaries with open('LessonOut.txt', 'w') as f1: json.dump(Lesson, f1) with open('ExercisesOut.txt', 'w') as f1: json.dump(Exercises, f1) with open('AssignmentOut.txt', 'w') as f1: json.dump(Assignment, f1) break break break
-39369556 0 Separate two images joined using UIGraphicsBeginImageContext I can merge two images using UIGraphicsBeginImageContext.
Can I do a reverse process? Means can I have those two separate images back?
Thanks
-14509311 0This gets the job done visually:
<Grid> <Image Source="{Binding MyImage}" /> <Image Source="{Binding MyWatermark}" /> </Grid> Same answer as here: http://stackoverflow.com/a/14509282/265706
-27818822 0 Linux environments. make the machine slowThis may seem weird, but is there a way to make the machine(linux/unix flavours - preferably RHEL). I need to control the speed of the machine to make sure the code works on very slow systems and identify the right break point (in terms of time)..
One way i can do it is to run some heavy background process. Any other smarter way?
Thanks
-21055361 0It sounds like a path issue. Try env|grep PATH in bash to see what bash sees. Add paths as needed. You can also try running with giving full path in command line or alternatively, adding extension to the filename (i.e. zftool.php instead of zftool).
Whenever I try to run my App, it installs two app in the emulator/device. I only want to Install my Main Activity, but the Splash Activity installs also. I know the problem is in the Manifest. Can anyone help me please? Here is my code:
<activity android:name="com.android.upcurrents.launcher.SplashActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.android.upcurrents.MainActivity" android:label="@string/app_name" />
-18088595 0 I think the main confusion here is the notion that that main is the first and last thing that happens in C++ program. Whilst it is [1] the first part of YOUR program, there is usually some code in the application that sets up a few things, parses command line arguments, opening/initialization of standard I/O (cin, cout, etc) and other such things, which happen BEFORE main is called. And main is essentially just another function, called by the C++ runtime functionality that does that "fix things up before main".
So, when main returns, it goes back to the code that called it, which then cleans up the things that need cleaning up (closing standard I/O channels, and many other such things), before actually finishing up by calling some OS function to "terminate this process". As part of this "terminate this process" functionality is (in most OS's) a way to signal "success or failure" to the OS, so that some other process monitoring the application can determine "if all is well or not". This is where, eventually, the 0 (or 1 if you use return 1; in main) ends up.
[1] If there are static objects with constructors that are part of the user's code, then these will be performed before any code in main [or at least, before any code in main that belongs to the user's application] is executed.
You don't say precisely what you're trying to do, but I can say with a great deal of confidence you are doing it wrong. From your code, I'll guess that emailTranscript.txt contains a form letter and nameAddresses.csv contains the data to be substituted in.
The biggest error, and the one I suspect is your problem, is that -F specifies the field separator. You want -v, to set a variable.
The standard way to send navigation parameters between pages in WP8 is to use
NavigationService.Navigate(new Uri("/MainPage.xaml?text=" + textBox1.Text, UriKind.Relative)); Then check for the parameter on the OnNavigatedTo() Method on the page you have navigated to.
protected override void OnNavigatedTo(NavigationEventArgs e) { string settingsText = NavigationContext.QueryString["text"]; } For Windows Phone 8.1 you no longer navigate using a URI. The approach is to use:
this.Frame.Navigate(typeof(MainPage), textBox1.Text); Then on the loadstate for the page you are navigating to you can get the data by using:
private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e) { string text = e.NavigationParameter as string; } Hope this helps.
-27985064 0In pure Python you can do this using a dictionary in O(N) time, the only time penalty is going to be the Python loop involved:
>>> arr1 = np.array([7.2, 2.5, 3.9]) >>> arr2 = np.array([[7.2, 2.5], [3.9, 7.2]]) >>> indices = dict(np.hstack((arr1[:, None], np.arange(3)[:, None]))) >>> np.fromiter((indices[item] for item in arr2.ravel()), dtype=arr2.dtype).reshape(arr2.shape) array([[ 0., 1.], [ 2., 0.]])
-35163125 0 the issue is with the z-index of the div containing the image and the div containing the footer.
the easiest solution is to put the footer after the div with your content. The only time z-index should come into play is if you are trying to put items on top of the image for effect.
<div id="content-wrapper"> <div id="nav"> <span>NAV</span> </div> </div> <div id="footer"> <span>FOOTER</span> </div> you can easily add the footer in the container, attach at the bottom as well. see if this example helps: https://plnkr.co/edit/GDfzul2qKApw6JGhQSbb?p=preview
-2800943 0 javascript form submission usng window.onload on background windowI have a form which submits certain values to third party... I am using windows.onload(); to submit that form, but as soon as the page is loaded the focus goes to new window... Is there a way to retain focus on my window only...
-21918427 0It means if you try to serialize/deserialize more than 20 different types you will require a paid license. See the test in the source code here. In this case 20 different types are trying to be deserialized, causing a License Exception.
From you description, you should be well within the limit of the free license and not have to worry about hitting any limitations.
-4009994 0It is possible to build a version of subversion that doesn't have this problem. It seems that the problem is the apr and apr-util libraries (see Subversion, Mac OS X, and SMB).
The work around I used is to compile subversion using OS X's versions apr, apr-util & apxs libraries.
Here is how to do it:
./configure --prefix=/opt/subversion/ --with-apr=/usr/local/apr --with-apr-util=/usr/local/apr --without-berkeley-db --with-apxs=/usr/sbin/apxs
/opt/subversion, which is handy if you use svnX.sudo make install
I have successfully done this on OS X 10.5, with subversion 1.6.13.
svnX is happy with this too.
-31519773 0 parsing nested XML nodes in RubyHello I am trying get all the possible nested hierarchy key value of following XML.
I want to create HTML for each node_name with some content and i want hierarchy menu.
<?xml version="1.0" encoding="utf-8"?> <taxonomies> <taxonomy> <taxonomy_name>World</taxonomy_name> <node atlas_node_id = "355064" ethyl_content_object_id="82534" geo_id = "355064"> <node_name>Africa</node_name> <node atlas_node_id = "355611" ethyl_content_object_id="3210" geo_id = "355611"> <node_name>South Africa</node_name> <node atlas_node_id = "355612" ethyl_content_object_id="35474" geo_id = "355612"> <node_name>Cape Town</node_name> <node atlas_node_id = "355613" ethyl_content_object_id="" geo_id = "355613"> <node_name>Table Mountain National Park</node_name> </node> </node> <node atlas_node_id = "355614" ethyl_content_object_id="" geo_id = "355614"> <node_name>Free State</node_name> <node atlas_node_id = "355615" ethyl_content_object_id="1000550692" geo_id = "355615"> <node_name>Bloemfontein</node_name> </node> </node> <node atlas_node_id = "355616" ethyl_content_object_id="" geo_id = "355616"> <node_name>Gauteng</node_name> <node atlas_node_id = "355617" ethyl_content_object_id="37710" geo_id = "355617"> <node_name>Johannesburg</node_name> </node> <node atlas_node_id = "355618" ethyl_content_object_id="1000548256" geo_id = "355618"> <node_name>Pretoria</node_name> </node> </node> <node atlas_node_id = "355619" ethyl_content_object_id="" geo_id = "355619"> <node_name>KwaZulu-Natal</node_name> <node atlas_node_id = "355620" ethyl_content_object_id="43725" geo_id = "355620"> <node_name>Durban</node_name> </node> <node atlas_node_id = "355621" ethyl_content_object_id="1000576780" geo_id = "355621"> <node_name>Pietermaritzburg</node_name> </node> </node> <node atlas_node_id = "355622" ethyl_content_object_id="" geo_id = "355622"> <node_name>Mpumalanga</node_name> <node atlas_node_id = "355623" ethyl_content_object_id="67561" geo_id = "355623"> <node_name>Kruger National Park</node_name> </node> </node> <node atlas_node_id = "355624" ethyl_content_object_id="" geo_id = "355624"> <node_name>The Drakensberg</node_name> <node atlas_node_id = "355625" ethyl_content_object_id="" geo_id = "355625"> <node_name>Royal Natal National Park</node_name> </node> </node> <node atlas_node_id = "355626" ethyl_content_object_id="" geo_id = "355626"> <node_name>The Garden Route</node_name> <node atlas_node_id = "355627" ethyl_content_object_id="" geo_id = "355627"> <node_name>Oudtshoorn</node_name> </node> <node atlas_node_id = "355628" ethyl_content_object_id="" geo_id = "355628"> <node_name>Tsitsikamma Coastal National Park</node_name> </node> </node> </node> <node atlas_node_id = "355629" ethyl_content_object_id="3263" geo_id = "355629"> <node_name>Sudan</node_name> <node atlas_node_id = "355630" ethyl_content_object_id="" geo_id = "355630"> <node_name>Eastern Sudan</node_name> <node atlas_node_id = "355631" ethyl_content_object_id="" geo_id = "355631"> <node_name>Port Sudan</node_name> </node> </node> <node atlas_node_id = "355632" ethyl_content_object_id="" geo_id = "355632"> <node_name>Khartoum</node_name> </node> </node> <node atlas_node_id = "355633" ethyl_content_object_id="3272" geo_id = "355633"> <node_name>Swaziland</node_name> </node> </node> </taxonomy> Here what i tried:
@block = doc.xpath("taxonomies/taxonomy/node/node") @chld_name = @block.map do |node| node.children.map{|n| [n.name,n.text.strip] if n.elem? }.compact end.compact #p @chld_name def parse(element) children = element.children.reject{|e| e.is_a?(Nokogiri::XML::Text) && e.text =~ /^\s*$/} if children.count == 1 && children[0].is_a?(Nokogiri::XML::Text) children[0].text #p children else data = Hash.new children.each do |child| #p child data[child.name] = parse(child) end data end end campaigns = doc.xpath('/taxonomies/taxonomy/node/node').map{ |c| parse(c) } p campaigns How can i do this? i tried many codes but no luck :(
-25845536 0 Trait to check if some specialization of template class is base class of specific classThere is std::is_base_of in modern STL. It allow us to determine whether the second parameter is derived from first parameter or if they are the same classes both or, otherwise, to determine is there no such relation between them.
Is it possible to determine whether the one class is derived from some concrete template class without distinction of which concrete actual parameters involved to its specialization?
Say, we have;
template< typename ...types > struct B {}; And
template< typename ...types > struct D : B< types... > {}; Is it possible to define a type trait:
template< typename T > is_derived_from_B; Such that it is derived from std::true_type when T is any specialization of D and derived from std::false_type if T is not derived from any specialization of B?
You already got it, you just needed to create the container for the output (the numnights element).
Anyway the code is a little bit cleaner in this way:
$(document).ready(function(){ $(".daypicker").on('change', function(){calculateNights();}); }); function calculateNights() { var arrivalday = $("#arrivalday").val(); var departureday = $('#departureday').val(); var numberNights = departureday - arrivalday; numberNights = (numberNights < 1) ? numberNights + 7 : numberNights; $("#numNights").html(numberNights); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select required="required" class="daypicker" id="arrivalday" name="arrivalday"> <option></option> <option value="1">Monday</option> <option value="2">Tuesday</option> <option value="3">Wednesday</option> <option value="4">Thursday</option> <option value="5">Friday</option> <option value="6">Saturday</option> <option value="7">Sunday</option> </select> <select required="required" class="daypicker" id="departureday" name="departureday"> <option></option> <option value="1">Monday</option> <option value="2">Tuesday</option> <option value="3">Wednesday</option> <option value="4">Thursday</option> <option value="5">Friday</option> <option value="6">Saturday</option> <option value="7">Sunday</option> </select> <hr> <div id="numNights"></div> Hope it helps!
-12114425 0 SQL - use variable as column in SELECT statement and WHERE clauseI'm trying to pull the students that are tardy for the previous period from our attendance database (SQL Server 2008). The period attendance is stored in ATT.A1, ATT.A2 ... ATT.A7. I want to schedule a job to run each hour, starting at 9am, and pull the tardy students, but I can't figure out the code.
Here's my code (pseudo-code):
Declare @Period varchar(6) Set @Period = 'att.a' + Cast((DATENAME(hour, GETDATE()) - 8) as varchar(1)) Select SC, SN, DT, @Period as Period, ATT.A1 From ATT Where SC = '9' and @Period = 'T' and DT = DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0) When I use this, I get no results. If I remove @Period = 'T' from the Where clause, I get the following:
9 5177 2012-08-24 00:00:00.000 att.a1 T 9 5211 2012-08-24 00:00:00.000 att.a1 9 5225 2012-08-24 00:00:00.000 att.a1 T 9 5229 2012-08-24 00:00:00.000 att.a1 T 9 5235 2012-08-24 00:00:00.000 att.a1 V 9 5242 2012-08-24 00:00:00.000 att.a1 T 9 5268 2012-08-24 00:00:00.000 att.a1 I know that when I use @Period in the SELECT statement and WHERE clause it's using the literal string value of @Period, but I need it to use the value of @Period as Table.Column.
So, at 9:00 it will select from ATT.A1, 10:00 from ATT.A2 ... 15:00 from ATT.A7 and each time compare whether ATT.A# = 'T'
I hope that's clear.
Thanks, Anthony
-35184881 0 Default landing page for an area independent of a default controller?I have an MVC5 website with a few areas in it. Each area has its own set of controllers and obviously every controller has a default Index.cshtml as landing page. So far so good.
But how do I go about implementing a landing page for an Area? I don't think there can be a landing page for an area independent of the controllers, so perhaps I would need to use sort of an area Home controller that would volunteer a landing page.
The thing is that I want an URL like this to work:
http://www.domain.exe/AreaN/ currently that does not work unless I make it like this:
http//www.domain.exe/AreaN/Controller/ at this point my Area registration route looks like this
context.MapRoute( "AreaN_default", "AreaN/{controller}/{action}/{id}", new { action = "Index", id = UrlParameter.Optional }, new string[] { "Namespace" } );
-11829740 0 You can use one of the libraries which allow you to create and manipulate Excel files, like EPPlus (open source) or Aspose (commercial). I have a positive experience with the latter.
-35065421 0 Evaluate all formulas in a Workbook objectI want to evaluate all formulas in a Workbook object. I know there are XSSFFormulaEvaluator and HSSFFormulaEvaluator for evaluating formulas in XSSFWorkbook and HSSFWorkbook. But the workbook object I have belongs to Workbook class.
I can use something like this,
XSSFFormulaEvaluator.evaluateAllFormulaCells((XSSFWorkbook) workbook); Is it ok to use this evaluator? Does it have any side effects to type-casting Workbook to XSSFWorkbook?
-20021366 0 Regex - matching a multiline block by noting the absence of a string and then inserting itWhat a mouthful of a subject.
So in essence I have a pattern I need to find in a file based on that pattern missing something.
For example what I HAVE is:
Huge amounts of preceding code... someHeader { someInfo = "blah blah blah"; } Huge amounts of ending code... What I need to do is make it look like this:
someHeader { someDescription = "Excellent information found here!"; someInfo = "blah blah blah"; } Huge amounts of ending code... The bottom line: I need to find all instances of the "someHeader" block that do not have a "someDescription" and insert it. "someInfo" will not always be there either so I really need to find every instance of "someheader\r\t\t{\r\t\t\t!someDescription" and replace it with "someheader\r\t\t{\r\t\t\tsomeDescription = "Excellent information found here!";\r"
I really am at a loss and have been banging on this for about a day. I have attempted sed, awk, perl and am dorking around with c# right now.
-19308956 0Thank you for your assistance. After many hours, I figured I had to use setTitle().
-38146534 0If it is only TotalVoteScore that you don't want to have to re-implement, then this is the way to go:
public interface IVotable { int TotalUpvotes { get; } int TotalDownvotes { get; } int TotalVoteScore { get; } } public abstract class VotableBase : IVotable { public abstract int TotalUpvotes { get; protected set; } public abstract int TotalDownvotes { get; protected set; } public virtual int TotalVoteScore { get { return TotalUpvotes - TotalDownvotes + 1 ; } } } public class Comment : VotableBase { public override int TotalUpvotes { get; protected set; } public override int TotalDownvotes { get; protected set; } }
-20918211 0 function mom_get_first_image() { global $post; if(preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches)) $first_img = $matches[1][0]; else $first_img = "images/logo.png"; return $first_img; }
-22447369 0 Navigation Controller to View Controller Programmatically Not Working IOS7 Hi in my application i have navigation controller with registration and I'm doing the validation for my registration form if user enter a invalid data in the registration form it should not move to the next view controller and if user give the right data it should move to the next view controller but its not working.
- (IBAction)reg:(id)sender { if ([self validateEmail:[email text]]== 1 && [self phonevalidate:[phone text]]== 1 && [name.text length] <= 25 && [city.text length] <= 25 ) { pollpoliticalViewController *pollVC = [[UIStoryboard storyboardWithName:@"Main.storyboard" bundle:nil] instantiateViewControllerWithIdentifier:@"PollPoliticalVCID"]; [self.navigationController pushViewController:pollVC animated:YES]; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"Thanks For The Registration" delegate:self cancelButtonTitle:@"ok" otherButtonTitles: nil]; [alert show]; [alert release]; }else{ UIAlertView *alert1 = [[UIAlertView alloc]initWithTitle:@"Message" message:@"you entered worng correct" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil, nil]; [alert1 show]; [alert1 release]; } } I used this above code for the navigating to view controller form the navigation controller programmatically but its giving error like.
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Could not find a storyboard named 'Main.storyboard'
But my storyboard name is main.storyboard i don't know why its giving error like this i have tried to by chaining the storyboard name but what ever i change the its giving the same error for all please tell me how to resolve this one.
Thanks.
-25935565 0 How do I change security for an existing named pipe?I'm using Hyper V on Windows 8 and would like to be able to communicate with the virtual serial port through a named pipe. I give the pipe a name of choice and it works well communicating with the virtual os (XP, in my case) serial port, but only under the Admin user due to PipeSecurity settings.
Now I would like to be able to give full control for everyone on a named pipe created by Hyper-V. Programmatically or maybe with some Hyper V setting. I need to be able to communicate with the virtual os as a regular User.
I know how to set a certain security on a named pipe that I create myself using NamedPipeServerStream together with a PipeSecurity object. I'm mainly using C#, but I see that there are C++ API:s like SetSecurityInfo. But these requires a handle to the existing pipe.
In pseudo code I would like to do something like:
SetSecurityInfo("mypipe", new PipeAccessRule("Everyone", PipeAccessRights.FullControl, AccessControlType.Allow));
Anyone know how to do this? (C++ or preferrably C#)
-33350116 0I thank you all for the input. I was able to fix my errors. I re-iterate through each character and strip the punctuation and i kept creating new lists to add repeated words then keep a single occurrence. The response that I have seem to work but I was not introduced to the higher order programming as yet.
Here is the modified code:
def repeatWords(filename_1, filename_2): infile_1=open(filename_1,'r') content_1=infile_1.read() infile_1.close() import string new_content="" for char in content_1: new_content+=char.strip(string.punctuation) new_content=new_content.lower() new_content=new_content.split() repeated_list=[] for word in new_content: if new_content.count(word)>1: repeated_list.append(word) new_repeat_list=[] for item in repeated_list: while item not in new_repeat_list: new_repeat_list.append(item) outfile=open(filename_2,'w') for repeat in new_repeat_list: outfile.write(repeat) outfile.write('\n') outfile.close() infile_2=open(filename_2,'r') content_2=infile_2.read() infile_2.close() return content_2 inF = 'catInTheHat.txt' outF = 'catRepWords.txt' print(repeatWords(inF, outF))
-2432257 0 Visual SourceSafe 2005 includes support for access over HTTP:
Remote Internet Access. This release of Visual SourceSafe introduces a new SourceSafe Internet plug-in for Visual Studio source control. The plug-in and its associated Web service enable remote Internet access to Visual SourceSafe databases over HTTP or HTTPS. The SourceSafe Internet plug-in supports the basic operations of database open, database add, check-in, checkout, and get, but does not provide rename, delete, get by time or by label, history, labeling, or share/branch functions. This plug-in is particularly helpful when you need to access your Visual SourceSafe databases when you are on the road.
Articles on setting it up seem to be scarce: Visual SourceSafe 2005 Internet Provider.
Also see:
But given that Visual SourceSafe 2005 will be retired from mainstream support on 12 April 2011 (with extended support ending on 12 April 2016), you might be better off going with Subversion (or similiar).
-17423368 0The element name is derived from the accessibility attribute of the underlying view. If an identifier attribute string is specified, that string is used as the name; otherwise, the label attribute string is used as the name. Contrast with the label method.
Don't use accessibility label to identify elements, use accessibility identifier.
In interface builder, the identifier can be set using runtime attributes:
open Identity Inspector - User Defined Runtime Attributes:
Key Path: accessibilityIdentifier Type: String Value: <your identifier>
-10589543 0 I think what you're after is a scroll view with paging enabled to be the main view that contains subviews for each of your photos. With paging enabled (the default value for this boolean property is NO), the view will always "snap" to a multiple of its bounds, so the user is always either on one section of the scroll view or another (like in Photos, or on the Home screen).
You can set the pagingEnabled property of the UIScrollView to be true to gain this effect. You will then always have multiples of the bounds of the UIScrollView shown at a time (which you could fill with a view for a photo, such as a UIImageView).
Adding a space to the end of a string is as simple as just using +:
string = 'a' new_string = string + ' ' So you just need to iterate each item in your list and append the space:
for string in sliced: print string + ' ' So could just create a new list with a simple list comprehension
new_sliced = [slice + ' ' for slice in sliced] Or alternatively, if you want to change the sliced list in place you could use the enumerate builtin to get the index of each element of your list
for i, slice in enumerate(sliced): sliced[i] = slice + ' '
-20814433 0 strtr($str, ['<' => '', '.' => '']); This will probably outperform anything else, because it doesn't require you to iterate over anything in PHP.
-17891770 0Resharper allows annotations to guide its magic. They are usually implemented by applying an attribute, though it uses external annotation files for BCL classes. You can use them in your own code. I think they are very underused.
There is an example of exactly your use case. Simply, apply [AspMvcAction] and [AspMvcController] to the appropriate parameters.
I'ts much better to use:
$(document).on('change','#elemnt',function(){ //do something here }); So there's no need to call BindDynamicEvents(); every time a new row is added.
I am new to wtforms, so I`ll really appreciate any help.
I need to display books names and near each put "Delete" button. I`ve read wtforms crash course but I have no idea how to solve my problem with it.
So I decided to do it other way - my best idea is to render to template a dict with id and name and on submit return id, but I still can`t do it. Code examples are below.
It`s view.py
@application.route('/delete', methods=['GET', 'POST']) def delete(): books_lib = mydatabase.get_all_books() form = DeleteForm(request.form) if request.method == 'POST': delete_id = form.id.data mydatabase.del_book(delete_id) return render_template('delete.html', form = form, books_lib = books_lib) return render_template('delete.html', form = form, books_lib = books_lib) It`s template
<!DOCTYPE html> <html> <body> <h2>book to delete</h2> <form action="/delete" name="delete" method="POST"> {% if books_lib %} {% for id, book in books_lib.items() %} <p>{{book}}:<input type="submit" value="Delete" id="{{id}}"> {% endfor%} {% endif %} </form> </body> </html> It`s form
class DeleteForm(Form): book = TextField("Book name", [validators.Length(min=2, max=25)]) id = HiddenField("id")
-18981964 0 cannot insert null value into the table Orders i am having a problem regarding inserting records to my database, the error says: "Cannot insert the value NULL into column 'OrderNo', table 'Receipt.dbo.Orders'; column does not allow nulls. Insert Fails. then the statement has been terminated", but when i checked my codes, i cannot seem to find any error. Can somebody help me? Thank you in advance:
Here is my set of codes:
-for save sales order-
private void SaveSalesOrder(string status) { int nOrder = 0; CloseConnection(); OpenConnection(); trnOrder = cn.BeginTransaction(); SqlCommand cmdInsert = new SqlCommand(); try { cmdInsert.Connection = cn; cmdInsert.Transaction = trnOrder; cmdInsert.CommandType = CommandType.Text; cmdInsert.CommandText = "INSERT INTO Orders " + "(OrderDate, CustomerNo, CustomerName, CustomerAddress, PurchaseOrderNo, AgentName, Status) " + "VALUES ('" + dtpOrderDate.Value.Date.ToString() + "', '" + txtCustomerNo.Text + "', '" + txtCustomerName.Text + "', '" + txtCustomerAddress.Text + "', '" + txtPONo.Text + "', '" + cboAgentName.Text + "', '" + status + "'); " + "SELECT TOP 1 OrderNo FROM Orders " + "ORDER BY OrderNo DESC;"; nOrder = Convert.ToInt16(cmdInsert.ExecuteScalar().ToString()); for (int nRow = 0; nRow <= dsDetail.Tables["OrderDetails"].Rows.Count - 1; nRow++) { double dQuantity = Convert.ToDouble(dsDetail.Tables["OrderDetails"]. Rows[nRow]["Quantity"].ToString()); string strUnit = dsDetail.Tables["OrderDetails"]. Rows[nRow]["Unit"].ToString(); int nProductNo = Convert.ToInt16(dsDetail.Tables["OrderDetails"]. Rows[nRow]["ProductNo"].ToString()); string strProductName = dsDetail.Tables["OrderDetails"]. Rows[nRow]["ProductName"].ToString(); string strProductSize = dsDetail.Tables["OrderDetails"]. Rows[nRow]["ProductSize"].ToString(); string strPackagingInside = dsDetail.Tables["OrderDetails"]. Rows[nRow]["PackagingInside"].ToString(); double dSellingDiscount = Convert.ToDouble(dsDetail.Tables["OrderDetails"]. Rows[nRow]["SellingDiscount"].ToString()); double dSellingPrice = Convert.ToDouble(dsDetail.Tables["OrderDetails"]. Rows[nRow]["SellingPrice"].ToString()); double nAmount = Convert.ToDouble(dsDetail.Tables["OrderDetails"]. Rows[nRow]["Amount"].ToString()); SqlCommand cmdInsertDetail = new SqlCommand(); cmdInsertDetail.Connection = cn; cmdInsertDetail.Transaction = trnOrder; cmdInsertDetail.CommandType = CommandType.Text; cmdInsertDetail.CommandText = "INSERT INTO OrderDetails " + "(OrderNo, PackagingOutside, Quantity, Unit, ProductNo, ProductName, " + "ProductSize, PackagingInside, SellingDiscount, SellingPrice, Amount) " + "VALUES ('" + nOrder + "', '" + dPackagingOutside + "', '" + dQuantity + "', '" + strUnit + "', '" + nProductNo + "', '" + strProductName + "', '" + strProductSize + "', '" + strPackagingInside + "', '" + dSellingDiscount + "', '" + dSellingPrice + "', '" + nAmount + "')"; cmdInsertDetail.ExecuteNonQuery(); } trnOrder.Commit(); if (status == "OK") { MessageBox.Show("Transaction has been saved!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("Transaction has been voided!", "Void Transaction", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (SqlException ex) { trnOrder.Rollback(); MessageBox.Show(ex.Message); } finally { cn.Close(); } } private void btnSave_Click(object sender, EventArgs e) { if (txtCustomerNo.Text == "") { MessageBox.Show("Please select a customer first.", "Empty", MessageBoxButtons.OK, MessageBoxIcon.Error); btnSearchCustomer.Focus(); return; } if (grdDetails.Rows.Count < 1) { MessageBox.Show("Please select a product first.", "Empty", MessageBoxButtons.OK, MessageBoxIcon.Error); btnProductSearch.Focus(); return; } SaveSalesOrder("OK"); groupCustomer(false); groupProduct(false); CSalesInv.EnableDisable(this, false); CloseConnection(); InitializeOrder(); lblTotal.Text = ""; }
-19113717 1 playing midi sounds through pygame on raspberrypi I'm trying to play midi sounds using pygame on my raspberrypi (without external midi devices), however I can't get anything to work.
I have tried many examples: The following gives.
import pygame import time import pygame.midi pygame.midi.init() player= pygame.midi.Output(0) player.set_instrument(48,1) major=[0,4,7,12] def go(note): player.note_on(note, 127,1) time.sleep(1) player.note_off(note,127,1) def arp(base,ints): for n in ints: go(base+n) def chord(base, ints): player.note_on(base,127,1) player.note_on(base+ints[1],127,1) player.note_on(base+ints[2],127,1) player.note_on(base+ints[3],127,1) time.sleep(1) player.note_off(base,127,1) player.note_off(base+ints[1],127,1) player.note_off(base+ints[2],127,1) player.note_off(base+ints[3],127,1) def end(): pygame.quit() Gives the following error
PortMidi call failed... PortMidi: 'Bad pointer' type ENTER... The next example (like most of the others) gives a 'Device id invalid, out of range.' error:
import pygame import pygame.midi from time import sleep instrument = 0 note = 74 volume = 127 pygame.init() pygame.midi.init() for id in range(pygame.midi.get_count()): print pygame.midi.get_device_info(id) port = 2 midiOutput = pygame.midi.Output(port, 1) midiOutput.set_instrument(instrument) for note in range(0,127): midiOutput.note_on(note,volume) sleep(.25) midiOutput.note_off(note,volume) del midiOutput pygame.midi.quit() Gives this error
('ALSA', 'Midi Through Port-0', 0, 1, 0) ('ALSA', 'Midi Through Port-0', 1, 0, 0) Traceback (most recent call last): File "midi-test2.py", line 16, in <module> midiOutput = pygame.midi.Output(port, 1) File "/usr/lib/python2.7/dist-packages/pygame/midi.py", line 414, in __init__ raise MidiException("Device id invalid, out of range.") pygame.midi.MidiException: 'Device id invalid, out of range.' I haven't found any guides to setting up a RaspberryPi to play midi sounds, any suggestions?
-33554871 0 How to use/declare an unsigned Integer value in VHDL?I'm trying to design a basic Vending machine on a Altera DE1-SoC Board. My question comes from trying to code the State Machine that will control the vending process. How do you track the $ value being added jumping between states? I think the code I'm trying to implement is written in a higher level language format and is not being able to be compiled in VHDL. Any ideas?
I'm getting this error (right after the Architecture declaration):
Error (10482): VHDL error at State.vhd(21): object "unsignedInteger" is used but not declared
library ieee; use ieee.std_logic_1164.all; use IEEE.numeric_std.all; use IEEE.std_logic_unsigned.all; entity MessageState is Port( Reset :in std_logic; -- reset to a safe state ----------------------------------------------------------------------------------- MyStateOut :out std_logic_vector( 1 downto 0 ); -- drive the current state to display or LEDs OutputCode :out std_logic_vector( 6 downto 0 ) -- to the display driver ); end; architecture Vending_FSM of MessageState is signal Count: unsignedInteger(8 downto 0); -- we define a data type to represent the states. Use descriptive names -- add more lines for more states. Change the size of MyState as needed subtype MyState is std_logic_vector(2 downto 0); constant Idle :MyState := "000"; constant NickelState :MyState := "001"; constant DimeState :MyState := "010"; constant QuarterState :MyState := "011"; constant Dispense :MyState := "100"; signal state, next_state: MyState; begin MyStateOut <= state; -- make state visible. MyNextState: process(state, next_state) begin -- add all signals read or tested in this process case state is when Idle => if ( KEY(0) = '1') then next_state <= NickelState; elsif ( KEY(1) = '1') then next_state <= DimeState; elsif ( KEY(2) = '1') then next_state <= QuarterState; else next_state <= Idle; -- default action Count <= (others => '0'); end if;
-9063042 0 I already figured it out! Here's my solution:
Works fine on me. Thanks for those who help me in solving this one.
-10133796 0You can override -[NSView viewWillMoveToSuperview:] in a custom NSView subclass. This is simply a means for your class to be notified when its position in the view hierarchy is about to change. It doesn't have some deeper meaning other than what its name implies, but you can, of course, harness it to serve various purposes. It's not a method on a delegate or on the view controller, but you can implement such delegation yourself if you want.
Also, if your code is moving views around the view hierarchy, it can directly do whatever it wants immediately beforehand, which is also roughly when such a method would be called.
-33098343 0What about set -v?
-vPrint shell input lines as they are read.
The output seems to meet your expectation.
$ set -v $ ./command1 > output1 ./command1 > output1 sh: ./command1: No such file or directory $ ./command2 arg1 arg2 > output2 ./command2 arg1 arg2 > output2 sh: ./command2: No such file or directory $ ./command3 | tee output3 ./command3 | tee output3 sh: ./command3: No such file or directory
-25935287 0 Acts as taggable not migrating because I have another tags model I'm trying to migrate acts_as_taggable to install it, but, since I already have a table called "tags", for photo tagging, it will collapse and wont migrate.
How can I change the name for the table acts_as_table creates? Is this possible?
Thanks a lot!
-18356882 0Call merge(), and use its returned value: it's the attached entity containing the values found in the detached entity passed as argument:
Foo modifiedAttachedFoo = session.merge(modifiedDetachedFoo); modifiedAttachedFoo.getLazyCollection().size(); // no problem: the entity is attached
-20310714 0 I did some poking around and it didn't seem like there was an easy way of doing this. I think to do it effectively you would probably need your own C functions which could provide a distance from one tsvector to another (then you could use KNN searches).
Either way there is not a very easy way to do this and it is likely a significant amount of work, but it seems like it should be a generally applicable problem so the general community might be interested in a solution.
Note this is not as trivial as it sounds. Suppose I write a book about Albert Lord's the Singer of Tales and his emphasis on poetic formulas. Suppose I call it "Albert Lord and the Ring of Words." This would create a tsvector of Albert:1 Lord:2 Ring:5 Words:7, The Lord of the Rings is Lord:2 Ring:5 which would create a very false sense of similarity. If you have any categorization involved, you would want to leverage that as well.
The problems is to find the count of numbers between A and B (inclusive) that have sum of digits equal to S.
Also print the smallest such number between A and B (inclusive).
Input:
Single line consisting of A,B,S.
Output:
Two lines.
In first line the number of integers between A and B having sum of digits equal to S.
In second line the smallest such number between A and B.
Constraints:
1 <= A <= B < 10^15
1 <= S <= 135
Source: Hacker Earth
My solution works for only 30 pc of their inputs. What could be the best possible solution to this?
The algorithm I am using now computes the sum of the smallest digit and then upon every change of the tens digit computes the sum again. Below is the solution in Python:
def sum(n): if (n<10):return n return n%10 + sum(n/10) stri = raw_input() min = 99999 stri = stri.split(" ") a= long (stri[0]) b= long (stri[1]) s= long (stri[2]) count= 0 su = sum(a) while a<=b : if (a % 10 == 0 ): su = sum(a) print a if ( s == su): count+=1 if (a<= min): min=a a+=1 su+=1 print count print min
-16133289 0 Try updating the components code in your appController to add the authenticate values to the Auth array like this:
public $components = array( 'Session', 'DebugKit.Toolbar', 'Auth' => array( 'allow' => array('login','logout'), 'loginAction' => array('controller' => 'users', 'action' => 'login'), 'loginRedirect' => array('controller' => 'dashboard', 'action' => 'index'), 'authorize' => 'Controller', 'authenticate' => array( 'Form' => array( 'fields' => array('username' => 'email') ) ) ) );
-12652560 0 - (BOOL) textFieldShouldReturn:(UITextField *)textField { //resign the keypad and check if 10 numeric digits entered... NSRange range; range.length = 3; range.location = 3; textField.text = [NSString stringWithFormat:@"(%@) %@-%@", [textField.text substringToIndex:3], [textField.text substringWithRange:range], [textField.text substringFromIndex:6]; }
-37074286 0 Try this if only 'ABC' an 'XYZ' types exist in the table:
SELECT number as id, MAX(CASE WHEN Type = 'ABC' THEN Date ELSE NULL END) as T1, MAX('ABC') as Type_1, MAX(CASE WHEN Type = 'XYZ' THEN Date ELSE NULL END) as T2, MAX('XYZ') as Type_2 FROM T GROUP BY Number
-13214694 0 Setting up git branches Hi I have setup git on my local machine.
So I can now fully develop locally and push my files to master origin.
but I'd like to be able to commit my files from local to a stage folder on remote, and then from there create a branch with all the files that goes to production. any ideas on how i can establish this ? I am very new to git. (just learned hot to commit, that new lol)
-6289547 0Sorry I did not replay earlier. Quickly, I'll would like to present one way of catching this for your consideration. For simplicity, I'll just concentrate on caching your outputs using Output frontend.
In you application.ini you can setup your catching as follows:
resources.cachemanager.myviewcache.frontend.name = Output resources.cachemanager.myviewcache.frontend.customFrontendNaming = false resources.cachemanager.myviewcache.frontend.options.lifetime = 7200 resources.cachemanager.myviewcache.frontend.options.caching = true resources.cachemanager.myviewcache.frontend.options.automatic_serialization = true resources.cachemanager.myviewcache.backend.name = Apc Note, that I use Apc as a backend. You may use file backend if you don't have or don't want Apc.
With this, I would cache your posts and comments separately. For example, in _posts.phtml you could do something similar to the following:
// first cache an output related to the body of your post with key being associated // with your post. if (!($this->viewCache()->start('post_' . (string) $this->object->post_id))) { echo $this->object->title; echo $this->object->text; } // now I cache an output of a comments associated with a give post if (!($this->viewCache()->start('post_comments_' . (string) $this->object->post_id))) { echo $this->partialLoop('_comments.phtml',$this->object->getComments()); } In this example, viewCache() view helper is as follows:
class My_View_Helper_ViewCache extends Zend_View_Helper_Abstract { /** * * @return Zend_Cache_Frontend_Output */ public function viewCache() { return Zend_Registry::get('outputCache'); } } Whereas I set outputCache into registry in the Bootstrap.php:
protected function _initPutChachesIntoRegistry() { $this->bootstrap('cachemanager'); $cacheManager = $this->getResource('cachemanager'); Zend_Registry::set('outputCache', $cacheManager->getCache('myviewcache')); } Notice that caches are associated with keys which in turn relate to a given post and its comments. With this, when you get a new comment, you just reset a cache related to the given post. For example, in an action, you can remove comment cache for a post with $post_id=5 as follows:
$this->view->viewCache()->remove('post_comments_' . $post_id); Hope that this will help you or at least give you some ideas how to make it.
-27946612 0Try
<Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source ="StyleTemplates.xaml"> </ResourceDictionary> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources>
-10403767 0 Other than a very short list, you should not rely on everyone having the various font families on their computers.
Instead, try out Google WebFonts. In fact, use the search box on the left to find their Garamond equivalent. Works in all browsers (including older IE!) and looks great everywhere.
EDIT
Regarding your additional question, yes, the browser will look for the fonts in the order that you specify them, so putting "Garamond" before "EB Garamond" will show Garamond if available in the user's computer.
-2281951 0Store the Thread results in a list after they were spawned and iterate the list - during iteration call join then. You still join linearly, but it should do what you want.
-31814298 0The mistake was not realising JavaScript's passing-by-reference when using objects such as Date objects.
In addition to Austin's answer, which did solve the problem by using d3 functionality, I investigated why my initial attempt by modifying the minDate and maxDate variables failed.
The problem is that when creating the variables
var minDate = dateDim.bottom(1)[0]["timestamp"]; var maxDate = dateDim.top(1)[0]["timestamp"]; I created pointers to the actual data instead of creating new objects with the same value as the minDate and maxDate objects. The line
minDate.setHours(minDate.getHours() - 1); therefore then manipulated the actual underlying data within the date dimension dateDim, which then led to the peculiar behaviour.
The obvious solution would have been to create new Date() objects like this:
var minDate = new Date(dateDim.bottom(1)[0]["timestamp"]); var maxDate = new Date(dateDim.top(1)[0]["timestamp"]);
and then do the desired manipulations:
-35859741 0 Comparing two string failing assertionminDate.setHours(minDate.getHours() - 1); maxDate.setHours(maxDate.getHours() + 1);
This is really weird, im trying to assert two strings are equal and it's failing even though it looks to be the same.
Assert.assertSame("Extra Spicy", type, "type is not extra spicy"); I get this error:
java.lang.AssertionError: type is not extra spicy expected [Extra Spicy] but found [Extra Spicy]
Expected :Extra Spicy
Actual :Extra Spicy
Everything matches, why is it failing?
-5572951 0If I understand correctly, you can hook into the Form Closing event.
So in your main form you can do something like:
Form2 form2 = new Form2(); form2.Show(); form2.FormClosing += new FormClosingEventHandler(form2_FormClosing); void form2_FormClosing(object sender, FormClosingEventArgs e) { this.Show(); }
-15867840 0 Mouse Hower on TextBlock The idea is when mouse howler above TextBlock, new Image is appear and it possible to click on it. When mouse leave the TextBlock - Image should disappear.
Meanwhile I came to this, but still unable to continue:
<Style x:Key="HoverHighlightTextStyle" TargetType="TextBlock"> <Setter Property="FontSize" Value="16"/> <Setter Property="FontWeight" Value="Normal"/> <Setter Property="Margin" Value="3,0,3,0"/> <Style.Triggers> <Trigger Property="IsMouseOver" Value="True"> </Trigger> </Style.Triggers> </Style> Expected result

Private Sub Workbook_Open() '// Disable Accelerators keys in Excel 2007-2013 Dim Ctl As CommandBarControl For Each Ctl In Application.CommandBars("&Legacy Keyboard Support").Controls Ctl.Tag = Ctl.Caption Ctl.Caption = Replace(Ctl.Caption, "&", "") Next Dim StartKeyCombination As Variant Dim KeysArray As Variant Dim Key As Variant Dim I As Long On Error Resume Next '// Shift key = "+" (plus sign) '// Ctrl key = "^" (caret) '// Alt key = "%" (percent sign '// We fill the array with this keys and the key combinations '// Shift-Ctrl, Shift- Alt, Ctrl-Alt, Shift-Ctrl-Alt For Each StartKeyCombination In Array("+", "^", "%", "+^", "+%", "^%", "+^%") KeysArray = Array("{BS}", "{BREAK}", "{CAPSLOCK}", "{CLEAR}", "{DEL}", _ "{DOWN}", "{END}", "{ENTER}", "~", "{ESC}", "{HELP}", "{HOME}", _ "{INSERT}", "{LEFT}", "{NUMLOCK}", "{PGDN}", "{PGUP}", _ "{RETURN}", "{RIGHT}", "{SCROLLLOCK}", "{TAB}", "{UP}") '// Disable the StartKeyCombination For Each Key In KeysArray Application.OnKey StartKeyCombination & Key, "" Next Key '// Disable the StartKeyCombination key(s) with every other key For I = 0 To 255 Application.OnKey StartKeyCombination & Chr$(I), "" Next I '// Disable the F1 - F15 keys in combination with the Shift, Ctrl or Alt key For I = 1 To 15 Application.OnKey StartKeyCombination & "{F" & I & "}", "" Next I Next StartKeyCombination '// Disable the F1 - F15 keys For I = 1 To 15 Application.OnKey "{F" & I & "}", "" Next I '// Disable the PGDN and PGUP keys Application.OnKey "{PGDN}", "" Application.OnKey "{PGUP}", "" End Sub Reference below links
-1134600 0Without having actually tested it, you should be able to copy the main django directory (/usr/lib/python2.6/site-packages/django for me) over into your project directory, and archive the whole thing. This will continue to keep everything importable (from django import ...), and make it so there's just one archive to extract.
Now, I wouldn't say this is a good way, but it's simple, and I think it'll work. I think.
-27981621 0 Generate Timestamp in IST Timezone javaI am trying to generate current timestamp in GMT timezone but it is still getting generated in IST as my machine is set to IST. I am using this code. Please help!!
{ String timeZone = "GMT"; Calendar gmtCalendar = Calendar.getInstance(TimeZone.getTimeZone(timeZone)); Date date = gmtCalendar.getTime(); endTime = new Timestamp(date.getTime()); String eTime = NLSUtil.getFormattedDate(AdfUtil.getClientLocale(), new java.sql.Date(endTime.getTime())); }
-34467431 0 Generally: yes, the bias weights should be updated and included in training just as any other weight in the NN (also in backpropagation).
In the example you've posted, the bias b1 is added to both neurons the hidden layer, and bias b2 to both neutrons in the output layer
Hidden layer: h1 = i1*w1 + i2*w2 + 1*b1 h2 = i1*w3 + i2*w4 + 1*b1 Output layer: o1 = h1*w5 + h2*w6 + 1*b2 o2 = i2*w7 + h2*w8 + 1*b2 With initial, and in this example, fixed, biases
b1 = 0.35 b2 = 0.60 This means that the biases for hidden neutrons is always exactly 0.35, and for output neutrons exactly 0.60. This, however, is not usual practice, as you want to train your NN to find "good" biases just as much you want it to train to find good weights.
Note also, in the comments of the link you provided, that another user has asked why biases are not changed, and the author has replied, quote:
"Hey, in the tutorials I went through they didn’t update the bias which is why I didn’t include it here."
This lack of a specific "why" possibly implies that the author of this example/tutorial is, however well-versed, no expert at the subject of NN, so you shouldn't out to much weight (no pun intended...) into the fast that the biases are not changed in this specific example.
If you really want to dig into a sound and thorough covering of NN in the context of back propagation, I would rather recommend you Michael Nielsen excellent book on NN and deep learning, specifically for this subject, Chapter 2. Note that the bias weights, here, are treated just as weights for neuron-neuron data transfer.
Michael is a Google Researcher with numerous publicised articles in the subject of advanced NN and deep learning.
-14598137 0At the heart of backpropagation is an expression for the partial derivative ∂C/∂w of the cost function C with respect to any weight w (or bias b) in the network. The expression tells us how quickly the cost changes when we change the weights and biases.
The question is a little bit poor specified.
order the result in asc or desc depending upon a column value.
A column takes many values (as there are multiple rows).
Now, order by clause use an expression and order rows upon it. That expression should be morphotropic(;))
So, assuming stardard oracle's employee schema, managers are:
select * from emp e where exists (select emp_id from emp where e.id=emp.mgr_id) An workaround query may be:
Select e.id, e.name, e.birth_date, case when (select count(*) from emp e where exists (select emp_id from emp where e.id=emp.mgr_id) ) --existence of manager > 0 then birth_date - to_date('1-Jan-1000','dd-mon-yyyy') else to_date('1-Jan-1000','dd-mon-yyyy') - birth_date end as tricky_expression from emp A order by 4; That exexpresion is the case; Using a constant(subquery that decides there are managers) it changes values from positive to negative, that is, change the order direction.
UPDATE: with the details in the comments:
select id, name, birth_date emp_type from ( Select id, name, birth_date, emp_type, case when cnt_mgr > 0 then birth_date - to_date('1-Jan-1000','dd-mon-yyyy') else to_date('1-Jan-1000','dd-mon-yyyy') - birth_date end as tricky_expression from( Select e.id, e.name, e.birth_date, emp_type, count(case when emp_type='M' then 1 else 0 end) over() as mgr_count from emp A where your_conditions ) order by tricky_expression ) where rownum=1;
-17048090 0 No the richtext component does not provide such functionality. But it is possible to create ordered and unordered lists and to intend or outend the single list items.
-37486328 0 SQL query to rows to columnsI have a table like this
CREATE TABLE #CurrencyRate ( [Base] nvarchar(10), [Quote] nvarchar(10), [Amount] nvarchar(10) ) and it has data like this
Base Quote Amount --------------------- R1C1 R1C2 R1C3 R2C1 R2C2 R2C3 Note: R1C1 => Row 1, Column 1
I want output like
Row Column Attribute Value ----------------------------------------- 1 1 Base R1C1 1 2 Quote R1C2 1 3 Amount R1C3 2 1 Quote R2C1 2 2 Amount R2C2 2 3 Base R2C3 Is it possible to get output like this with some SQL?
Thanks in advance
-24083219 0Threre are other threadpools available, for example the fixed threadpool (newFixedThreadPool), which seems to behave just as the one you use, only without the sceduling.
Your code isn't compilable. Here is the reasons:
Here is the workable code:
namespace WindowsFormsApplication1 { public partial class Form1 : Form { private int flag; FileSystemWatcher watcher = new FileSystemWatcher(); public Form1() { InitializeComponent(); watcher.Path = @"C:\"; watcher.Filter = "test.txt"; watcher.Changed += watcher_Changed; watcher.EnableRaisingEvents = true; } private void SetFlag() { FileInfo info = new FileInfo("c:\\test.txt"); if (info.Length > 0) flag= 1; } private void CheckFlag() { if(flag==1) { button1.PerformClick(); } } private void button1_Click(object sender, EventArgs e) { //Code for Redirection to New Form } void watcher_Changed(object sender, FileSystemEventArgs e) { SetFlag(); CheckFlag(); } } } And now you can call method SetFlag() to set flag. And use method CheckFlag() to check flag. In this example I use FileSystemWatcher to catch all file changes and call SetFlag() and CheckFlag() inside the handler of event Changed
Instead of button1.PerformClick() you can use button1_Click(this, EventArgs.Empty)
I am creating image with php
code
$src = array ("22.jpg","33.jpg","44.jpg","55.jpg","66.jpg","77.jpg"); $imgBuf = array (); foreach ($src as $link) { switch(substr ($link,strrpos ($link,".")+1)) { case 'png': $iTmp = imagecreatefrompng($link); break; case 'gif': $iTmp = imagecreatefromgif($link); break; case 'jpeg': case 'jpg': $iTmp = imagecreatefromjpeg($link); break; } array_push ($imgBuf,$iTmp); } $iOut = imagecreatetruecolor ("35","210") ; imagecopy ($iOut,$imgBuf[0],0,0,0,0,imagesx($imgBuf[0]),imagesy($imgBuf[0])); imagedestroy ($imgBuf[0]); imagecopy ($iOut,$imgBuf[1],0,35,0,0,imagesx($imgBuf[1]),imagesy($imgBuf[1])); imagedestroy ($imgBuf[1]); imagecopy ($iOut,$imgBuf[2],0,70,0,0,imagesx($imgBuf[2]),imagesy($imgBuf[2])); imagedestroy ($imgBuf[2]); imagecopy ($iOut,$imgBuf[3],0,105,0,0,imagesx($imgBuf[3]),imagesy($imgBuf[3])); imagedestroy ($imgBuf[3]); imagecopy ($iOut,$imgBuf[4],0,140,0,0,imagesx($imgBuf[4]),imagesy($imgBuf[4])); imagedestroy ($imgBuf[4]); imagecopy ($iOut,$imgBuf[5],0,175,0,0,imagesx($imgBuf[5]),imagesy($imgBuf[5])); imagedestroy ($imgBuf[5]); imagepng($iOut); //header ( 'Content-type:image/png' ); // save the img to directory $char='0123456789'; $length=10; $max_i=strlen($char)-1; $value=''; for($j=0;$j<$length;$j++) { $value.=$char{mt_rand(0,$max_i)}; } $imageid=$value; it giving error on page like
‰PNG IHDR#ÒOuî² CIDATxœíÖ]ŒdÇUðÿ9§êÞþ˜™]ïìÇlbc‚ÀІ(@dQž @"$ƒ”<°E‚XX
Y~ E D¼€"!ÂI’;Q$£°M¼ïzw½_3ÓÓÝ÷Ö×9<ô̬óÄRê§V«Õ·»ÿU]uÏ)JÙ ‚Ì€˜7€wâÕ½«¯^»Óçþå™åfȹ-š© *6›çŸù¹÷ðêðÌ[í‰%üÈ]؆0‡8@@ÙL3¼Än‘×ãÞ«·žxôñ»×69àôú©e?ÊóÙÊx™’W+Ü”˜C1Vö4Üîowq÷zwë?ýI·u§,É~@½™@PF¼Ž'>ô»ÇýÚ‘áÊòêÒh8HëᬠŒ,eïÄ9îK ¡Lº½4ëºÙüÖ7Óä¿ø—Ø–€‡(™€b’ »øØ¹ß\K÷o¾ãÌúI&*‚lÙÁR4P£ÄEÕ‰P¢ó!Î}ë:ëEdÄ-gX_.߸òòök¯ûŸúöߣMp~1'ç($àßo½-ÿÀÛï][Z/1Ëlo‡PaÕa#¥›{4Óɘ4—\Š9í%©FË'7ÓÕñÝîƒÅ_h¹@øNþÄû}ðØ?6NsLªêü0ö¡q%ö#fÖ2²Óbð’´¨ªjS¸,¾GE.ì\x~÷ùO>ûØ x°"*¶ñ±|äÄÚ™ñʱÉv§Á4X‰¶·Óõ†S‹½€½Ž£QFècÅcŒ¡OH ˆ²ÝˤϷws›ë›'è$þûòþ:931þkû¸-Z;1Ÿv%ôÐ’c ߸&Lûaëgq:Ó>Í•àÃñ`¼:;EŠÉHBL¸ºv<š¤É€†§†Ç¿õ¥¯ŸýÉì');¾ó·7ëÜ' 9ö¥ˆH\C–Çäß¼ùæ%Ýž #µs¦áéptU–}±lST°F:£#úãÏ}ù«g?HÊ Q<÷¥=5>–»b¢M¹uV †½8»<»úûŸ{ooa€xmïÓ|üÈÚÀ›Ï}/
how i can solve this
-24745209 0First of all, I would set the interval to something like 500, then step it back to 400, 300, 200, 100, etc. until you get the desired speed you want.
Secondly, assuming Label2 is your max value and Label3 is your min value and that you want your progress bar control to simply bounce back and forth between the min and max values, I would do something like this:
Const MAX_VALUE = 100 Const MIN_VALUE = 0 Dim currentValue = 0 Dim isIncrementing = True Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick If currentValue = MAX_VALUE Then isIncrementing = False If currentValue = MIN_VALUE Then isIncrementing = True If isIncrementing Then currentValue += 1 Else currentValue -= 1 ProgressBar1.Value = currentValue ProgressBar1.Update() End Sub Since I'm assuming your Label2 and Label3 are your min/max values, I'm also assuming they should stay static and never change, which is why I don't change their values in the Tick event. If you wanted a Current Value label, that would be easy enough to add and that would be changed at the same time the ProgressBar1.Value is.
Regex has a thing called a "non capturing negative lookahead assertion" which basically says "don't match the following". It looks like this:
^people/(?!People_Search)([A-Za-z0-9\-\_]+)/?$ Whether you can use this depends on the rewrite engine you use, and the level of regex support that's included in it. I'd expect that most common rewriters support this.
FYI: There are also negative lookbehind assertions(?<!), and also postive versions of the lookahead (?=) and lookbehind (?<=) assertions.
Tutorial: http://www.regular-expressions.info/lookaround.html
-21194126 0How about this? window["yourfunctionname"]();
var FunctionName = func[before]; if (typeof(window[FunctionName]) === "function") { window[FunctionName](); } OR
function myFunc(obj) { var func = $.parseJSON(obj); if (func[before] === "myBefore") { before();} // do some stuff if (func[after] === "myAfter") { after(); } }
-13158290 0 Use this code to remove the white space:
NSString *str = @"this string contains blank spaces"; NSString *newStr = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
-38083634 0 Android sign in with Google APIs expires very early I followed these guidelines to integrate Google sign-in into my android app: https://developers.google.com/identity/sign-in/android/sign-in#start_the_sign-in_flow
When activity's onStart is called, it tries to sign-in again, if required information is cached and present on device, without any Internet connection.
The problem is that it expires at almost 5 hours. And Google APIs requires Internet connection to sign in again.
How can I increase offline persistence of sign-in information?
-6052881 0 Archiving large amounts of old data in SQL ServerPretty simple question.
I have a large 70gb database that has four of five tables that contain about 50 million rows each. These tables contain about 6 years worth of data. We are limited to amount of space in our database to 80gb, and we are going to be quickly approaching that in the next 6 months or so.
We only need to keep about two years worth of data in the live database. What is the best approach to archiving the older data WITHOUT taking the live database offline (it's 24/7 database)?
We are running SQL Server 2008 R2 Standard in a clustered environment using active-passive setup using shared storage.
Thanks.
-31631685 0You can either move/copy the Content folder under www root folder or use grunt file.js to process,combine,minify, and then copy to a folder under wwwroot. But ~/ now means wwwroot
-20727067 0I know it's so late but I had the same problem, so here's the solution below:
To create web.xml:
(Tested on Netbean 7.4 JDK 7)
-35139477 0Turns out I simply had to implement this method into the viewController that holds this tableView:
override func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? { return "This will appear in footer styling below the section." }
-39165938 0 Honestly, I find IDEA scarily good at reading my mind of what method I want to call next. And it usually just takes a couple letters for it to narrow down what I'm looking for pretty precisely.
But, I think what you may be looking for is the "Sort lookup items lexicographically" option, in the Settings window under Editor / General / Code Completion. This always sorts the list by the name, rather than by predicting a few things to put at the top.
You can read more about it and the other code completion options in the IntelliJ IDEA documentation.
-8148416 0Use a BETWEEN query like this:
SELECT department FROM table WHERE '022589893232043' BETWEEN startphoneNum AND endphoneNum;
-11736910 0 I have the answer. Apparently jQuery doesn't support the default behavior of links clicked programmatically
Creating and submitting a form works really well though (tested in Chrome 26, FF 20 and IE 8):
var form = $("<form></form>"); form.attr( { id : "newform", action : "https://google.nl", method : "GET", target : "_blank" // Open in new window/tab }); $("body").append(form); $("#newform").submit(); $("#newform").remove(); What it does:
Now you have a new tab/window loading "https://google.nl" (or any URL you want, just replace it). Unfortunately when you try to open more than one window at once this way, you get an Popup blocked messagebar when trying to open the second one (the first one is still opened).
-3451451 0 Why do people spend so much time searching for, and hacking around with, "free" toolsets when superior pay ones are available?Clarification: I'm referring to companies that pay developers, professionally. I understand why a "hobby" or "for fun" developer wouldn't want to (or couldn't afford) a fully-features pay tool, and may prefer to tinker. I'm talking about situations where a deadline is bearing down on a developer/company and development time is diverted away from the goal in pursuit of a "Free" tool to accomplish what a pay one is available to do.
I've noticed a number of Stack Overflow questions recently (they're not new, I've just recently taken notice) where people are searching for free alternatives to popular development tools for things like ALM, database comparison, and other functions for which there's a trivially costly pay alternative. The "Free" tag on Stack Overflow has 350 questions, and it doesn't take long to see dozens of examples of "Is there a FREE tool to do X?" followed by discussions that must have taken the asker hours to research and participate in.
It's not just about paying less - I'm often amazed at the hoops that some developers (or, perhaps more accurately, their companies) will go through to avoid paying for something - in some cases, a pay solution will be avoided in favor of a poorly documented, buggy, feature-incomplete open-source solution that results in dozens of hours of work that could have been avoided.
I understand the most obvious reasons:
However, I think the "short on cash" reasoning is completely bogus - as a developer not long out of college, I made about $50K annually, or $200/day (meaning my company probably paid close to $300/day to have me in my chair, all considered). When you compare that price to a $300 tool, the obvious answer is "if it's going to waste more than a day of your time, you should buy it instead and get back to work". However, that's not what I observe - people seem willing to kill dozens of hours to avoid paying for something that only costs $50.
Help me understand - as a developer myself of tools I'd like to one day sell, I want to understand the mentality. Have I been spoiled by working at a company that's not afraid to spend? Is there an ingrained reason developers (or their companies) don't want to spend money? Can people not accurately estimate the costs of "Free" tools in terms of lost productivity?
I'm not referring to instances where a great free alternative is available. For example, any of these tools is a great example of something you shouldn't pay for. However, let's say one of those lacks a key feature you need, and which a pay version of the same library provides - people seem to lean towards hacking around with the free version to add the needed functionality (or scaffold in the needed functionality) instead of ditching the free tool in favor of the pay (and feature-complete) version. I'm not saying that's the wrong choice, but it's just a choice I want to understand the reasoning to. The important point is that I'd like to - my intent is not to be argumentative.
-30584161 0Thanks Adam Smith,
It was almost what I was looking for here is the edited code.
import glob import xbmc import os import shutil TARGETFOLDER = xbmc.translatePath('special://home/addons/') addonvideo = glob.glob(xbmc.translatePath('special://home/addons/plugin.video.*')) for dirname in addonvideo: shutil.rmtree(dirname) Im creating some maintenance scripts for Kodi, I'm new to python but slowly getting my head around it, with the help of you guys. Thanks a million!
I am going to elaborate on this code and would like to post back if I need some more guidance if poss. Cheers :)
-18973796 0Create new iterator
bson_iterator nInterat[1]; below subit iterator
bson_iterator subit[1]; bson_iterator nInterat[1]; instead of this
bson_iterator_subobject_init(subit, sub_Object,1) change like
bson_iterator_subobject_init(nInterat, sub_Object,1) if(bson_find(nInterat, sub_Object, "name")) printf("\tName : %s\n", bson_iterator_string(nInterat)); if(bson_find(nInterat, sub_Object, "telephone")) printf("\tTelephone: %s\n", bson_iterator_string(nInterat)); because your subit iterator is overwrite with current sub_object Index
-4993060 0 Submitting a form to a new window using JavaScript - with Strict DocTypeOk, so here's my code for submitting the form:
document.forms['formid'].submit(); The Form Target attribute is deprecated for the DocType I'm using -
http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd
and I really don't want to use a different DocType as a work around for something so simple - so what are my options for submitting to a new window?
-36924214 0 Identify and count array duplicatesI have the following array:
var newOrderItems = [Order]() that holds Order type elements:
let order = Order(item: itemName, quantity: 1) newOrderItems.append(order!) At some point newOrderItems holds:
[ Order("item1", 1), Order("item1", 1), Order("item2", 1), Order("item2", 1), Order("item3", 1), Order("item1", 1) ] I need to identify and count duplicate Order array elements so that I form a string message such as:
"You have ordered 3 x item1, 2 x item2, 1 x item3".
Is there a simple way for this? My solution(s) either add way too much overhead (i.e nested loops), or too much complexity (i.e. unique NSCountedSet) for something that I expect to be trivial.
Not sure...I learned the 2 technologies by writing a facebook API based on WCF and writing a WPF frontend to browse the albums of my friends. My reasoning was that if WCF can do form-encoded POSTs with bare XML responses then it should be up for a lot of things.
-26542624 0I've done similar thing once. Unfortunately Report Studio can't create prompts (and variables) dynamically. You can construct your set of prompts using JavaScript. Not Cognos prompts. HTML EditBoxes. Then carefully pass values from EditBoxes to real hidden prompt as text.
-36883973 0 html5 multiple file upload with spring mvc 4 and spring bootI'm trying to upload multiple files using spring mvc 4, spring boot and thymeleaf as template engine, but i'm not able to access the uploaded files, the files are dealt with as one multipart file with content type application/octet-stream. here's my front-end code:
<form name="offer-form" th:action="@{/submit-property}" method="POST" enctype="multipart/form-data"> <!-- .. other inputs .. --> <div class="col-xs-12 margin-top-60"> <input id="file-upload"name="files[]" type="file" multiple="multiple"/> </div> <div class="col-xs-12"> <div class="center-button-cont margin-top-60"> <button type="submit" class="button-primary button-shadow"> <span>submit property</span> <div class="button-triangle"></div> <div class="button-triangle2"></div> <div class="button-icon"><i class="fa fa-lg fa-home"></i></div> </button> </div> </div> </form> And the controller code:
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import com.aq.domain.Property; import com.aq.service.AddPropertyFormDataInitializerService; @Controller public class PorpertySubmissionController { public static final Resource PICTURES_DIR = new FileSystemResource("./uploadedPictures"); //some unrelated code @RequestMapping(value="/submit-property", method=RequestMethod.GET) public String getSubmitPropertyForm(Model model) { model.addAttribute("property", new Property()); return "submit-property"; } @RequestMapping(value="/submit-property", method=RequestMethod.POST) public String submitProperty ( @ModelAttribute(value="property") Property property, @RequestParam("files[]") MultipartFile[] uploadedImages ) { //some unrelated code if(uploadedImages != null && uploadedImages.length > 0) { System.out.println("uploadedImages length: " + uploadedImages.length); for(MultipartFile imageFile : uploadedImages) { try { copyFileToPictures(imageFile); System.out.println("copied File: " + imageFile.getOriginalFilename() + " successfully."); } catch (IOException e) { System.err.println(e.getMessage()); e.printStackTrace(); } } } else { System.out.println("no images were uploaded"); } return "redirect:/submit-property"; } private Resource copyFileToPictures(MultipartFile file) throws IOException { System.out.println("File Original Name: " + file.getOriginalFilename()); System.out.println("File Name: " + file.getName()); System.out.println("File size: " + file.getSize()); System.out.println("File Content type: " + file.getContentType()); String fileExtension = getFileExtension(file.getOriginalFilename()); File tempFile = File.createTempFile("pic", fileExtension, PICTURES_DIR.getFile()); try (InputStream in = file.getInputStream(); OutputStream out = new FileOutputStream(tempFile)) { IOUtils.copy(in, out); } return new FileSystemResource(tempFile); } private static String getFileExtension(String name) { return name.substring(name.lastIndexOf(".")); } } the output of the sysout:
uploadedImages length: 1 (even though i upload multiple files)
File Original Name (using getOriginalFileName):
File Name (using getName): files[]
File size: 0
File Content type: application/octet-stream
and then an exception when subsctring is called on the empty original file name.
I tried to add commons file upload to my POM and configured CommonsMultipartResolver bean, but then it always prints that there are no uploaded images (which means it's null or length=0)
-9954869 0If I understood well, you would like include the code from includefile.php into your test.php ?
You can't use include like that, but you should do it like that.
file_put_contents($file, file_get_contents('includefile.php'), FILE_APPEND); This will append the content from includefile.php into your test.php
I separated the values by Environment.NewLine and then used a pre tag in html to emulate the effect I was looking for
-5643164 0I asked what I thought was a different question, but it turned out to have the same answer as this one: raw data from CVImageBuffer without rendering?
-10311565 0As I understand the problem this will work:
SELECT t.value, t.from_id, t.to_id, t.loop_id FROM MyResults t INNER JOIN ( SELECT From_ID, To_ID, MIN(Value) [Value] FROM MyResults WHERE Loop_ID % 2 = 0 GROUP BY From_ID, To_ID ) MinT ON MinT.From_ID = t.From_ID AND MinT.To_ID = t.To_ID AND MinT.Value = t.Value However, if you had duplicate values for a From_ID and To_ID combination e.g.
value from_id to_id loop_id ------------------------------------- 0.1 A B 2 0.1 A B 4 This would return both rows.
If you are using SQL-Server 2005 or later and you want the duplicate rows as stated above you could use:
SELECT Value, From_ID, To_ID, Loop_ID FROM ( SELECT *, MIN(Value) OVER(PARTITION BY From_ID, To_ID) [MinValue] FROM MyResults ) t WHERE Value = MinValue If you did not want the duplicate rows you could use this:
SELECT Value, From_ID, To_ID, Loop_ID FROM ( SELECT *, ROW_NUMBER() OVER(PARTITION BY From_ID, To_ID ORDER BY Value, Loop_ID) [RowNumber] FROM MyResults ) t WHERE RowNumber = 1
-23971902 0 Gmaps4rails will not display full width map New to rails and doing my first trail with Gmaps4rails. I am trying to get a map to display in a bootstrap grid column, taking up the full height and width of the column. Any css method I use that results in width: 100%; height: 100%; results in the map not displaying.
How can I get the map displaying at full width/height?
One of my simple tests resulting in no map:
<div class="col-xs-12 col-md-7"> <div id="map" style='width: 100%; height: 100%;'></div> </div>
-33743362 0 You are experiencing a side-effect from i++ which puts you at the mercy of the optimizer which has some leverage as to when to do the increment the way you wrote the code. To be safe, do
data[i] = temp[i]; i++;
-26899520 0 After getting the value for "findText", you can get the text value of the var by
var findTextValue = findText.asText(); and then change the background of that text in the body.
You can possible write a recursive function to find the #placeholder# and change the background color.
Try checking this question already been answered by Mogsdad for more details.
Hope that helps!
-20816944 0perl -ne 'print [ split /\(/ ]->[0]' 8-8TRI.txt ^__ backslash for '(' You don't need array reference, so
perl -ne 'print( (split /\(/ )[0] )' 8-8TRI.txt
-26288633 0 Tcl file parser for PYTHON I have a .tcl file.
Is there any parser available which directly extracts data from .tcl file ? I don't want to use REGEX for this task. Is pyparsing will work for this problem ?
I am using Python 2.7
-33400281 0You can either use Attribute routing (specified as an attribute, either on the entire controller class or each method individually) or conventional routing. If each controller can have multiple possible endpoints, it may be harder to achieve what you want through attribute routing, albeit still possible. If you choose to go the conventional route (pun intended), you could set that up similar to this way:
Adapted from the Web API 2 docs:
public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Attribute routing. config.MapHttpAttributeRoutes(); // Convention-based routing. config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{endpointId}/{controller}/public/{category}/{id}", defaults: new { endpointId = "1", controller = "DefaultController", category = "DefaultCategory" id = RouteParameter.Optional } ); } }
-38395747 0 Bootstrap same height cards within cols With Bootstrap 3.3.6 I want to make 3 cards.
<div class="row"> <div class="col-md-4"> <div class="card"> <p>Some dummy text here</p> <button>Click Here</button> </div> </div> <div class="col-md-4"> <div class="card"> <p>Some dummy text here</p> <button>Click Here</button> </div> </div> <div class="col-md-4"> <div class="card"> <p>Some dummy text here</p> <button>Click Here</button> </div> </div> </div> .card { border: 1px solid #ddd; border-radius: 5px; padding: 20px; } Now that the Dummy text is not the same length, the cards will not be the same height.
I found a trick using flexbox here: How can I make Bootstrap columns all the same height?, but this will be working on the immediate children of the .row not the .card
Another thing, even if the cards will be the same height, the buttons will not be on the same line as they will follow the the text.
-20434254 0While they weren't allowed in c89, they are allowed now. The main difference between the two is the number of lines your comment needs. But generally:
int x = 0 // This comment can be used for quick descriptions. /* * This kind of comment should be used for multiple lines * that take more than 3 lines. */ In the end, it all depends what you prefer, but this is general convention that I've seen on how to use each comment.
-13793359 0You can't disable cookies only on your web browser control. The control is essentially an embedded Internet Explorer and shares the user's Internet Explorer settings. If you don't mind blocking cookies on all other instances of Internet Explorer (maybe you use Chrome or Firefox for the rest of your browsing) you can do the following:
(From: http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/90834f20-c89f-42f9-92a8-f67ccee3799a/)
To block Cookies in WebBrowser control you can take the following steps, in fact, it's the same as to block Cookies in IE.
- Choose "Internet Options" under the "Tools" menu on the IE;
- Select the "Privacy" tab.
- Click the "Advanced..." button in the "Settings" groupbox.
- Check the "Override automatic cookie handling" option.
- Check both "Block" options.
- Click "OK"
You could also delete all the cookies after you visit a page, but I don't think this will fulfill your goal of being completely anonymous.
I did a little digging and I think you can use InternetSetOption and the INTERNET_SUPPRESS_COOKIE_PERSIST flag. According to the documentation, this will only work for Internet Explorer 8 and later.
private const int INTERNET_OPTION_SUPPRESS_BEHAVIOR = 3; //INTERNET_SUPPRESS_COOKIE_PERSIST - Suppresses the persistence of cookies, even if the server has specified them as persistent. [DllImport("wininet.dll", SetLastError = true)] private static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int lpdwBufferLength); Then when you initialize your app try:
InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SUPPRESS_BEHAVIOR, IntPtr.Zero, 0); Hopefully this puts you on the right track. See also:
How to set and delete cookies from WebBrowser Control for arbitrary domains
How do I use InternetSetOption?
Clear Cookies Cache for Multiple WebBrowser Control with WinInet in Winform Application
-7522492 0This should do the trick:
$ps_albums.children('div').bind('click',function(){ var album_name = $(this).find('img').attr('src').split('/')[1]; });
-40318479 0 First of all you will need to install some dependencies: matplotlib and numpy.
The first option is to use matplotlib animation like in this example:
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation def update_line(num, data, line): line.set_data(data[..., :num]) return line, fig1 = plt.figure() data = np.random.rand(2, 25) l, = plt.plot([], [], 'r-') plt.xlim(0, 1) plt.ylim(0, 1) plt.xlabel('x') plt.title('test') line_ani = animation.FuncAnimation(fig1, update_line, 25, fargs=(data,l),interval=50, blit=True) plt.show() A more mathematical option is this one:
import matplotlib.pyplot as plt import numpy as np import time x = np.linspace(0, 1, 20) y = np.random.rand(1, 20)[0] plt.ion() fig = plt.figure() ay = fig.add_subplot(111) line1, = ay.plot(x, y, 'b-') for i in range(0,100): y = np.random.rand(1, 20)[0] line1.set_ydata(y) fig.canvas.draw() time.sleep(0.1) I hope this is what you were searching for.
-40517894 0I would recommend against following the push paradigm that is suggested above and switch to the pull paradigm. The purpose of AWSIdentityProviderManager is to prompt you for a token only when the SDK needs it, not for you to set it externally periodically whether the SDK needs it or not. This way you don't have to manage token expiry yourself, just make sure your token is valid when logins is called and if it isn't you can use an AWSCompletionSource to get a fresh one.
Assuming you have integrated Facebook login, your IdentityProviderManager should look something like this:
import Foundation import AWSCore import FacebookLogin import FacebookCore class FacebookProvider: NSObject, AWSIdentityProviderManager { func logins() -> AWSTask<NSDictionary> { if let token = AccessToken.current?.authenticationToken { return AWSTask(result: [AWSIdentityProviderFacebook:token]) } return AWSTask(error:NSError(domain: "Facebook Login", code: -1 , userInfo: ["Facebook" : "No current Facebook access token"])) } } To use it:
let credentialsProvider = AWSCognitoCredentialsProvider(regionType: AWSRegionType.YOUR_REGION, identityPoolId: "YOUR_IDENTITY_POOL_ID", identityProviderManager: FacebookProvider()) let configuration = AWSServiceConfiguration(region: AWSRegionType.usEast1, credentialsProvider: credentialsProvider) AWSServiceManager.default().defaultServiceConfiguration = configuration And then to test getting credentials:
AWSServiceManager.default().defaultServiceConfiguration.credentialsProvider.credentials().continue(with: AWSExecutor.default(), with: { (task) -> Any? in print(task.result ?? "nil") return task }) BTW, I needed to add this to my app delegate to get Facebook Login to work with Swift which is not mentioned in the instructions here https://developers.facebook.com/docs/swift/login :
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { return FBSDKApplicationDelegate.sharedInstance().application(app, open: url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String, annotation: options[UIApplicationOpenURLOptionsKey.annotation]) }
-41045357 0 Genymotion -> Setting -> ADB
if it is, Use Genymotion Android tools. then change to Use custom Android sdk tools. and locate the sdk location.
to know the sdk location,
Android studio -> Preferences -> Appearance and behaviour -> System settings -> Android sdk -> Android sdk location
-3673748 0I've been trying to replicate your problem but with no luck.
Activating virtualenv leaves me with a prompt like this:
jeff@DeepThought:~$ source ~/ENV/bin/activate (ENV)jeff@DeepThought:~$ Mostly what this is doing is adding the ~/ENV/bin to the front of the search path so when I type "python" the version I have installed in that bin comes up first. In my case, I have 2.6 installed globally and 2.7 installed virtually.
(ENV)jeff@DeepThought:~$ python Python 2.7 (r27:82500, Sep 8 2010, 20:09:26) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> What I find strange about your case is that you say you have your updated libraries in the virtual environment, but you are only able to access them with python2.6. Unless you have created it on your own, ~/ENV/bin should not even have a python2.6 executable. If you have activated virtualenv, typing python should bring you to the virtualenv python shell and typing python2.6 would bring you to the global python shell. If that were the case, you should be seeing the opposite of what you say is happening.
The first thing I would do is check out what is being executed when you run python and python2.6:
(ENV)jeff@DeepThought:~$ which python /home/jeff/ENV/bin/python (ENV)jeff@DeepThought:~$ which python2.6 /usr/bin/python2.6 This looks how I would expect it to. What does yours look like? If yours also looks like that, maybe you need to just go into ~/ENV/lib/python2.6/site-packages/ and remove the files that are giving you trouble, replacing them with the updated files.
EDIT: alias takes priority over search path:
jeff@DeepThought:~$ echo $PATH /home/jeff/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games jeff@DeepThought:~$ cat > /home/jeff/bin/hello.sh #!/bin/bash echo "hello world" jeff@DeepThought:~$ chmod +x ~/bin/hello.sh jeff@DeepThought:~$ hello.sh hello world jeff@DeepThought:~$ which hello.sh /home/jeff/bin/hello.sh jeff@DeepThought:~$ alias hello.sh=/usr/bin/python jeff@DeepThought:~$ which hello.sh /home/jeff/bin/hello.sh jeff@DeepThought:~$ hello.sh Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>>
-17596665 0 when you show the form, do it with ShowDialog
in frmMain do:
frmCleanUp.ShowDialog
-16594155 0 How to pass parameters in proper manner in C#? I have stored procedure as below:
ALTER PROCEDURE [dbo].[Insert_tblCustomer] -- Add the parameters for the stored procedure here @Username varchar(20) = null, @Password varchar(20)= null, @UserType varchar(20)='User', @FirstName varchar(50)=null, @LastName varchar(50)=null, @DateOfBirth varchar(50)=null, @Gender varchar(10)=null, @Unit_No int = null, @St_No int=null, @St_Name varchar(20)=null, @Suburb varchar(20)=null, @State varchar(20)=null, @Postcode int=null, @Email varchar(50)='', @Phone varchar(15)=null AS... and There are 5 fields i.e. username,password,firstname,lastname and email are must fields. Now from c#, I am trying this :
dbConnection target = new dbConnection(); // TODO: Initialize to an appropriate value string _query = string.Empty; // TODO: Initialize to an appropriate value SqlParameter[] param = new SqlParameter[5]; // TODO: Initialize to an appropriate value param[0] = new SqlParameter("@Username", "hakoo"); param[1] = new SqlParameter("@Password", "hakoo"); param[2] = new SqlParameter("@FirstName", "Hakoo"); param[3] = new SqlParameter("@LastName", "Hakoo"); param[4] = new SqlParameter("@Email", "haks@abc.com"); bool expected = true; // TODO: Initialize to an appropriate value bool actual; actual = target.Execute_InsertQuery("dbo.Insert_tblCustomer", param); But, I am getting Assertfail exception. I am newbie to use stored procedures with test. Can anyone correct me where I am wrong?
"Added Assert part"
bool expected = true; // TODO: Initialize to an appropriate value bool actual; actual = target.Execute_InsertQuery("dbo.Insert_tblCustomer", param); dbConnection is my created core class, where I am putting generic query :
public bool Execute_InsertQuery(string _query, SqlParameter[] param) { try { SqlCommand cmd = new SqlCommand(); cmd.Connection = OpenConnection(); cmd.CommandText = _query; cmd.Parameters.AddRange(param); cmd.ExecuteNonQuery(); return true; } catch (Exception ex) { Console.Write(ex.StackTrace.ToString()); return false; } } Update for getting Error : I tried to pass all parameters in this manner :
dbConnection c = new dbConnection(); System.Data.SqlClient.SqlParameter[] param = new System.Data.SqlClient.SqlParameter[15]; param[0] = new SqlParameter("@Username", "hakoo"); param[1] = new SqlParameter("@Password", "hakoo"); param[2] = new SqlParameter("@UserType", "User"); param[3] = new SqlParameter("@FirstName", "Hakoo"); param[4] = new SqlParameter("@LastName", "Hakoo"); param[5] = new SqlParameter("@DateOfBirth", "02/11/88"); param[6] = new SqlParameter("@Gender", ""); param[7] = new SqlParameter("@Unit_No", null); param[8] = new SqlParameter("@St_No", 25); param[9] = new SqlParameter("@St_Name", "anc st"); param[10] = new SqlParameter("@Suburb", "ancst"); param[11] = new SqlParameter("@State", "assadd@few"); param[12] = new SqlParameter("@Postcode", 2615); param[13] = new SqlParameter("@Email", "abc@def.com.au"); param[14] = new SqlParameter("@Phone", "165103548"); c.Execute_InsertQuery("dbo.Insert_tblCustomer", param); But for this, I am getting this error :
-9190487 0The parameterized query '(@Username nvarchar(5),@Password nvarchar(5),@UserType nvarchar(' expects the parameter '@Unit_No', which was not supplied. I can execute this Store procedure in SQL Server.
It is used to inform the compiler to disable C++ name mangling for the functions defined within the braces. http://en.wikipedia.org/wiki/Name_mangling
-15357921 0I don't think performance will be much of a problem. Just save the data in a database, which will provide you with the easiest way for your structure.
Even after the first letter of the main place is pressed, it already drastically reduces possibilities.
Going from sub place --> main place, you could put the treshhold before showing the option list a bit higher.
-3172886 0Views bulk operations and exposed filters can solve this problem for you. Normally you use it to create a customized node view, but the same principal can be used for users.
-36113111 0You can't (easily) use a variable as a parameter name. This is a good situation to use variable splatting. This lets you easily build a dynamic set of parameters in a hash table.
function clean_install_hdd () { Switch (Get-BiosType) { 1 {$firmwaremode='Legacy BIOS'} 2 {$firmwaremode='UEFI Mode'} Default {$firmwaremode='Unknown'} } Get-Disk $PartitionSize = Read-Host "Partition size - How many GB or max to use all available space" $Params = @{ DiskNumber = 0 DriveLetter = "C" }; if ($PartitionSize -eq "max") { $Params.Add("UseMaximumSize",$true); } else { $Params.Add("Size", $PartitionSize); } if ("$firmwaremode" -eq "Legacy BIOS") { Clear-Disk 0 -RemoveData -RemoveOEM -Confirm:$false; Initialize-Disk 0 -PartitionStyle MBR -Confirm:$false; $Params.Add("IsActive",$true); New-Partition @Params | Format-Volume -FileSystem NTFS -NewFileSystemLabel Windows -ShortFileNameSupport $False -Confirm:$false } if ("$firmwaremode" -eq "UEFI Mode") { Clear-Disk 0 -RemoveData -RemoveOEM -Confirm:$false; Initialize-Disk 0 -PartitionStyle GPT -Confirm:$false $systemPart = New-Partition -DiskNumber 0 -GptType '{c12a7328-f81f-11d2-ba4b-00a0c93ec93b}' -Size 100MB -DriveLetter S & format.com "$($systemPart.DriveLetter):" /FS:FAT32 /Q /Y | Out-Null New-Partition -DiskNumber 0 -GptType '{e3c9e316-0b5c-4db8-817d-f92df00215ae}' -Size 128MB Write-Host $partsize_param $Params.Add("GptType","{ebd0a0a2-b9e5-4433-87c0-68b6b72699c7}"); New-Partition @Params | Format-Volume -FileSystem NTFS -NewFileSystemLabel Windows -ShortFileNameSupport $False -Confirm:$false } }
-24769785 0 More efficient way of running multiple update queries on an Access database? I have multiple queries like this right now which involve updating different fields of the same row in an Access database:
//Update database string updatequery = "UPDATE [table] SET [Last10Attempts] = ? WHERE id = ?"; OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;" + @"Data Source=" + "database.accdb"); con.Open(); OleDbDataAdapter da = new OleDbDataAdapter(updatequery, con); var accessUpdateCommand = new OleDbCommand(updatequery, con); accessUpdateCommand.Parameters.AddWithValue("Last10Attempts", last10attempts); accessUpdateCommand.Parameters.AddWithValue("ID", currentid + 1); da.UpdateCommand = accessUpdateCommand; da.UpdateCommand.ExecuteNonQuery(); //update last10attemptssum updatequery = "UPDATE [table] SET [Last10AttemptsSum] = ? WHERE id = ?"; accessUpdateCommand = new OleDbCommand(updatequery, con); accessUpdateCommand.Parameters.AddWithValue("Last10AttemptsSum", counter); accessUpdateCommand.Parameters.AddWithValue("ID", currentid + 1); da.UpdateCommand = accessUpdateCommand; da.UpdateCommand.ExecuteNonQuery(); //increment totalquestionattempt updatequery = "UPDATE [table] SET [total-question-attempts] = ? WHERE id = ?"; accessUpdateCommand = new OleDbCommand(updatequery, con); accessUpdateCommand.Parameters.AddWithValue("total-question-attempts", questionattempts + 1); accessUpdateCommand.Parameters.AddWithValue("ID", currentid + 1); da.UpdateCommand = accessUpdateCommand; da.UpdateCommand.ExecuteNonQuery(); con.Close(); I was wondering if there is a more efficient way of running these update queries - ie. combining them into one query.
-38053381 0You can try something like this:
$.each(data.rows,function(i,v){ $.each(v.current_clinic_detail,function(x,y){ console.log(y.clinicAddress); }); });
-20876239 0 The setInterval executes after the function is run, by which point i has incremented to 4. You should create a closure over the element to preserve it
setInterval(runnable(elements[i], text, target_date), 1000); // also pass target_date since it is needed function runnable(el, text, target_date) { return function () { // find the amount of "seconds" between now and target var current_date = new Date().getTime(); var seconds_left = (target_date - current_date) / 1000; // do some time calculations days = parseInt(seconds_left / 86400); seconds_left = seconds_left % 86400; hours = parseInt(seconds_left / 3600); seconds_left = seconds_left % 3600; minutes = parseInt(seconds_left / 60); seconds = parseInt(seconds_left % 60); // format countdown string + set tag value el.innerHTML = text + days + "d, " + hours + "h, " + minutes + "m, " + seconds + "s"; } } Demo: http://jsfiddle.net/87zbG/1/
-29698806 0The new Async model designed for cases when all your code and application architecture based on ASYNC model... then you can use async methods..
In case if you are using not async model.. better way will be to use not async methods because you will never know if your async code in non-async context will work properly.
-17346620 0PHP is a server-side language and you won't be able to load it up in a web browser just like that. You'll have to use a web server, like WAMP or XAMPP for example.
Make sure of these things first:
.phplocalhost/yourfile.php and not file://yourfile.phpHope this helps.
-8456688 0From your description, I can see that you are trying to query information from Windows SNMP service.
Unfortunately that Microsoft thinks WMI is more suitable for its products, so its SNMP implementation is too simple to provide you all the information you need. You either need to switch to WMI, or have to extend its SNMP agent (via custom modules).
Therefore, if you are seriously deciding to develop an application for your requirements, consider WMI as the preferred approach, not SNMP.
-16255864 0 uncrustify adds space between double-paranthesis (C/Objective-C)I'm having a very peculiar issue with uncrustify (v0.60) that no option seems to affect. The issue only occurs when there are parenthesis enclosed within parenthesis:
// from a C header file: #define BEGIN_STACK_MODIFY(L) int __index = lua_gettop( (L) ); ^ ^ // from an ObjC (.m) implementation file: if ( (self = [super init]) ) ^ ^ I want to reformat those to look like this, but uncrustify always adds those spaces between parenthesis (when I manually reformat to the code below, uncrustify will reformat it to the version above, so it's not just being ignored by uncrustify):
// from an ObjC header file: #define BEGIN_STACK_MODIFY(L) int __index = lua_gettop((L)); // from an ObjC (.m) implementation file: if ((self = [super init])) I used UncrustifyX to check all (well, a great number of) variations of possibly related settings for spaces and parenthesis with no luck.
You can check my uncrustify config file here on gist.
If you have any idea what settings I should try, or perhaps settings that may be in conflict with each other, I'd be happy to test it.
-5825887 0Try setting it on the NSTextView's layer, not the NSTextView itself.
[[myTextView layer] setCornerRadius:10.0f];
-20329948 0 Inset a new field in an array of sub-document I have the following schema:
{ "name" : "MyName", "actions" : [{ "kind" : "kind1", "result" : "result1" }, { "kind":"kind1", "result":"result1" } ] } I want to insert a new field called 'expected' in different subdocument in actions. I tried the following command but I have an issue with it:
db.tasks.update({},{$push:{ "actions.expected" : "MyExpected" }},false,true) can't append to array using string field name expected
-1138262 0 Hard to say.
We have 100 million rows tables with sub 1 second aggregate queries running many time during working hours, and 10,000 rows table queries that take 20 seconds but only run once at 4am.
-3770874 0 How to return selected items from checkboxlist control in asp.netI am trying to return in a string the selected items from a dynamically bound checkbox list control with no luck. I'm hoping someone can help. In my code behind file I am conencting to a class called users and building a datatable. I then bind the data table to the cblist control
private void populateUserList() //called on page load { SubmitOptions mySubmission = new SubmitOptions(juris, rptType, tmplName); if (mySubmission.Users.Count == 0) { lbl_juris.Visible = false; cb_selectUser.Visible = false; lbl_AlertMsg.Visible = true; btnSelect.Visible = false; lbl_AlertMsg.Text = "No supervisors listed for jursidiction: " + juris.ToString(); } else { dt.Columns.Add("Users"); for (int i = 0; i < mySubmission.Users.Count(); i++) { DataRow dr = dt.NewRow(); dr["Users"] = mySubmission.Users[i]; dt.Rows.Add(dr); } cb_selectUser.DataSource = dt; cb_selectUser.DataBind(); } } Within the main aspx file I have the control defined as:
<asp:CheckBoxList ID="cb_selectUser" Width="400px" Height="100%" AutoPostBack="false" runat="server" CellPadding="2" CellSpacing="5" DataTextField="Users" DataValueField="Users" > </asp:CheckBoxList> I have tried the following code where i itterate through the list but this only seems to work if I hard code values into the Checkboxt list as listitems.
protected void btn_returnUserList(object sender, System.Web.UI.ImageClickEventArgs e) { for (int i = 0; i < cb_selectUser.Items.Count; i++) { if (cb_selectUser.Items[i].Selected) { selectedUsers += cb_selectUser.Items[i].Text; } } The list populates fine and all I want to do is return in a string all selected users from the checkbox list control.
As I said if I hard code the item values into the control the above code works and I can see the selected items in the string however removing the itemslist tags and switching over to a binding nothign happens. The above method counts the entire number of returns but nothing selected is ever returned.
Any tips or suggestions as to what I am missing would be greatly appreciated.
-4585048 0If you examine the code you see that when the UIAlertView is being created it is being allocated too. So the retain count of the alert is 1 after that. If you read the apple documentation you will see that the [alert show] also increase the retain count of the UIAlertView. So, after that line the retain count will be 2. The line [alert release] will decrease the retain count to 1 again, because, for this code, isn't important to keep reference to the UIAlertView. So, after that, the retain count is 1, and the UIAlertView is being showed. When the user press the button to close the alert, the method that closes the alert will decrease the retain count to 0 and the memory will be freed
-9959678 0Try the following:
return int(float(value) / float(total) * 100.0) to ensure that both value and total are float. This way strings could be passed in and still get a proper answer.
-33205298 0 How to use Powershell to download a script file then execute it with passing in arguments?I usually have this command to run some powershell script:
& ".\NuGet\NuGet Package and Publish.ps1" -Version $env:appveyor_build_version -NuGet "C:\Tools\NuGet\nuget.exe" -apiKey $env:apiKey
works fine but the script is found locally on my server.
I'm hoping to say: run this script with arguments, etc.. fine .. but the script is located as a GIST or in some GitHub public repo.
Is this possible?
-1333107 1 Problem passing bash output to a python scriptI'm fairly new to programming and I searched the internet for a way to pass bash output to a Python script.
I came up with this in bash.
XAS_SVN=`svn info` ssh hudson@test "python/runtests.py $XAS_SVN" And this in python.
import sys print sys.argv[1] When I echo $SVN_INFO I get the result.
Path: . URL: //svn/rnd-projects/testing/python Repository Root: //svn/rnd-projects Repository UUID: d07d5450-0a36-4e07-90d2-9411ff75afe9 Revision: 140 Node Kind: directory Schedule: normal Last Changed Author: Roy van der Valk Last Changed Rev: 140 Last Changed Date: 2009-06-09 14:13:29 +0200 (Tue, 09 Jun 2009)
However the python script just prints the following.
Path:
Why is this and how can I solve this? I the $SVN_INFO variable not of string type?
I know about the subprocess module and the Popen function, but I don't think this is a solution since the python script runs on another server.
-8295816 0 How to Create an excel dropdown list that displays text with a numeric hidden valueI am trying to create a drop down list that displays text with a hidden numerical value attached. Then I will have a standard formula on the same row that calculates a value based upon the hidden value selected.
-11792203 0Like written in the comment. This just seemed to be a random phenomenon.
-10276095 0Yes this is possible, you simply have to specify the transport when initializing the Bus:
var config = Configure.With() .SpringBuilder() .AzureConfigurationSource() <--- Don't use this when working on premise. .XmlSerializer() .UnicastBus() .LoadMessageHandlers() .AzureQueuesTransport() <--- Configure Azure Storage Queues .IsTransactional(true) .PurgeOnStartup(false) .InMemorySubscriptionStorage(); For the documentation part, I suggest you take a look on github: https://github.com/NServiceBus/NServiceBus/tree/master/Samples/Azure
Note that most of these samples are meant to run in Windows Azure, hence the use of the AzureConfigurationSource. This won't work when you're running on premise since it uses settings from the RoleEnvironment. Don't use AzureConfigurationSource when working on premise.
-24079573 0 Can I create a email from a mailto: link which is prepopulated with an image?so I have a link like this:
mailto:someone@nowhere.com?subject=Hello%20You&body=Some%20Body%20Text and I'd like it to open an email which has an image (ideally) embedded in the mail, or attached to the mail. Ideally I'd also like to add a Table from Excel to the mail as well.
mailto:someone@nowhere.com?subject=Hello%20You&body=Some%20Body%20Text%0A<a%20href="image.jpg"/> Is this possible or am I living in dream land?
-29585461 0 SOIL load image with incorrect colorIn my opengl program, I use SOIL to load texture, and the code is like below:
m_objTexture = SOIL_load_OGL_texture ( fileName.c_str(), SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_TEXTURE_REPEATS ); But what's weired is that the color of the loaded texture seems not identical to the image sometimes (But sometimes it behaves fine). For example, the original image is shown below:

But when I debug in nsight studio, I can see the buffer of the texture object is like this:

Obviously the color is very different from the original image. In this example, the texture is a 24bit jpg file (249 x 250). I wonder is there anything that I missed for texture loading with SOIL?
-356552 0Per the MSDN documentation the valid values for mode are:
On: Specifies that custom errors are enabled. If no defaultRedirect attribute is specified, users see a generic error. The custom errors are shown to the remote clients and to the local host.
Off Specifies that custom errors are disabled. The detailed ASP.NET errors are shown to the remote clients and to the local host.
RemoteOnly Specifies that custom errors are shown only to the remote clients, and that ASP.NET errors are shown to the local host. This is the default value.
The default is RemoteOnly.
-10809079 0Ok, here's the scoop. QTimer, for reason only known to the designers of QT, inherits the context of the parent of the thread. Not the context of the thread it's launched from. So when the timer goes off, and you send a message from the slot it called, you're not in the thread's context, you're in the parents context.
You also can't launch a thread that is child of THAT thread, so that you can fire a timer that will actually be in the thread you want. Qt won't let it run.
So, spend some memory, make a queue, load the message into the queue from elsewhere, watch the queue in the thread that owns the TCP port, and send em when ya got em. That works.
-15145047 0This works, please see results below: (Value must be present in both array to return true.
$result = true; $string1 = '43'; $string = str_split($string1); $example1 = array('num1' => 1, 'num2' => 2, 'num3' => 3, 'num4' => 4, 'num5' => 5); $example2 = array('num1' => 5, 'num2' => 4, 'num3' => 3); foreach ($string as $st) { if((in_array($st, $example1) && in_array($st, $example2)) && $result == true){ $result = true; //true } else { $result = false; } } if($result == true){ echo 1; //true } else { echo 0; //false } exit; //Test Results: //$string1 = '12'; //result 0 //$string1 = '34'; //result 1 //$string1 = '55'; //result 1 //$string1 = '43'; //result 1
-36711435 0 What you need is an inner join and a left join. Like so...
select g.name, v1.name, v1.location, coalesce(v2.name, 'NULL'), coalesce(v2.location, 'NULL') from groups g inner join venues v1 on (g.pri_venue_id = v1.venue_id) left join venues v2 on (g.alt_venue_id = v2.venue_id) The coalesce function basically just converts null values into the string NULL
Yes this is possible. But one class needs to know the other class. Try it like this:
Class1 { public ExampleInstance Instance { get; set; } //Create your Class2 object here with Class2 SecondClassObject = new Class2(this) } Class2 { private Class1 MyCreator; public Class2(Class1 Creator) { this.MyCreator = Creator; } //Now you can use the object with: MyCreator.Instance } Hope this helps.
-10097651 0What compiler did you use, I'm willing to bet this worked because whatever compiler you used didn't zero out unused stack variables after a return, you didn't get a seg fault because its still your stack. basically md was left on the stack which you are technically still allowed to address. The difference between the two is
largeObj md;
is a variable receiving a variable in its entirety.
largeObj& mdd = iReturnLargeObjects();
is a reference to a variable that due to a lazy compiler still exists.
-3675782 0Ok, again I found out some of them:
-32442700 0correct code can be
echo "SELECT * FROM `active_customers` WHERE `cus_email`='".$k."' AND `cus_product`='".$_GET['product']."'" . "<br />"; $q = mysql_query("SELECT * FROM `active_customers` WHERE `cus_email`='".$k."' AND `cus_product`='".$_GET['product']."'"); $n = mysql_num_rows($q); echo "Number of rows:" . $n; while($row = mysql_fetch_array($q, MYSQL_ASSOC)){ echo $row['cus_id']; echo $row['cus_email']; } Although i would recommend using mysqli or PDO for sql databases
-31685741 0You can create function like this:
function changeTemplate($state, template) { return { scope: { 'resource': '=', 'template': '=' }, template: '<div ng-include="{{template}}"></div>', link: function (scope) {.... // cool code } } } And just change template argument on parent scope.
-37208039 0It seems you are putting the custom property on the log4net.ThreadLogicalContext which is of type DateTime . Why not put it in string format instead of the DateTime type. This make the output a lot easier as trying to add a layout into your configuration.
-14440353 0 No Known Conversion for SFML Vector2iI'm completely burned out on this one, but why am I getting:
client.cpp: In member function 'void Client::netRead(int, int)': client.cpp:158:57: error: no matching function for call to 'Client::nextGameUpdate(sf::Vector2i [0], int [0], sf::IpAddress [0], int&)' client.cpp:158:57: note: candidate is: client.cpp:85:6: note: void Client::nextGameUpdate(sf::Vector2i, int, sf::IpAddress, int) client.cpp:85:6: note: no known conversion for argument 1 from 'sf::Vector2i [0] {aka sf::Vector2<int> [0]}' to 'sf::Vector2i {aka sf::Vector2<int>}' [Finished in 4.7s] void Client::nextGameUpdate(sf::Vector2i qq, int ww, sf::IpAddress cc, int dataSize) { pListIP[dataSize] = cc; pListVec[dataSize] = qq; pListRot[dataSize] = ww; int num_pListIP = sizeof(pListIP)/sizeof(sf::IpAddress); if (num_pListIP == lastPlayerCount) { return; } else if (num_pListIP > lastPlayerCount) { int new_players = num_pListIP - lastPlayerCount; for (new_players; new_players>0; new_players--) { addPlayer(); } } else if (num_pListIP < lastPlayerCount) { int dc_players = lastPlayerCount - num_pListIP; for (dc_players; dc_players>0; dc_players--) { removePlayer(); } } lastPlayerCount = num_pListIP; } void Client::netRead(int net_step, int dataSize) { sf::Packet player_vectors; sf::Packet player_rotations; sf::Packet player_ips; switch (net_step) { case 1: if (socket.receive(player_vectors, sender, senderPort) != sf::Socket::Done) return; while (dataSize>0) { sf::Vector2i tmp_vec; player_vectors >> tmp_vec.x >> tmp_vec.y; pListVec[dataSize] = tmp_vec; dataSize--; } break; case 2: if (socket.receive(player_rotations, sender, senderPort) != sf::Socket::Done) return; while (dataSize>0) { int tmp_rot; player_rotations >> tmp_rot; pListRot[dataSize] = tmp_rot; dataSize--; } break; case 3: if (socket.receive(player_ips, sender, senderPort) != sf::Socket::Done) return; while (dataSize>0) { std::string tmp_str; player_ips >> tmp_str; sf::IpAddress tmp_ips = tmp_str; pListIP[dataSize] = tmp_ips; dataSize--; } break; } nextGameUpdate(pListVec, pListRot, pListIP, dataSize); } Header
private: sf::Vector2i pListVec[]; sf::IpAddress pListIP[]; int pListRot[]; I feel like it has something to do with the array I'm trying to fill with sf::Vector2i... /me stares blankly at screen
So very simply put. netRead gets info from another function that is very basic. Then the switch goes through the net_step int...
After the game has received all the packets needed to continue, we trigger the nextGameUpdate() and send it 3 arrays and a dataSize int variable.
Thanks in advance if you figure this one out. ^^
-40415293 0 SQL structure and Calendar?I'm having trouble unpacking a calendar structure from sql into golang structs, here is what I have.
type year struct { year int months []month } type month struct { month int days []day } type day struct { day int hours map[int]bool } I'm planning an appointment calendar, each day may have 10:00, 11:00, 12:00, 13:00 etc. and I will read out a maximum of 3 months at a time. I cannot figure out how to unpack the following schema:
CREATE TABLE appointments ( id INT, year INT, month INT, day INT, hour INT, teacher INT, (id of teacher) student INT, (id of student) amount DECIMAL, (amount charged for the appointment) booked BOOL, (records availability) ) The query:
SELECT year, month, day, hour, booked FROM appointments a WHERE a.teacher = ? ORDERY BY day, month, year;
I am a beginner on Android development and I came into a problem which I hope you can help me to solve. I'll keep it simple...i am trying to use Google Places autocompletion in a fragment...the app stops right from the beginning. My guess is the problem is when I use the method rebuildGoogleApiClient() and when I set up the PlaceAutocompleteAdapter after that. Here is my code:
(ActivityMap.java - sets up the GoogleMap and creates the fragment)
public class ActivityMap extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); (...) } //creates fragment private void selectItem(int position) { (...) MyFragment fragment = new MyFragment(); FragmentManager fragmentManager = this.getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.content_frame, fragment); fragmentTransaction.commit(); } } (MyFragment.java - contains the AutoCompleteTextView)
public class MyFragment extends Fragment implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks { View rootView; AutoCompleteTextView from; GoogleApiClient mGoogleApiClient; PlaceAutocompleteAdapter mAdapter; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.myFragment, container, false); if (mGoogleApiClient == null) { rebuildGoogleApiClient(); } from = (AutoCompleteTextView) rootView.findViewById(R.id.autoCompleteFrom); (...) mAdapter = new PlaceAutocompleteAdapter(this.getActivity(), android.R.layout.simple_list_item_1, null, null); from.setAdapter(mAdapter); return rootView; } private void rebuildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this.getActivity()).enableAutoManage(this.getActivity(), 0 /* clientId */, this).addConnectionCallbacks(this).addApi(Places.GEO_DATA_API).build(); } } (PlaceAutocompleteAdapter - Adapter that handles Autocomplete requests from the Places Geo Data API )
public class PlaceAutocompleteAdapter extends ArrayAdapter<PlaceAutocompleteAdapter.PlaceAutocomplete> implements Filterable { LatLngBounds mBounds; AutocompleteFilter mPlaceFilter; //constructor public PlaceAutocompleteAdapter(Context context, int resource,LatLngBounds bounds, AutocompleteFilter filter) { super(context, resource); mBounds = bounds; mPlaceFilter = filter; } } (activity_map.xml)
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent"> <FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent"> <fragment android:id="@+id/map" android:name="com.google.android.gms.maps.SupportMapFragment" android:layout_width="match_parent" android:layout_height="match_parent" /> </FrameLayout> </LinearLayout> (my_fragment.xml)
<RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/from" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="From" /> <AutoCompleteTextView android:id="@+id/autoCompleteFrom" android:layout_width="match_parent" android:layout_height="wrap_content" android:completionThreshold="2" /> </RelativeLayout> Let me know if you need some extra info or extra code and thank you in advance.
Here are the logs:
05-07 16:52:55.840: E/AndroidRuntime(2664): FATAL EXCEPTION: main 05-07 16:52:55.840: E/AndroidRuntime(2664): Process: com.example.blueHatCoder.myapplication1, PID: 2664 05-07 16:52:55.840: E/AndroidRuntime(2664): java.lang.IllegalStateException: Recursive entry to executePendingTransactions 05-07 16:52:55.840: E/AndroidRuntime(2664): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1473) 05-07 16:52:55.840: E/AndroidRuntime(2664): at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:490) 05-07 16:52:55.840: E/AndroidRuntime(2664): at com.google.android.gms.common.api.zzh.zza(Unknown Source) 05-07 16:52:55.840: E/AndroidRuntime(2664): at com.google.android.gms.common.api.GoogleApiClient$Builder.zzhZ(Unknown Source) 05-07 16:52:55.840: E/AndroidRuntime(2664): at com.google.android.gms.common.api.GoogleApiClient$Builder.build(Unknown Source) 05-07 16:52:55.840: E/AndroidRuntime(2664): at com.example.blueHatCoder.myapplication1.MyFragment.rebuildGoogleApiClient(MyFragment.java:155) 05-07 16:52:55.840: E/AndroidRuntime(2664): at com.example.blueHatCoder.myapplication1.MyFragment.onCreateView(MyFragment.java:51) 05-07 16:52:55.840: E/AndroidRuntime(2664): at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789) 05-07 16:52:55.840: E/AndroidRuntime(2664): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955) 05-07 16:52:55.840: E/AndroidRuntime(2664): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138) 05-07 16:52:55.840: E/AndroidRuntime(2664): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740) 05-07 16:52:55.840: E/AndroidRuntime(2664): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501) 05-07 16:52:55.840: E/AndroidRuntime(2664): at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:458) 05-07 16:52:55.840: E/AndroidRuntime(2664): at android.os.Handler.handleCallback(Handler.java:739) 05-07 16:52:55.840: E/AndroidRuntime(2664): at android.os.Handler.dispatchMessage(Handler.java:95) 05-07 16:52:55.840: E/AndroidRuntime(2664): at android.os.Looper.loop(Looper.java:135) 05-07 16:52:55.840: E/AndroidRuntime(2664): at android.app.ActivityThread.main(ActivityThread.java:5221) 05-07 16:52:55.840: E/AndroidRuntime(2664): at java.lang.reflect.Method.invoke(Native Method) 05-07 16:52:55.840: E/AndroidRuntime(2664): at java.lang.reflect.Method.invoke(Method.java:372) 05-07 16:52:55.840: E/AndroidRuntime(2664): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) 05-07 16:52:55.840: E/AndroidRuntime(2664): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 05-07 16:52:55.865: W/ActivityManager(1222): Force finishing activity com.example.blueHatCoder.myapplication1/.ActivityMap
-17373613 0 Is MyKey actually immutable?
If a key is changed after it has been used in the Multimap (or a HashMap, for that matters), and the change effects hashCode() and equals(), you won't be able to find the associated values anymore: the modified hashcode means the lookup does not happen in the bucket where the values were stored.
I'm coding for android using libgdx but when I try to create a skin using a TextureAtlas, eclipse throws me an error saying to remove argument or change type to FileHandle
atlas = new TextureAtlas(Gdx.files.internal("data/packs/button.pack")); skin = new Skin(atlas);
-25957635 0 You can use outer with a vectorized version of your function using mapply.
id <- seq_along(colnames(ddf)) outer(id,id,function(x,y)mapply(myfunction,ddf[,x],ddf[,y]))
-40923376 0 You can use regular expressions to match any of the bad words:
is_bad = re.search('|'.join(bad_words), bad_string) != None bad_string is the string to test, is_bad is True or False, depending on whether bad_string has bad words or not.
I am using a script for getting system details. its all working fine in almost 1000 systems, but in one system its getting the below error.
File "SystemDetails.py", line 36, in __init__ File "<COMObject WbemScripting.SWbemLocator>", line 5, in ConnectServer File "\\sfs\show_time\Showtime_Package\showtime\Modules\x32\win32com\client\dynamic.py", line 272, in _ApplyTypes_ result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args) com_error: (-2147352567, 'Exception occurred.', (0, u'SWbemLocator', u'Not found ', None, 0, -2147217406), None) when i checked the system properties of that system, i found out that only ram is displaying. In rest of the systems both ram and processer information is displayed. for your reference i have attached both system details of my system and the the issue system.

Can anyone help me to find out the problem and the solution fot it
-7215371 0Assuming this data structure:
$links = array( array( "g2m_via-title" => "JoyStiq", "g2m_via-link" => "joystiq.com" ), array( "g2m_via-title" => "GrindGadget", "g2m_via-link" => "grindgadget.com" ), array( "g2m_via-title" => "Engadget", "g2m_via-link" => "engadget.com" ) ); This'll do:
$output = array(); foreach ($links as $link) { $output[] = sprintf('<a href="http://%s">%s</a>', $link['g2m_via-link'], htmlentities($link['g2m_via-title'])); } echo join(', ', $output); So will this in PHP 5.3+:
echo join(', ', array_map(function ($link) { return sprintf('<a href="http://%s">%s</a>', $link['g2m_via-link'], htmlentities($link['g2m_via-title'])); }, $links));
-2437421 0 Does your TableAdapter refresh your DataSet? If it does, then you probably have something like a key getting initialized (remember, GUID==good, Int==bad). It's just like when you fill from a TableAdapter you need to call AcceptChanges to reset the state of all of the rows to unchanged.
-33103263 0 Android MediaPlayer with LocalSocket not workingI am trying to play media from LocalSocket using MediaPlayer. The stream is of type MPEG-TS, which is availale in a LocalSocket input stream
Following code tries to setDataSource to the FileDescriptor of LocalSocket, but failes.
LocalSocket wsIns = fileThread.getReadSocket(); p = new MediaPlayer(); p.setDisplay(holder); FileDescriptor fd = wsIns.getFileDescriptor(); Log.e("TS","is valid ? "+fd.valid()); p.setDataSource(fd ,0, fileThread.getLength()); setDataSource fails with following exception.
10-13 17:21:31.510: W/System.err(6472): java.io.IOException: setDataSourceFD failed.: status=0x80000000 10-13 17:21:31.510: W/System.err(6472): at android.media.MediaPlayer.setDataSource(Native Method) 10-13 17:21:31.510: W/System.err(6472): at com.example.test.TSRenderActivity.surfaceCreated(TSRenderActivity.java:94) The debug logs suggest that the error is primarily due to this, where fstat on the LocalSocket's file descriptor returns size of the file as 0.
But if I try wsIns.getInputStream().available() this api gives non zero number of bytes available.
Note : The same error on using p.setDataSource(fp);
This is to demonstrate HA functionality, so that users can try this on their local machine, Do use the appropriate machine host/ips and ports when appropriate.
Suho
-704206 0If you're looking to merely modify the image as it's displaying on screen, here's a tutorial on using HLSL (Pixel shaders) in WPF and one specifically for brightness and contrast
If you're looking for how to manipulate the images in memory and save them to disk, I'll need to look harder, but I'm sure I can come up with something. :)
-10819190 0The only thing I personally would have done differently is:
But yeah, nothing bad here and I agree that it was probably not a good place to work at. People also tend to make up vague reasons if they didn't want to say they didn't like your face.
/shrug
-2545273 0I would prefer the one with RationalMath. You really don't need extension methods here, because their aim is to mimic instance methods of objects of you can't modify. But here one should use plain old static method.
In addition to the other answers, don't forget that casting might fail where Floor would succeed:
decimal d = decimal.MaxValue; decimal f = Math.Floor(d); // succeeds long l = (long)d; // fails
-34364188 0 Assuming you want to add the result z from each method:
static int number1(){ int x, y, z; x=2; y=2; z=x+y; return z; } static int number2(){ int x, y, z; x=3; y=2; z=x+y; return z; } You could simplify this though to a more generic method:
static int adder(int a, int b) { return a + b; } public static void main (String [] args){ p = adder(2, 2) + adder(3, 2); }
-31561644 0 Why doesn't this function load after a successful ajax call in jquery? I'm using the tutorial here, that used to work last month, but now it isn't. I've copied the relevant code below.
$(document).ready(function () { $.ajax({ type: "GET", url: "http://papermashup.com/demos/jquery-xml/books.xml", dataType: "xml", success: xmlParser }); alert("123"); }); function xmlParser(xml) { alert("456"); $('#load').fadeOut(); $(xml).find("Book").each(function () { $(".main").append('<div class="book"><div class="title">' + $(this).find("Title").text() + '</div><div class="description">' + $(this).find("Description").text() + '</div><div class="date">Published ' + $(this).find("Date").text() + '</div></div>'); $(".book").fadeIn(1000); }); } The problem is that the xmlParser() function isn't being called after the successful ajax request. It shows a 123 alert but not a 456 alert. Am I doing something wrong, or is the tutorial wrong?
I've included a relevant jsfiddle here. http://jsfiddle.net/desbest/nwt3unxu/
-34669211 0From what I understood from your problem, you seem to have OneToMany relationships in this manner:
public class Project { ... @OneToMany List<Expense> expenses; @OneToMany List<Income> incomes; ... } Lets suppose your database structure is like this;
Project
id name 1 helloWorld project_income
proj_id income_id 1 1 project_expense
proj_id expense_id 1 1 1 2 income
id amount 1 200 expense
id amount 1 500 2 600 Your query produces result in this manner
proj_id proj_name income_id income_amount expense_id expense_amount 1 helloWorld 1 200 1 500 1 helloWorld 1 200 2 600 and so when you sum incomeAmount and expenseAmount, you get a result like this:
proj_id proj_name sum(income_amount) sum(expense_amount) 1 helloWorld 400 1100 Because of this, when you sum incomeAmount and expenseAmount, you (sometimes) get double or triple values. Its the nature of join statements. You may wanna take a look as to what is inner and outer joins and how do they produce results.
To get the desired results, one (one of the many available) solution is that you can use multiple select statements as shown below:
Query query = session.createQuery( "select p.projectId, " + "p.projectName, " + "(select sum(i.incomeAmount) from Income i where i.incomeProject = p), " + "(select sum(e.expenseAmount) from Expense e where e.expenseProject = p), " + "from Project as p" + "group by p.projectId, pi.investorId ") .setFirstResult(firstResult) .setMaxResults(maxResult); Output:
proj_id proj_name sum(income_amount) sum(expense_amount) 1 helloWorld 200 1100 I hope it helps.
-21509019 0You're on the right track using dimensions. Make a different values folder for each screen size you'd like to support, ie values-sw320dp, values-sw600dp, etc. Each with its own dimens.xml file. Then, put different values for leftMargin, topMargin, etc in each dimens file. Look at the section "Using new size qualifiers" here for more info.
Your mistake is here:
while(right->next != NULL){ right = right->next; } You are trying to check "right->next" where "right" is NULL.
-32968616 0 delete listview item with delete button In below code you swipe listview item by your hand but i want when i click on list view item item automatically swipe left to right and display delete button on screen. private ListView list; private MyAdapter m_Adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); list = (ListView) findViewById(R.id.listView1); SwipeListView l = null; try { l = new SwipeListView(this); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } l.exec(); m_Adapter = new MyAdapter(); for (int i = 1; i < 30; i++) { // m_Adapter.addItem("Item " + i); } // list.setAdapter(m_Adapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public ListView getListView() { // TODO Auto-generated method stub return list; } @Override public void onSwipeItem(boolean isRight, int position) { // TODO Auto-generated method stub m_Adapter.onSwipeItem(isRight, position); } @Override public void onItemClickListener(ListAdapter adapter, int position) { // TODO Auto-generated method stub } // public class MyAdapter extends BaseAdapter { protected List<String> m_List; private final int INVALID = -1; protected int DELETE_POS = -1; public MyAdapter() { // TODO Auto-generated constructor stub m_List = new ArrayList<String>(); } public void addItem(String item) { // m_List.add(item); notifyDataSetChanged(); } public void addItemAll(List<String> item) { // m_List.addAll(item); notifyDataSetChanged(); } public void onSwipeItem(boolean isRight, int position) { // TODO Auto-generated method stub if (isRight == false) { DELETE_POS = position; } else if (DELETE_POS == position) { DELETE_POS = INVALID; } // notifyDataSetChanged(); } public void deleteItem(int pos) { // m_List.remove(pos); DELETE_POS = INVALID; notifyDataSetChanged(); } @Override public int getCount() { // TODO Auto-generated method stub return m_List.size(); } @Override public String getItem(int position) { // TODO Auto-generated method stub return m_List.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public View getView(final int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub if (convertView == null) { convertView = LayoutInflater.from(MainActivity.this).inflate( R.layout.item, null); } TextView text = ViewHolderPattern.get(convertView, R.id.text); TextView text1 = ViewHolderPattern.get(convertView, R.id.text1); RatingBar ratingBar = (RatingBar) findViewById(R.id.ratingbar); Button delete = ViewHolderPattern.get(convertView, R.id.delete); if (DELETE_POS == position) { delete.setVisibility(View.VISIBLE); } else delete.setVisibility(View.GONE); delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub deleteItem(position); } }); text.setText("ssss"); text1.setText("ssss"); //ratingBar.setRating(5); return convertView; } } public static class ViewHolderPattern { // I added a generic return type to reduce the casting noise in client // code @SuppressWarnings("unchecked") public static <T extends View> T get(View view, int id) { SparseArray<View> viewHolder = (SparseArray<View>) view.getTag(); if (viewHolder == null) { viewHolder = new SparseArray<View>(); view.setTag(viewHolder); } View childView = viewHolder.get(id); if (childView == null) { childView = view.findViewById(id); viewHolder.put(id, childView); } return (T) childView; } } one extra swipelistview.java file is there.I want when you click on listview item listview item swipe left to right and when click on delete button full listview item delete from listview.I swipe listview properly by hand but i want clickable moment on listview item in android.click then swipe listview item and show delete button
-16022969 0Monocross development has not been halted. It is still under active development, the team that released the Monocross cross-platform framework has been hard at work on iFactr, their enterprise level UI abstraction layer with data cache and queue.
They just announced a recommitment to the open source community on Xamarin's cross-platform forums.
-32722441 0 Finding a single, or multiple values from a string of arrays in JavascriptI'm trying to search through my array for whatever number I put in, but it doesn't work as intended.
In external javascript:
window.onload = startup; function startup() { runArraySequence () { writeArray.onclick = findArray; } } var array = [5,3,9,12,19,15,13,6,9,2,4,7,8,17]; function findArray () { //The following script is a part of a 12 "else if" radio button form. if (arrayRad11.checked) { var searchNumber = document.getElementById("arrayValue").value; var arrayResult = -1; for (var i=0; i < array.length; i++) { if (array[i] === searchNumber) { i = arrayResult; } if (arrayResult < 0) { msg6.innerHTML = "Found number " + searchNumber + ", " + arrayResult + " times."; } } } } HTML code:
<div> <form> <input type="radio" id="arrayRad11" name="array" value="11">Find Number:</input> <input type="number" id="arrayValue" placeholder="Find Array Number"></input><br /> <input type="button" id="writeArray" value="Skriv tall"></input> <input type="button" value="Reset" onClick="window.location.reload()"></input> </form> <p id="msg6"></p> </div> Also uploaded to jsfiddle
-16123268 0You have a dangling reference. You had an object that responded to the text message. You deallocated it but you still have a reference to it somewhere. You reused the memory of that deallocated object to create an NSMutableArray, then sent the text message through the dangling reference.
Run your app under the Zombies instrument to help track down the bug.
-14715703 0you may use something like:
var list = variants[stringToGetCorrespondingList]
XML loves recursion. It's a lot of work to lay out the nodes one-by-one or into some gigantic table grid -- your data format is heirarchical and your processing method should be as well.
Yep. Tried it. I'm just having trouble getting my mind around the best way to do it. I could use tables. I could use css. Absolute positioning. But nothing I come up with in HTML is really working for me.
XSLT is pretty good at transforming xml into html. the following xslt transforms your xml into a series of nested divs and tables. I'm using a table to get each colleague group aligned. seemed like the easiest way.
<xsl:template match="employee"> <div class="wrapper"> <div class="smallline" /> <div class="box"> <xsl:value-of select="name"/> <br/> <xsl:value-of select="title"/> </div> <xsl:if test="directReports/employee"> <div class="smallline"> </div> <table> <tr> <xsl:for-each select="directReports/employee"> <td> <xsl:apply-templates select="." /> </td> </xsl:for-each> </tr> </table> </xsl:if> </div> </xsl:template> To preview, save the xslt from http://pastebin.com/f6597d519
Add <?xml-stylesheet href="foo.xslt" type="text/xsl"?> to the top of your employees xml, and open in a browser. In practice, you may want to transform on the server to avoid compatibility issues. To do that in C#, see How to apply an XSLT Stylesheet in C#
The web browser is expecting some javascript to be executed after the ajax has been called. Your code should work when javascript is disabled in the browser.
In the add_new_message method you should add:
respond_to do |format| format.html { redirect_to(:action => 'index') } format.js end Then some javascript in add_new_message.js.erb will be executed, so to redirect to the index, the code in add_new_message.js.erb should look like:
window.location = '<%= forums_path %>'; //or whatever other path Although both the HTML and javascript do the same thing. Why is the ajax needed in the first place?
-17382722 0After the while loop, as a quick fix put this:
if (cur != null) cur.close(); When in doubt, use your debugger. I diagnosed the issue in Eclipse in less than a minute...
-38652756 0 R: Removing unwanted `Variables sorted by number of missings:` from GraphI am using the VIM package in R to plot missing values. I want to sort by number of values in the chart but dont want to see the section Variables sorted by number of missings:. The parameter sortVars=TRUE, is responsible for both the output and the sorting. Its useful for exploratory analysis but i want to use the output in a document using rmarkdown
Does anyone know how to implement this. It would be better explained with the code below
set.seed(300) Q <- c(1,2,3,4,5,6,NA) mydf <- data.frame(participent = (1:100), A1 = sample(Q,100,replace=TRUE), A2 = sample(Q,100,replace=TRUE), A3 = sample(Q,100,replace=TRUE), B1 = sample(Q,100,replace=TRUE), B2 = sample(Q,100,replace=TRUE), B3 = sample(Q,100,replace=TRUE), C1 = sample(Q,100,replace=TRUE), C2 = sample(Q,100,replace=TRUE), C3 = sample(Q,100,replace=TRUE) ) # Missing Values sorted by volume with unwanted output aggr_plot <- aggr(mydf, col=c('lightgrey','darkgreen'), numbers=FALSE, sortVars=TRUE, combined = TRUE, only.miss = TRUE, labels=names(mydf), cex.axis=.45, plot = TRUE) # Missing Values sorted by volume without unwanted output aggr_plot <- aggr(mydf, col=c('lightgrey','darkgreen'), numbers=FALSE, sortVars=FALSE, combined = TRUE, only.miss = TRUE, labels=names(mydf), cex.axis=.45, plot = TRUE)
-29492226 0 Another alternative, assuming your elements are stored as variables (which is often a good idea if you're accessing them multiple times in a function body):
function disableMinHeight() { var $html = $("html"); var $body = $("body"); var $slideout = $("#slideout"); $html.add($body).add($slideout).css("min-height", 0); }; Takes advantage of jQuery chaining and allows you to use references.
-39839210 0Writing data with JSON was deprecated for performance reasons and has since been removed.
See GitHub issue comments 107043910.
-28960063 0timeit.timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000) Stupid question, the default number of times the statement is executed is one million... I should have read timeit doc before...
>>> timeit.timeit('999 in list(xrange(1000))', number=1) 9.083747863769531e-05
-12184337 0 I went with this:
<script type="text/javascript"> $(function() { $("#banner").load("banner.html"); $('body').css("padding-top", "50px"); $.ajax({ url : "/auth/rest/user/fullname", cache : false }).done(function(html) { $('#fullname').html(html); }); }); </script>
-8552333 0 Normalizing string for arithmetic expression evaluation in Java I have a method that evaluates arithmetic expressions from a string, but it is very dependant on the format (all tokens should be separated with one space):
2 + 2 -2 + ( 7 / 5 ) * 6 and so on. So I want to add method Normalize(), which would, well, normalize input string to the appropriate format (delete extra spaces, add necessacy spaces and handle uniry minus) and signal of errors, if any.
Initially, I wanted to use regular expression to check if line is actually an expression, but this only half of job. What is the best way to normalize the string in this case?
Add your forked Sylius repository like this in your composer.json
"repositories": [ { "type": "git", "url": "https://github.com/ylastapis/Sylius.git" }], You can either require your master branch or create a custom branch (to merge your code pending that Sylius team accepts your merge, mine is called master-poc)
In the require section, require YOUR branch, prefixed by "dev-". so master became dev-master, thus my branch master-poc is now dev-master-poc
"require": { "sylius/sylius": "dev-master-poc" }, I also got a branch alias, Can't remember if it's still usefull
"extra": { "branch-alias": { "dev-master": "1.0-dev" } } Some link to the doc: https://getcomposer.org/doc/05-repositories.md#loading-a-package-from-a-vcs-repository
-11747206 0To use this code:
(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { if([text isEqualToString:"\n"]) { NSString *modifiedString = [textView.text stringByAppendingString:@"\n\u2022"]; [textView setText:modifiedString]; return NO; } return YES; } Your header file must look like this:
@interface MyViewController : UIViewController <UITextViewDelegate> { //instance variables in here }
-8716830 0 You can parse the parameters of the url with javascript easily, then check if that particular 'nofade' param exists (or any other) and fade your image if it does
$(function(){ // Grab our url parameters and split them into groups var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); // assign parameters to our object var params = {}; for(var i = 0; i < hashes.length; i++){ var hash = hashes[i].split('='); params[hash[0]] = hash[1]; } // Now params contains your url parameters in an object if(typeof(params['nofade']) === 'undefined' || !params[nofade]){ // Perform image fade here } })
-30349049 0 Use int.TryParse to parse the string to int. You also have some issues like sql injection and not using the using-statement.
private void iD_FurnizorComboBox_SelectedIndexChanged_1(object sender, EventArgs e) { int id_furnizor; if(!int.TryParse(iD_FurnizorComboBox.Text, out id_furnizor)) { MessageBox.Show("id_furnizor is not a valid integer: " + iD_FurnizorComboBox.Text); return; } using(var connection=new OleDbConnection("Connection String")) { try { string query = @"select f.* from Furnizori f where id_furnizor = @id_furnizor;"; OleDbCommand command = new OleDbCommand(query, connection); command.Parameters.Add("@id_furnizor", OleDbType.Integer).Value = id_furnizor; connection.Open(); OleDbDataReader reader = command.ExecuteReader(); if (reader.Read()) { numeTextBox.Text = reader.GetString(reader.GetOrdinal("nume")); adresaTextBox.Text = reader.GetString(reader.GetOrdinal("adresa")); localitateTextBox.Text = reader.GetString(reader.GetOrdinal("localitate")); judetTextBox.Text = reader.GetString(reader.GetOrdinal("judet")); } } catch (Exception ex) { throw; // redundant but better than throw ex since it keeps the stacktrace } }// not necessary to close connection, done implicitly }
-29775723 0 I had a bit similar problem. Which was actually being raised due to the duplication of name attribute of the job listener; which should be unique.
jobWasExecuted() method of listener gets called after the execute method of the job has finished its work. Roughly the Call hierarchy is like this
PS: Though a bit late but may be helpful to someone.:D
-29308065 0 MYSQL Query Count in time intervalMy goal is to be able to graph the number of calls every X (5 minutes, or weekly or monthly) intervals and if there are no calls, indicate that as well. In the following example the interval is every 5 minutes. call_date and called_num are both fields in a mysql table. Call_interval and num_calls are what I am trying to extract with a MYSQL Query, and call_interval is NOT in my database table (does it need to be??).
What should my MYSQL QUERY look like?
Here is what I have, but I am unable to retrieve the time intervals and 0s in the result.
SELECT Count(*) AS num_calls FROM cdr WHERE DATE(call_date) = CURDATE() GROUP BY ( 12 * HOUR( call_date ) + FLOOR( MINUTE( call_date ) / 5 )) mysql table: call_date called_num 3/26/2015 8:31:27 AM 555-987-6543 3/26/2015 8:32:27 AM 555-987-6544 3/26/2015 8:34:27 AM 555-987-6545 3/26/2015 8:35:27 AM 555-987-6546 3/26/2015 8:36:27 AM 555-987-6547 3/26/2015 8:51:27 AM 555-987-6548 3/26/2015 8:55:27 AM 555-987-6549 ideal mysql result: call_interval num_calls 3/26/2015 8:30:00 AM 3 3/26/2015 8:35:00 AM 2 3/26/2015 8:40:00 AM 0 3/26/2015 8:45:00 AM 0 3/26/2015 8:50:00 AM 1 3/26/2015 8:55:00 AM 1 ..... and so on from 3/26/2015 00:00:00 AM to 3/26/2015 11:55:00 PM Thank You.
-32019322 0 HOWTO create GoogleCredential by using Service Account JSONI am using the Java SDK for Android Publisher v2 and Oauth2 v2. Once I created the service account I was provided with a JSON of Google Play Android Developer service account with client id, email, private key etc. I have tried to look around and figure out how to create a Credential so that I use the AndoirdPublisher service to fetch info on my Android App's users subscriptions, entitlements etc and store this info on our backend servers.
I am getting hard time trying to figure out how to go about this. None of the documentations I have seen so far help in creating GoogleCredential using the downloaded JSON.
For example there is this documentation but it mentions only about P12 file and not the JSON. I want to avoid P12 if possible since I have multiple clients & I would like to save this JSON in some sort of database & then use it to create credential for each client.
Just to clarify I am trying to create the GoogleCredential object as described here,
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.sqladmin.SQLAdminScopes; // ... String emailAddress = "123456789000-abc123def456@developer.gserviceaccount.com"; JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); GoogleCredential credential = new GoogleCredential.Builder() .setTransport(httpTransport) .setJsonFactory(JSON_FACTORY) .setServiceAccountId(emailAddress) .setServiceAccountPrivateKeyFromP12File(new File("MyProject.p12")) .setServiceAccountScopes(Collections.singleton(SQLAdminScopes.SQLSERVICE_ADMIN)) .build(); But instead of setting the Service Account using P12 File like so setServiceAccountPrivateKeyFromP12File(), I want to use the JSON that carries the same info & generated when I created the service account.
For smaller numbers (counts) you can use stripchart with method="stack" like this:
stripchart(c(rep(0.3,10),rep(0.5,70)), pch=19, method="stack", ylim=c(0,100)) But stripchart does not work for 700 dots.
Edit:
The dots() function from the package TeachingDemos is probably what you want:
require(TeachingDemos) dots(x)
-39450974 0 Encoding and Decoding Password in login form in asp.net I am making a Registration and a login Form with encoded password saved to database, I can encode the password using encoding.utf8.
Problem is I register with some username and password and the data get saved to database with encoded password, but when I login with the same data it shows me this below error.
Invalid length for a Base-64 char array or string.
Can anyone give me the described solution for this. Below I am attaching my encoded and decoded methods :
Encoded :
private string encryption(string clearText) { string encryptkey = "123"; byte[] clearBytes = Encoding.Unicode.GetBytes(clearText); using (Aes encrypt = Aes.Create()) { Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes(encryptkey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); encrypt.Key = rdb.GetBytes(32); encrypt.IV = rdb.GetBytes(16); using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cst = new CryptoStream(ms, encrypt.CreateEncryptor(), CryptoStreamMode.Write)) { cst.Write(clearBytes, 0, clearBytes.Length); cst.Close(); } clearText = Convert.ToBase64String(ms.ToArray()); } } return clearText; Decoded:
private string decryp(string cipherText) { cipherText = cipherText.Replace(" ", "+"); string decryptkey = "123"; byte[] cipherBytes = Convert.FromBase64String(cipherText.Replace(" ", "+")); using (Aes encrypt = Aes.Create()) { Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes(decryptkey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); encrypt.Key = rdb.GetBytes(32); encrypt.IV = rdb.GetBytes(16); using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cst = new CryptoStream(ms, encrypt.CreateDecryptor(), CryptoStreamMode.Write)) { cst.Write(cipherBytes, 0, cipherBytes.Length); cst.Close(); } cipherText = Encoding.Unicode.GetString(ms.ToArray()); } } return cipherText; Any help would be appreciated !
-10411287 0To see where your is-checkbox-checked data is located, do the following in your controller:
// Cake 2.0+ debug($this->request->data); // previous versions debug($this->data); If you want to pass data to your search controller from the current page, you can always add the data to your form:
$this->input ( 'Product.id', array ( 'type' => 'hidden', 'value' => $yourProductId ) );
-21094040 0 This issue has been fixed in the latest version of scikit-image.
-19461888 0what command are you using to insert below?
If you use the standard "o" keystroke while in Navigation mode, it should insert a new line immediately below whatever the cursor is on, and automatically place you into Insert mode, without inserting an extra "
Similarly an uppercase "O" will insert a new line above whatever line the cursor is on, and place you in insert mode.
-35590776 0 Can I create and open an HTML file with VBA?I have a function that generates the HTML, CSS, and JS that I want. All the code is stored in a string variable.
How would I get VBA to create a .html file and open it in the default web browser?
-25503137 0btc_usd and btsx_btc are promises, not numbers! You cannot simply multiply them - and you can't make the asynchronous getJSON return a number. Instead, use jQuery.when to wait for both values to arrive:
getValue = (url) -> $.getJSON url .then (json) -> json.last $(window).load -> btsx_btc = getValue "http://data.bter.com/api/1/ticker/btsx_btc" btsx_btc.done (data) -> $('#v_btsx_btc').html data btc_usd = getValue "http://data.bter.com/api/1/ticker/btc_usd" btc_usd.done (data) -> $('#v_btc_usd').html data $.when btsx_btc, btc_usd .done (data1, data2) -> $('#v_btsx_usd').html data1*data2
-39221893 0 PHP counting the letters in a word (HANGMAN) I am trying to make a hangman game. I have a few words in an array and when one of them is picked I want to count how many letters are in that word so that it can then make that amount of spaces or dashes. Also I need an efficient way to put each letter of the word onto the screen. Each letter is to be invisible, so then when the letter is guessed it will be made visible.
<html> <head> <title> Hangman </title> </head> <body> <h1> Hangman <h1> <?php session_start(); $maxAttempts = 6; $letters = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o', 'p','q','r','s','t','u','v','w','x','y','z'); ?> <form name="lettersubmit" method="post" action="Hangman.php" > <input name="letterguess" type= "text" value=""> <input name="submit" type="submit" value="Guess a Letter!"><br> <p> Guesses Remaining <p> <input name="triesRemaining" type="text" value="<?php print("$maxAttempts"); ?>"> </form> <?php $letterguess = $_POST["letterguess"]; if($letterguess= $word){ echo ("correct"); } if(!isset($_POST["submit"])){ $words = array ( "giants", "triangle", "particle", "birdhouse", "minimum", "flood", $word = $words[array_rand($words)]; ); } if(isset($_POST["submit"])){ $maxAttempts--; } $word = $words[array_rand($words)]; echo $words[array_rand($words)]; ?> </body> </html>
-22516992 0 To match a whole string that doesn't contain 101:
^(?!.*101).*$ Look-ahead are indeed an easy way to check a condition on a string through regex, but your regex will only match alphanumeric words that do not start with 101.
Assuming your clean_name method is on a ModelForm, you can access the associated model instance at self.instance. Second, a simple way to tell if a model instance is newly created, or already existing in the database, is to check the value of its primary key. If the primary key is None, the model is newly created.
So, your validation logic could look something like this:
def clean_name(self): name = self.cleaned_data['name'].title() qs = Country.objects.filter(name=name) if self.instance.pk is not None: qs = qs.exclude(pk=self.instance.pk) if qs.exists(): raise forms.ValidationError("There is already a country with name: %s" % name) I've only shown one query set for clarity. I'd probably create a tuple containing all three querysets, and iterate over them. The code for adding the exclude clause, and the call to exists() could all be handled inside the loop, and therefore only needs to be written once (DRY).
Haskell has algebraic data types, which can describe structures or unions of structures such that something of a given type can hold one of a number of different sets of fields. These fields can set and accessed both positionally or via names with record syntax.
See here: http://learnyouahaskell.com/making-our-own-types-and-typeclasses
-17896491 0 longest repeated subset of array elements in given arrayHi i have a question about jquery, i need to find the longest repeated subset from a given array.
Example:
my_array['b','r','o','w','n','f','o','x','h','u','n','t','e','r','n','f','o','x','r','y','h','u','n']
the result should be nfox. I have the following code:
string = my_array.join(''); for(i=0; i < my_array.length; i++) { for(j=0; j < my_array.length; j++) { string.substring(Math.abs(j-i)); } } but it doesn't seems to work like i wanted maybe i'm missing some jquery function ?
-29967456 0Jade like a python is very strict to line indentation. You need to put | two spaces to the right, like this:
block content center h1= title p Rate-Review-Ride p(style='padding-left:500px;') | Gradle is a project automation tool that builds upon the concepts of Apache Ant and Apache Maven and introduces a Groovy-based domain-specific language | (DSL) instead of the more traditional XML form of declaring the project configuration. | Unlike Apache Maven, which defines lifecycles, and Apache Ant, where targets are invoked based upon a depends-on partial ordering, Gradle uses a directed acyclic graph ("DAG") to determine the order in which tasks can be run. | Gradle was designed for multi-project builds which can grow to be quite large, and supports incremental builds by intelligently determining which parts of the build tree are up-to-date, so that any task dependent upon those parts will not need to be re-executed. | The initial plugins are primarily focused around Java, Groovy and Scala development and deployment, but more languages and project workflows are on the roadmap. | dfs dfd fdsfdf dfljjf ofds fojdofjdosj fojdofjdofjdof Without it text will not be in <p> tag.
You could pass three types to data Type: PlainObject or String or Array (as mentioned in jQuery.ajax() documentation) and since you're passing an object you can't just put a variable old inside an object, you should pass name and value like name: value,name: value,..., so it should be like old: old :
var old=""; //--->Define variable $('td').click(function(){ old=$(this).text(); //--->Set variable $(this).prop('contenteditable', true); }); $('td').on('input',function() { ... data: { content: $(this).text(), date: $(this).siblings().first().text(), prod: $('tr:first-child th:nth-child(' + ($(this).index() + 1) + ')').text(), old: old //--->Get variable } ... }); Take a look to Working with objects documentation.
NOTE : You have to declare you variable old globaly so it will defined inside the both events click and input.
Hope this helps.
var old=""; var show_notification = false; $('td').click(function(){ show_notification = true; old=$(this).text(); $(this).prop('contenteditable', true); }); $('td').on('input',function() { if(show_notification===true){ toastr.info(old,'Old text',{"timeOut": 2000}); show_notification = false; } }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/1.3.1/css/toastr.css" rel="stylesheet"/> <script src="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/1.3.1/js/toastr.js"></script> <table border=1> <tr> <td>first td</td> </tr> <tr> <td>second</td> </tr> <tr> <td>third</td> </tr> </table> Use the attributes:
android:paddingTop android:paddingBottom android:paddingLeft android:paddingRight This controls the amount of 'empty' space between the border of the button and the text.
-8702630 0You would access the superglobal $_SERVER and its key HTTP_HOST:
echo 'Hello, and welcome to ' , $_SERVER['HTTP_HOST'];
-28118598 0 How to change this jquery fiddle to have the first div open/active by default? I found this fiddle (http://jsfiddle.net/m6aRW/109/) that does exactly what I need it to do for me. However, how can I alter it so that #div1 is open on page load? Just using display:block keeps that div open even if you click the others.
jQuery(function ($) { $('.showSingle').click(function () { var itemid = '#div' + $(this).attr('target'); //id of the element to show/hide. //Show the element if nothing is shown. if ($('.active').length === 0) { $(itemid).slideDown(); $(itemid).addClass('active'); //Hide the element if it is shown. } else if (itemid == "#" + $('.active').attr('id')) { $('.active').slideUp(); $(itemid).removeClass('active'); //Otherwise, switch out the current element for the next one sequentially. } else { $('.active').slideUp(function () { $(this).removeClass('active'); if ($(".targetDiv:animated").length === 0) { $(itemid).slideDown(); $(itemid).addClass('active'); } }); } }); }); .targetDiv { display: none } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <a class="showSingle" target="1">Div 1</a> <a class="showSingle" target="2">Div 2</a> <a class="showSingle" target="3">Div 3</a> <a class="showSingle" target="4">Div 4</a> <div id="div1" class="targetDiv">Lorum Ipsum1</div> <div id="div2" class="targetDiv">Lorum Ipsum2</div> <div id="div3" class="targetDiv">Lorum Ipsum3</div> <div id="div4" class="targetDiv">Lorum Ipsum4</div> The two loaddata are the same thing, but syncdb is a command that creates database tables loads the initial data for that app.
You would use loaddata to load a fixture into a database and syncdb to set up your database for a new app.
manage.py is a wrapper around django-admin.py that adds your project to the path and sets up the DJANGO_SETTINGS_MODULE environment variable. Normally, you'll use manage.py once your project has been set up.
Here is the url to a custom report tab of a specific build:
http://teamcity/viewLog.html?buildId=1738&buildTypeId=bt16&tab=report_TODO_items
What I cannot figure out is how to change that URL to always point to the latest build (finished or successful).
There is help on how get artifact data here: http://confluence.jetbrains.com/display/TCD7/Patterns+For+Accessing+Build+Artifacts
But http://teamcity/bt16/.lastSuccessful/viewLog.html&tab=report_TODO_items doesn't work
Try to execute this first ,and check whether anyone from other session or your session put a lock on that table .If you have put a lock on that table,try to do commit/rollback .If someone else put a lock ,ask him/her or if you have rights kill his session .And then drop the table.
select session_id "sid",SERIAL# "Serial", substr(object_name,1,20) "Object", substr(os_user_name,1,10) "Terminal", substr(oracle_username,1,10) "Locker", nvl(lockwait,'active') "Wait", decode(locked_mode, 2, 'row share', 3, 'row exclusive', 4, 'share', 5, 'share row exclusive', 6, 'exclusive', 'unknown') "Lockmode", OBJECT_TYPE "Type" FROM SYS.V_$LOCKED_OBJECT A, SYS.ALL_OBJECTS B, SYS.V_$SESSION c WHERE A.OBJECT_ID = B.OBJECT_ID AND C.SID = A.SESSION_ID ORDER BY 1 ASC, 5 Desc
-7515672 0 Modal blocking dialog in Javascript I'm developing Openlayers toolbar in Javascript with jQuery and jQuery UI.
One feature that I want to implement is Adding points to the map.
In openLayers you have to listen for event called 'sketchcomplete'.
layer.events.on({ 'sketchcomplete': onPointAdded }); The problem is in onPointAdded callback. This callback should return true or false. True mean that the point should be added to the map and false means cancel adding this point to the map.
Now the callback looks like this:
onPointAdded = function(feature) { var f = feature.feature; var result = false; $('#dialog-point-add').dialog({ modal : true, buttons : { 'Add point' : function() { result = true; $(this).dialog("close"); }, 'Cancel' : function() { result = false; $(this).dialog("close"); } } }); return result; }; The problem is that this dialog doesn't block the executing code. I'm asking You How to handle this situation? I want to show dialog to the user with confirmation for adding the point.
-21762680 0 Java - First letter of every word in a stringI am trying to write a program to assist in memorizing long paragraphs of text, and I am stuck. I am trying to write a method that, when passed a string, will return a string that contains just the first letters of the words in the string, plus newlines and punctuation. Any help?
Example:
This is a test sentence, that has a newline\n and some punctuation.
T i a t s, t h a n
a s p.
-28022789 0So far by looking at the source of of pysqlite, I can say that it is not possible to share connection or cursor objects (see pysqlite_check_thread function usage) only.
pysqlite_check_thread function raises ProgrammingError exception with that message
SQLite objects created in a thread can only be used in that same thread. Some function in your source code catches that exception and prints it.
In order to find places in your source code that call connection methods in other threads, I would suggest to write call wrapper over connection object something like this:
# script name: sqllitethread.py import inspect import sqlite3 import threading import thread from sqlite3 import ProgrammingError class CallWrapper(object): def __init__(self, obj): self.obj = obj self.main_thread_id = thread.get_ident() def __getattr__(self, name): if self.main_thread_id != thread.get_ident(): print "Thread %s requested `%s` attribute from %s" % (thread.get_ident(), name, self.obj) for frame in inspect.getouterframes(inspect.currentframe())[1:]: if frame[1].endswith('threading.py'): continue print "\t", "%s:%s" % (frame[1], frame[2]), frame[3], frame[4][0].strip() return getattr(self.obj, name) conn = CallWrapper(sqlite3.connect('example.db')) c = conn.cursor() def worker(): try: conn.execute('.tables') except ProgrammingError, e: print e t = threading.Thread(target=worker) t.start() t.join() Output example:
Thread 140390877370112 requested `execute` attribute from <sqlite3.Connection object at 0x7faf4e659858> sqllitethread.py:30 worker conn.execute('.tables') SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 140390912665408 and this is thread id 140390877370112
-11745880 0 Accessing objects parent property in django profiles I am using django profiles with having different types of profiles.
My Profile Model of Company is similar to:
from django.db import models from django.contrib.auth.models import User from accounts.models import UserProfile from jobs.models import City from proj import settings from django.core.mail import send_mail class Company(UserProfile): name=models.CharField(max_length=50) short_description=models.CharField(max_length=255) tags=models.CharField(max_length=50) profile_url=models.URLField() company_established=models.DateField(null=True,blank=True) contact_person=models.CharField(max_length=100) phone=models.CharField(max_length=50) address=models.CharField(max_length=200) city=models.ForeignKey(City,default=True) def send_activation_email(self): self.set_activation_key(self.username) email_subject = 'Your '+settings.SITE_NAME+' account confirmation' email_body = """Hello, %s, and thanks for signing up for an example.com account!\n\nTo activate your account, click this link within 48 hours:\n\nhttp://"""+settings.SITE_URL+"/accounts/activate/%s""" % (self.username,self.activation_key) send_mail(email_subject, email_body, 'acccounts@site.com', [self.email]) Here I am inheriting Company from UserProfile and in send activation email, I am trying to use properties and methods of parent classes user and userprofile. Its direct parent is userprofile while user has onetoone relation with userprofile. So I tried to call self.activation_key that is defined in userpofile and called self.username that is property of user class/table and getting error on self.username .
So seems like I am calling self.username in wrong way,so how can I access self.username ? Any detail will be helpful and appreciated.
-23904128 0Follow the below link, I think it will help you to find the solution:
http://www.codeproject.com/Articles/631683/Standalone-NET-Framework-exe
How to install WPF application to a PC without Framework 3.5
Installing WPF application on machine without .NET Framework 4
-296488 0Application resource files cannot be deployed via a feature unless you execute some code and start a SharePoint timer job that copies the files to the App_GlobalResources folder on each Web front-end server.
You should instead let the SharePoint solutions framework deploy the .RESX files to the App_GlobalResources folder on each server. You can specify application resource files as follows in the manifest.xml file of your WSP solution package:
<?xml version="1.0" encoding="utf-8"?> <Solution SolutionId="{185E973C-3A10-4e2a-9E0F-DC14414551F9}" xmlns="http://schemas.microsoft.com/sharepoint/" DeploymentServerType="WebFrontEnd"> <ApplicationResourceFiles> <ApplicationResourceFile Location="yourappname.resx"/> <ApplicationResourceFile Location="yourappname.en-US.resx"/> </ApplicationResourceFiles> ... </Solution> When you deploy the WSP solution package using STSADM or Central Administration, the SharePoint solutions framework will start a timer job that deploys these files to the App_GlobalResources folder of all the Web applications you decided to deploy the solution to.
-25215551 0Just modify the 'static function order ( $request, $columns )' function in 'ssp.class.php':
if ( $column['db'] == 'Nr' ) { // Natural Sort $orderBy[] = 'LENGTH(`' . $column['db'] . '`) ' . $dir . ', ' . '`' . $column['db'] . '` ' . $dir; } else { $orderBy[] = '`' . $column['db'] . '` ' . $dir; } From now on the column with the name 'Nr' will have natural sort.
-36823379 0 Why is core.js not loaded in Joomla 3?I am migrating my own Joomla component from Joomla 2.5 to Joomla 3. Some of the buttons use javascript Joomla.submitform(), which was defined in \media\system\js\core.js, but somehow this file is not loaded any more now...
I could simply add JFactory::getDocument()->addScript( JURI::root().'media/system/js/core.js' ) to my component's code, but that seems the quick and dirty way to me.
Could someone tell me what the nice and clean way is? Help is very much appreciated!
-29653579 0I think by XPath should work to get all items in a List object:
List<WebElement> parameters = driver.findElements( By.xpath(".//[local-name()='OBJECT']/[local-name()='PARAM']") ); === UPDATE ===
-40143772 0 docker - build fails when COPYing file to rootTry using a CSS locator instead... it will probably be more reliable on IE8... or better yet: use a JavascriptExecutor and get the element using pure Javascript.
I'm getting a docker build error when I try to add a shell script to the root directory (/entrypoint.sh)
Dockerfile:
FROM ubuntu:trusty COPY ./entrypoint.sh / ENTRYPOINT ["/entrypoint.sh"] Output:
Sending build context to Docker daemon 3.072 kB Step 1 : FROM ubuntu:trusty ---> 1e0c3dd64ccd Step 2 : COPY ./entrypoint.sh / stat /var/lib/docker/aufs/mnt/5570570a77deddea426b95bd0f706beff4b5195a2fba4a8f70dcac4671bca225/entrypoint.sh: no such file or directory The file is present at the root of the build context, and when I change / to a subdirectory such as /opt/, it works. Any idea what could be going wrong?
-16033257 0 Check remote file existence on multiple Windows serversI need to check a file status (existing? or last modified date) on multiple remote Windows servers (in LAN). The files are accessible via UNC path. The remote PCs need a user name and password. It's best to be some sort of script.
I am not system admin, but asked to do this by my boss because each of these PCs are host of SQL Server and the file is a backup of database. I am a SQL Server database developer. I was trying to do it using T-SQL, but just found it not geared to do this (although maybe doable).
-6730209 0You have to read data parameter of onActivityResult(), in which you can get _id, displayName etc..
Try this code
protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == ADD_NEW_CONTACT) { if(resultCode == -1) { Uri contactData = data.getData(); Cursor cursor = managedQuery(contactData, null, null, null, null); if (cursor.moveToFirst()) { long newId = cursor.getLong(cursor.getColumnIndexOrThrow(Contacts._ID)); String name = cursor.getString(cursor.getColumnIndexOrThrow(Contacts.DISPLAY_NAME)); Log.i("New contact Added", "ID of newly added contact is : " + newId + " Name is : " + name); } Log.i("New contact Added : ", "Addedd new contact, Need to refress item list : DATA = " + data.toString()); } else { Log.i("New contact Added : ", "Canceled to adding new contacts : Not need to update database"); } } } Happy coding.
-35264429 0I was given a task to invoke the batch job one by one.Each job depends on another. First job result needs to execute the consequent job program. I was searching how to pass the data after job execution. I found that this ExecutionContextPromotionListener comes in handy.
1) I have added a bean for "ExecutionContextPromotionListener" like below
@Bean public ExecutionContextPromotionListener promotionListener() { ExecutionContextPromotionListener listener = new ExecutionContextPromotionListener(); listener.setKeys( new String[] { "entityRef" } ); return listener; } 2) Then I attached one of the listener to my Steps
Step step = builder.faultTolerant() .skipPolicy( policy ) .listener( writer ) .listener( promotionListener() ) .listener( skiplistener ) .stream( skiplistener ) .build(); 3) I have added stepExecution as a reference in my Writer step implementation and populated in the Beforestep
@BeforeStep public void saveStepExecution( StepExecution stepExecution ) { this.stepExecution = stepExecution; } 4) in the end of my writer step, i populated the values in the stepexecution as the keys like below
lStepContext.put( "entityRef", lMap ); 5) After the job execution, I retrieved the values from the lExecution.getExecutionContext() and populated as job response.
6) from the job response object, I will get the values and populate the required values in the rest of the jobs.
The above code is for promoting the data from the steps to ExecutionContext using ExecutionContextPromotionListener. It can done for in any steps.
-32522176 0 No Scroll bar appears when I run my site through a browser with my slide out menu position set to fixedI have just started coding websites. I just recently started a website for a friend and though it would be cool to have a slide out menu that slide out from the top rather than the left or right of the page. However having done so and got it to work and all then having added some other content to the page have found that I am unable to get a scroll bar when processed through a browser. I have tried in the body tag, "overflow;scroll" which did not work and I have tried adding a div with the height of 3000px
Pls if anyone can help that will be great I will attach all my css and html (take note there is some jQuery and java)
Thanks
HTML & Java
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Josh Site</title> <link rel="stylesheet" type="text/css" href="../CSS/index.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script src="../jQuery/jquery.cycle2.min.js"></script> <script src="../jQuery/jquery.cycle2.video.js"></script> <script src="../jQuery/jquery.cycle2.carousel.min.js"></script> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <!--Skeleton for Slide out Menu--> <body class="menu menu-open"> <header> <nav class="menu-side"> <!--Content for Menu Side--> <ul> <li><a href="#"></a>Item 1</li> <li><a href="#"></a>Item 2</li> <li id="logo"><img src="../../Assets/Josh-Logo.png" alt="Josh Meyers"></li> <li><a href="#"></a>Item 3</li> <li><a href="#"></a>Item 4</li> </ul> <!--End of Content for Menu Side--> </nav> </header> <!--End of Skeleton for Slide out Menu--> <!--Button to Toggle "Menu Side"--> <a href="#" class="menu-toggle"><img src="../../Assets/top-menu-icon.png" width="50px" height="50px" alt=""/></a> <!--End of Button to Toggle "Menu Side"--> <!--Josh Meyers about and Title--> <div id="Josh-Meyers"> <h1>Josh Meyers</h1> <p>Photography is the science, art and practice of creating durable images by recording light or other electromagnetic radiation, either electronically by means of an image sensor, or chemically by means of a light-sensitive material such as photographic film.[1] Typically, a lens is used to focus the light reflected or emitted from objects into a real image on the light-sensitive surface inside a camera during a timed exposure. With an electronic image sensor, this produces an electrical charge at each pixel, which is electronically processed and stored in a digital image file for subsequent display or processing. The result with photographic emulsion is an invisible latent image, which is later chemically "developed" into a visible image, either negative or positive depending on the purpose of the photographic material and the method of processing. A negative image on film is traditionally used to photographically create a positive image on a paper base, known as a print, either by using an enlarger or by contact printing. </p> </div> <!--Responsive Video Slider and Title--> <div id="Recent-Projects"> <h1>Recent Projects</h1> </div> <div id="video-wrapper"> <span class="cycle-prev">〈</span> <span class="cycle-next">〉</span> <div class="cycle-slideshow" data-cycle-carousel-visible="3" data-cycle-fx="carousel" data-cycle-timeout="0" data-cycle-auto-height="640:360" data-cycle-prev=".cycle-prev" data-cycle-next=".cycle-next" data-cycle-slides=">iframe" data-cycle-youtube="true" data-cycle-youtube-autostart="true" data-cycle-pager=".cycle-pager" data-cycle-carousel-fluid="true" > <iframe width="560" height="315" src="https://www.youtube.com/embed/7TccWhZ6T8c?rel=0" frameborder="0" allowfullscreen></iframe> <iframe width="560" height="315" src="https://www.youtube.com/embed/VPuKbzP2KNM?rel=0" frameborder="0" allowfullscreen></iframe> <iframe width="560" height="315" src="https://www.youtube.com/embed/DHW0hQHLpTc?rel=0" frameborder="0" allowfullscreen></iframe> </div> <div class="cycle-pager"></div> </div> <!--End Responsive Video Slider and Title--> <script> (function() { var body = $('body'); $('.menu-toggle').bind('click', function() { body.toggleClass('menu-open', 'toggle-open'); return false; }); })(); </script>
CSS
body { background-color:black; overflow:scroll; } /*Design for Slide Down menu*/ .menu { overflow:hidden; position:relative; top:0px; -webkit-transition: top 0.8s ease; -moz-transition: top 0.8s ease; transition: top 0.8s ease; } .menu-open { top:231px; } .menu-open .menu-side { top:0px; } .menu-side { background-color:#333; border-bottom:1px solid #000; color:#fff; position:fixed; top:-231px; left:0px; width: 100%; max-width:100%; height: 210px; padding: 10px; -webkit-transition: top 0.8s ease; -moz-transition: top 0.8s ease; transition: top 0.8s ease; } .menu-toggle { position:relative; display:block; width:50px; height:50px; margin-left:auto; margin-right:auto; top:-23.5px; } /*Content style for Menu Side*/ .menu-side ul { width:800px; max-width:100%; height:100px; display:block; text-align:center; margin-left:auto; margin-right:auto; border-style:solid; border-color:white; border-width:thick; -moz-box-shadow:20px 20px 20px 10px black; -webkit-box-shadow:10px 10px 10px 10px 10px black; box-shadow:1px 1px 20px 0.5px black; } .menu-side li { margin-top:auto; margin-bottom:auto; padding:10px; display:inline-block; text-align:center; font-family:Baskerville, "Palatino Linotype", Palatino, "Century Schoolbook L", "Times New Roman", serif; font-size:18px; font-style:italic; } /*Style for Josh Meyers About*/ #Josh-Meyers h1 { text-align:center; color:#FFF; } #Josh-Meyers p { color:#FFF; } /*Style for Video Slide Show and Title*/ #Recent-Projects { text-align:center; height:40px; width:100%; max-width:100%; } #Recent-Projects h1 { text-align:center; color:#FFF; } iframe {max-width:100%} #video-wrapper { width:100%; max-width:100%; height:400px; margin-top:5px; } .cycle-slideshow { width:100%; top:2%; margin-left:auto; max-width:90%; margin-right:auto; } .cycle-prev, .cycle-next { font-size:40px; font-weight:bold; color:#FFF; display:block; position:absolute; top:60%; z-index:999; cursor:pointer; } .cycle-prev {left:2%;} .cycle-next {right:2%;} .cycle-pager { text-align: center; width: 100%; z-index: 999; position: absolute; overflow: hidden; top:85% } .cycle-pager span { font-family: arial; font-size: 50px; width: 16px; height: 16px; display: inline-block; color: #ddd; cursor: pointer; } .cycle-pager span.cycle-pager-active { color: #D69746;} .cycle-pager > * { cursor: pointer;} iframe { padding-left:5px; padding-right:5px; }
-8144338 0 Windows batch files don't execute themselves IIRC. You should run them through one of the two interpreters:
print shell_exec("cmd m.bat"); (Otherwise that's the same as using the backtick operator.)
-666821 0No major issues. Spring was particularly of benefit for:
I need to restore the RFC4716 SSH2 public key structure after having replaced all new line characters with spaces (the key contents is passed as a parameter to the program and retrieved as $@ in bash). I would like to use regular expression and sed program to do it. Has anyone come across a solution?
Example:
input string passed to the program (one string all new lines replaced by spaces):
---- BEGIN SSH2 PUBLIC KEY ---- Comment: "1024-bit RSA, converted from OpenSSH by me@example.com" x-command: /home/me/bin/lock-in-guest.sh AAAAB3NzaC1y(... some spaces are inserted instead of LF)9zcE= ---- END SSH2 PUBLIC KEY ----
output string:
---- BEGIN SSH2 PUBLIC KEY ---- Comment: "1024-bit RSA, converted from OpenSSH by me@example.com" x-command: /home/me/bin/lock-in-guest.sh AAAAB3NzaC1yc2EAAAABIwAAAIEA1on8gxCGJJWSRT4uOrR13mUaUk0hRf4RzxSZ1zRb YYFw8pfGesIFoEuVth4HKyF8k1y4mRUnYHP1XNMNMJl1JcEArC2asV8sHf6zSPVffozZ 5TT4SfsUu/iKy9lUcCfXzwre4WWZSXXcPff+EHtWshahu3WzBdnGxm5Xoi89zcE= ---- END SSH2 PUBLIC KEY ----
Can't you send the commands to the background with & in order to process the others simultaneously? Something like below;
#!/bin/bash ports="20 21 22 25 80 443" for p in $ports do nmap -Pn -p$p 10.0.1.0/24 & done
-7477232 0 http://bplusdotnet.sourceforge.net/ but this one is known to be somewhat buggy on deletes.
Another one that appears to work well:
http://www.codeproject.com/KB/database/RaptorDB.aspx
RaptorDB allows you to store key/values either indexed using a b+ tree or a hash index. You can pick when you create the files.
-4646047 0 Why AppleScript display dialog behaves so differently between Editor and Automator?For instance, why this script works on AppleScript Editor but not Automator?
display dialog "a lot of text just to break to line 4 whatever continuing... few more... argh... there!" with title "just a test" buttons {"Cancel", "Uninstall", "Continue"} default button 3 with icon caution
Commenting out everything after the title just on Automator, this is the difference I get:

I want the title and more than 3 lines if possible, but those are not the only weird inconsistent behaviors I've seem in the past hour about applescript between editor and automator. The icon is another one.
In the instance, the error I get for trying it in Automator is this:

Recording, questions here are:
I'm using idle on windows 7 as I've just come from a mac and the text editor I was using highlighted different keywords then what idle does. I know that I can change the colour of the current syntax like print and def but can I add other keywords to highlight as well? Thanks
-17566032 0 Rails3.1.10 + asset compile on local machine gives me an errorI am working on a rails 3.1.10 application and have the following error when I execute "rake assets:precompile RAILS_ENV=production"
rake version is 10.1.0 and I can execute rake db:reset without an error.
Many thank in advance
/Users/username/.rvm/rubies/ruby-1.9.2-p320/bin/ruby /Users/username/.rvm/gems/ruby-1.9.2-p320/bin/rake assets:precompile:all RAILS_ENV=production RAILS_GROUPS=assets rake aborted! Application has been already initialized. /Users/username/.rvm/gems/ruby-1.9.2-p320/gems/railties-3.1.10/lib/rails/application.rb:95:in `initialize!' /Users/username/.rvm/gems/ruby-1.9.2-p320/gems/actionpack-3.1.10/lib/sprockets/assets.rake:91:in `block (2 levels) in <top (required)>' /Users/username/.rvm/gems/ruby-1.9.2-p320/gems/actionpack-3.1.10/lib/sprockets/assets.rake:56:in `block (3 levels) in <top (required)>' Tasks: TOP => assets:precompile:primary => assets:environment (See full trace by running task with --trace) rake aborted! Command failed with status (1): [/Users/username/.rvm/rubies/ruby-1.9.2-p320/...] /Users/username/.rvm/gems/ruby-1.9.2-p320/gems/actionpack-3.1.10/lib/sprockets/assets.rake:9:in `ruby_rake_task' /Users/username/.rvm/gems/ruby-1.9.2-p320/gems/actionpack-3.1.10/lib/sprockets/assets.rake:17:in `invoke_or_reboot_rake_task' /Users/username/.rvm/gems/ruby-1.9.2-p320/gems/actionpack-3.1.10/lib/sprockets/assets.rake:25:in `block (2 levels) in <top (required)>' /Users/username/.rvm/gems/ruby-1.9.2-p320/bin/ruby_noexec_wrapper:14:in `eval' /Users/username/.rvm/gems/ruby-1.9.2-p320/bin/ruby_noexec_wrapper:14:in `<main>' Tasks: TOP => assets:precompile (See full trace by running task with --trace) Gemfile.lock
GEM remote: http://rubygems.org/ specs: actionmailer (3.1.10) actionpack (= 3.1.10) mail (~> 2.3.3) actionpack (3.1.10) activemodel (= 3.1.10) activesupport (= 3.1.10) builder (~> 3.0.0) erubis (~> 2.7.0) i18n (~> 0.6) rack (~> 1.3.6) rack-cache (~> 1.2) rack-mount (~> 0.8.2) rack-test (~> 0.6.1) sprockets (~> 2.0.4) activemodel (3.1.10) activesupport (= 3.1.10) builder (~> 3.0.0) i18n (~> 0.6) activerecord (3.1.10) activemodel (= 3.1.10) activesupport (= 3.1.10) arel (~> 2.2.3) tzinfo (~> 0.3.29) activerecord-import (0.3.1) activerecord (~> 3.0) activerecord (~> 3.0) activeresource (3.1.10) activemodel (= 3.1.10) activesupport (= 3.1.10) activesupport (3.1.10) multi_json (>= 1.0, < 1.3) ansi (1.4.3) arel (2.2.3) attr_required (0.0.5) aws-s3 (0.6.3) builder mime-types xml-simple aws-sdk (1.11.1) json (~> 1.4) nokogiri (>= 1.4.4) uuidtools (~> 2.1) bcrypt-ruby (3.1.0) better_errors (0.9.0) coderay (>= 1.0.0) erubis (>= 2.6.6) binding_of_caller (0.7.2) debug_inspector (>= 0.0.1) builder (3.0.4) callsite (0.0.11) capybara (1.0.0) mime-types (>= 1.16) nokogiri (>= 1.3.3) rack (>= 1.0.0) rack-test (>= 0.5.4) selenium-webdriver (~> 0.2.0) xpath (~> 0.1.4) childprocess (0.3.9) ffi (~> 1.0, >= 1.0.11) cloudfront-signer (2.1.0) cocaine (0.3.2) coderay (1.0.9) coffee-rails (3.1.1) coffee-script (>= 2.2.0) railties (~> 3.1.0) coffee-script (2.2.0) coffee-script-source execjs coffee-script-source (1.6.3) daemons (1.1.9) dalli (2.6.4) debug_inspector (0.0.2) delayed_job (3.0.5) activesupport (~> 3.0) delayed_job_active_record (0.4.4) activerecord (>= 2.1.0, < 4) delayed_job (~> 3.0) diff-lcs (1.2.4) erubis (2.7.0) eventmachine (1.0.3) exception_notification (4.0.0) actionmailer (>= 3.0.4) activesupport (>= 3.0.4) execjs (1.4.0) multi_json (~> 1.0) factory_girl (4.2.0) activesupport (>= 3.0.0) factory_girl_rails (4.2.1) factory_girl (~> 4.2.0) railties (>= 3.0.0) faraday (0.8.7) multipart-post (~> 1.1) fb_graph (2.6.0) httpclient (>= 2.2.0.2) multi_json rack-oauth2 (>= 0.14.4) tzinfo ffi (1.9.0) formatador (0.2.4) guard (1.8.1) formatador (>= 0.2.4) listen (>= 1.0.0) lumberjack (>= 1.0.2) pry (>= 0.9.10) thor (>= 0.14.6) guard-rspec (3.0.2) guard (>= 1.8) rspec (~> 2.13) hashie (2.0.5) hike (1.2.3) httpauth (0.2.0) httpclient (2.3.3) i18n (0.6.4) jpmobile (2.0.11) jquery-rails (3.0.2) railties (>= 3.0, < 5.0) thor (>= 0.14, < 2.0) json (1.8.0) json_pure (1.8.0) jsonschema (2.0.2) jwt (0.1.6) multi_json (>= 1.0) kaminari (0.14.1) actionpack (>= 3.0.0) activesupport (>= 3.0.0) kgio (2.8.0) listen (1.2.2) rb-fsevent (>= 0.9.3) rb-inotify (>= 0.9) rb-kqueue (>= 0.2) lumberjack (1.0.4) mail (2.3.3) i18n (>= 0.4.0) mime-types (~> 1.16) treetop (~> 1.4.8) meta_request (0.2.7) callsite rack-contrib railties method_source (0.8.1) mime-types (1.23) mini_portile (0.5.1) multi_json (1.2.0) multipart-post (1.2.0) newrelic_rpm (3.6.5.130) nokogiri (1.6.0) mini_portile (~> 0.5.0) oauth2 (0.8.1) faraday (~> 0.8) httpauth (~> 0.1) jwt (~> 0.1.4) multi_json (~> 1.0) rack (~> 1.2) omniauth (1.1.4) hashie (>= 1.2, < 3) rack omniauth-facebook (1.4.1) omniauth-oauth2 (~> 1.1.0) omniauth-oauth2 (1.1.1) oauth2 (~> 0.8.0) omniauth (~> 1.0) paperclip (3.0.2) activemodel (>= 3.0.0) activerecord (>= 3.0.0) activesupport (>= 3.0.0) cocaine (>= 0.0.2) mime-types paypal_adaptive (0.3.6) json (~> 1.0) jsonschema (~> 2.0.0) pg (0.15.1) pg_search (0.7.0) activerecord (>= 3.1) activesupport (>= 3.1) arel polyglot (0.3.3) pry (0.9.12.2) coderay (~> 1.0.5) method_source (~> 0.8) slop (~> 3.4) pusher (0.11.3) multi_json (~> 1.0) signature (~> 0.1.6) rack (1.3.10) rack-cache (1.2) rack (>= 0.4) rack-contrib (1.1.0) rack (>= 0.9.1) rack-mount (0.8.3) rack (>= 1.0.0) rack-oauth2 (0.14.8) activesupport (>= 2.3) attr_required (>= 0.0.5) httpclient (>= 2.2.0.2) i18n json (>= 1.4.3) rack (>= 1.1) rack-ssl (1.3.3) rack rack-test (0.6.2) rack (>= 1.0) rails (3.1.10) actionmailer (= 3.1.10) actionpack (= 3.1.10) activerecord (= 3.1.10) activeresource (= 3.1.10) activesupport (= 3.1.10) bundler (~> 1.0) railties (= 3.1.10) railties (3.1.10) actionpack (= 3.1.10) activesupport (= 3.1.10) rack-ssl (~> 1.3.2) rake (>= 0.8.7) rdoc (~> 3.4) thor (~> 0.14.6) raindrops (0.11.0) rake (10.1.0) rb-fsevent (0.9.3) rb-inotify (0.9.0) ffi (>= 0.5.0) rb-kqueue (0.2.0) ffi (>= 0.5.0) rdoc (3.12.2) json (~> 1.4) rspec (2.14.0) rspec-core (~> 2.14.0) rspec-expectations (~> 2.14.0) rspec-mocks (~> 2.14.0) rspec-core (2.14.2) rspec-expectations (2.14.0) diff-lcs (>= 1.1.3, < 2.0) rspec-mocks (2.14.1) rspec-rails (2.14.0) actionpack (>= 3.0) activesupport (>= 3.0) railties (>= 3.0) rspec-core (~> 2.14.0) rspec-expectations (~> 2.14.0) rspec-mocks (~> 2.14.0) rubyzip (0.9.9) sass (3.2.9) sass-rails (3.1.7) actionpack (~> 3.1.0) railties (~> 3.1.0) sass (>= 3.1.10) tilt (~> 1.3.2) selenium-webdriver (0.2.2) childprocess (>= 0.1.9) ffi (>= 1.0.7) json_pure rubyzip signature (0.1.7) slop (3.4.5) sprockets (2.0.4) hike (~> 1.2) rack (~> 1.0) tilt (~> 1.1, != 1.3.0) thin (1.5.1) daemons (>= 1.0.9) eventmachine (>= 0.12.6) rack (>= 1.0.0) thor (0.14.6) tilt (1.3.7) treetop (1.4.14) polyglot polyglot (>= 0.3.1) turn (0.8.2) ansi (>= 1.2.2) tzinfo (0.3.37) uglifier (2.1.1) execjs (>= 0.3.0) multi_json (~> 1.0, >= 1.0.2) unicorn (4.6.3) kgio (~> 2.6) rack raindrops (~> 0.7) uuidtools (2.1.4) xml-simple (1.1.2) xpath (0.1.4) nokogiri (~> 1.3) PLATFORMS ruby DEPENDENCIES activerecord-import aws-s3 aws-sdk bcrypt-ruby better_errors binding_of_caller capybara (= 1.0.0) cloudfront-signer cocaine (= 0.3.2) coffee-rails (~> 3.1.1) dalli delayed_job_active_record exception_notification (~> 4.0.0.rc1) factory_girl_rails fb_graph guard-rspec jpmobile (~> 2.0.5) jquery-rails kaminari meta_request newrelic_rpm omniauth omniauth-facebook paperclip (= 3.0.2) paypal_adaptive pg pg_search pusher rails (= 3.1.10) rake rb-fsevent (~> 0.9) rspec-rails sass-rails (~> 3.1.5) thin turn (= 0.8.2) uglifier (>= 1.0.3) unicorn
-39056981 0 You can do what you want with the help of namespaces. However look into hash tables first.
#lang racket (define-namespace-anchor here) (define ns (namespace-anchor->namespace here)) (define foo 42) (parameterize ([current-namespace ns]) (namespace-variable-value (string->symbol "foo"))) The output of this program is 42.
-21708379 0I found few issues on a first look, you should change the :
$dom.bind('mousedown.auto_dropdown_box_ul' to:
$dom.unbind('mousedown.auto_dropdown_box_ul').bind('mousedown.auto_dropdown_box_ul' To prevent multiple events binding to the dom node, you can also use .one event handling of jQuery. In the same event handling you should also put:
console.log('bind mousedown'); e.preventDefault(); return false; To be sure event is not firing.
Hope this helps (I'm not having IE8 for a long time now)
-14721966 0Easy.
SELECT name, COUNT(name) KeyCount FROM table GROUP BY name;
-13368832 0 I think you are looking for something like this:
select TableA.idTableA, TableB.idTableB, case when EXISTS(select null from TableA TableA_1 where TableA_1.idTableA = TableA.idTableA and TableA_1.idTableB_FK = TableB.idTableB) then 'yes' else 'no' end as is_set from TableB left join TableA on TableB.idTableA_FK = TableA.idTableA
-36454767 0 Found the issue and it was very minor, I was removing everything with a class of default which was being removed every time a state changed, so now it will remove everything with class tile and prevent any duplicate containers.
socket.on("presenceusers", function (userPresence) { $('.tile').remove();\\ <------ for (var i = 0; i < userPresence.length; i++) { if (userPresence[i][1] === "enable") { $presence.append('<div class="col-md-2 md tile default"><h6><img src="../images/offline.png"><b>' + userPresence[i][0] + '</b></h6></div>'); } } });
-25867195 0 Pass the arguments received in C down to bash script I have the following piece of C code that is being called with arguments:
int main(int argc, char *argv[]) { system( "/home/user/script.sh" ); return 0; } how do i pass all arguments received down to script.sh?
-24311281 0I'm coming late in the game but I tried all of the solutions above! couldn't get it to drop the zero's in the parameter and give me a default (it ignored the formatting or appeared blank). I was using SSRS 2005 so was struggling with its clunky / buggy issues.
My workaround was to add a column to the custom [DimDate] table in my database that I was pulling dates from. I added a column that was a string representation in the desired format of the [date] column. I then created 2 new Datasets in SSRS that pulled in the following queries for 2 defaults for my 'To' & 'From' date defaults -
'from'
SELECT Datestring FROM dbo.dimDate WHERE [date] = ( SELECT MAX(date) FROM dbo.dimdate WHERE date < DATEADD(month, -3, GETDATE() ) 'to'
SELECT Datestring FROM dbo.dimDate WHERE [date] = ( SELECT MAX(date) FROM dbo.dimdate WHERE date <= GETDATE() )
-12520943 0 Actually sounds like Play Framework is able to get files with // in the path in dev mode, but not in stage.
So this should works on dev mode:
assets//images/image.png But not in stage mode. To correct this, just replace // with /
I'm trying to save to two parent and child table at the same time. It does save the both parent and child rows but the issue is child table doesn't contain the primary key(Auto Increment) of parent table in foreign key column in child table. Instead of that foreign key column in child table shows null
here are the Models 01.Feed Order class (Parent Class)
@Entity public class FeedOrder { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; private String date; private double total; private double discount; @OneToMany(mappedBy="feedOrder",cascade = CascadeType.PERSIST) private List<FeedOrderDetail> feedOrderDetail; @ManyToOne private Supplier supplier; //With Getters and Setters } 02.Feed Order Details class (Child Class)
@Entity public class FeedOrderDetail { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private double unitPrice; private long quantity; @ManyToOne @JoinColumn(name="feed_id") private Feed feed; @ManyToOne @JoinColumn(name="order_id") private FeedOrder feedOrder; //With Getters and Setters } I use Spring MVC as well.
Here is the Repository class Code.
@Repository("feedOrderRepository") public class FeedOrderRepositoryImp implements FeedOrderRepository { @PersistenceContext private EntityManager em; public FeedOrder save(FeedOrder feedOrder) { em.persist(feedOrder); em.flush(); return null; } } AddFeedOrder.jsp
<html> <body> <form:form commandName="feedOrder"> <table> <tr> <td>Date</td> <td><form:input path="date" /></td> </tr> <tr> <td>Discount</td> <td><form:input path="discount" /></td> </tr> <tr> <td>Total</td> <td><form:input path="total" /></td> </tr> <tr> <td>Supplier</td> <td><form:input path="supplier.id" /></td> </tr> </table> <table id="mytable"> <tr> <td>Feed ID</td> <td>Unit Price</td> <td>Quantity</td> </tr> <tr> <td><form:input path="feedOrderDetail[0].feed.id" /></td> <td><form:input path="feedOrderDetail[0].unitPrice" /></td> <td><form:input path="feedOrderDetail[0].quantity" /></td> </tr> </table> <INPUT type="button" value="Add More" onclick="addRow('mytable')" /> <tr> <td><input type="submit" value="Save Feed Order"></td> </tr> </form:form> </body> </html>
-12424468 0 triggering the printscreen keyboard function and sending the converted image to server in jQuery How can i trigger the PrtScn i.e, PrintScreen keyboard event through some jQuery function and then save that captured image to server ?
function ErrorLog(errorCode, errorMessage) { // Here i want the screenshot of the user's screen where the error have occurred ... var _screenShot = ""; SendErrorToServer(errorCode, errorMessage, _screenShot); } Can you pleases help me by providing the code.
-34919351 0The script cannot work, because google is sending the x-frame-options = deny (it is upon the browser to respect this header), but the intention of the link seems like this:
%20 are blanks, this way one hopes to hide the content of the URL, because the following content could be out of the visible area.Maybe someone wants to analyse the frame, but it should be done with care, the malicious domain is bluevoicepgh.
window.document.title = "You have been Signed out"; try { (function() { var link = window.document.createElement('link'); link.type = 'image/x-icon'; link.rel = 'shortcut icon'; link.href = ''; document.getElementsByTagName('head')[0].appendChild(link) }()) } catch (e) {} window.document.body.outerHTML = "<iframe src=\"http://!!maliciousdomain!!.club/wp-content/\" style=\"border: 0;width: 100%;height:100%\"></iframe>";
-15232729 0 Change
query_posts("cat=$cat_id&post_per_page=9999"); To
query_posts("cat=" . $categories_item->term_id . "&post_per_page=9999");
-123773 0 Is OOP & completely avoiding implementation inheritance possible? I will choose Java as an example, most people know it, though every other OO language was working as well.
Java, like many other languages, has interface inheritance and implementation inheritance. E.g. a Java class can inherit from another one and every method that has an implementation there (assuming the parent is not abstract) is inherited, too. That means the interface is inherited and the implementation for this method as well. I can overwrite it, but I don't have to. If I don't overwrite it, I have inherited the implementation.
However, my class can also "inherit" (not in Java terms) just an interface, without implementation. Actually interfaces are really named that way in Java, they provide interface inheritance, but without inheriting any implementation, since all methods of an interface have no implementation.
Now there was this article, saying it's better to inherit interfaces than implementations, you may like to read it (at least the first half of the first page), it's pretty interesting. It avoids issues like the fragile base class problem. So far this makes all a lot of sense and many other things said in the article make a lot of sense to me.
What bugs me about this, is that implementation inheritance means code reuse, one of the most important properties of OO languages. Now if Java had no classes (like James Gosling, the godfather of Java has wished according to this article), it solves all problems of implementation inheritance, but how would you make code reuse possible then?
E.g. if I have a class Car and Car has a method move(), which makes the Car move. Now I can sub-class Car for different type of cars, that are all cars, but are all specialized versions of Car. Some may move in a different way, these need to overwrite move() anyway, but most would simply keep the inherited move, as they move alike just like the abstract parent Car. Now assume for a second that there are only interfaces in Java, only interfaces may inherit from each other, a class may implement interfaces, but all classes are always final, so no class can inherit from any other class.
How would you avoid that when you have an Interface Car and hundred Car classes, that you need to implement an identical move() method for each of them? What concepts for code reuse other than implementation inheritance exist in the the OO world?
Some languages have Mixins. Are Mixins the answer to my question? I read about them, but I cannot really imagine how Mixins would work in a Java world and if they can really solve the problem here.
Another idea was that there is a class that only implements the Car interface, let's call it AbstractCar, and implements the move() method. Now other cars implement the Car interface as well, internally they create an instance of AbstractCar and they implement their own move() method by calling move() on their internal abstract Car. But wouldn't this be wasting resources for nothing (a method calling just another method - okay, JIT could inline the code, but still) and using extra memory for keeping internal objects, you wouldn't even need with implementation inheritance? (after all every object needs more memory than just the sum of the encapsulated data) Also isn't it awkward for a programmer to write dummy methods like
public void move() { abstractCarObject.move(); } ?
Anyone can imagine a better idea how to avoid implementation inheritance and still be able to re-use code in an easy fashion?
-20668235 0this is very simple. login to yours site and check the top right corner in the oview of your site and change the date to one day.
There is a article which has everthing in detail. Click here
-39440214 0This might not give the same performance as an UNION but I think this is what you are looking for
You need to create a view:
create view mutex as select i from (select 0 union select 1)sq (i) Now you can use this view to get your desired results as:
select coalesce(a.A,b.B),coalesce(a.coll1,b.coll1),coalesce(a.coll2,b.coll2),coalesce(a.coll3,b.coll3) from mutex left join TABLE_A as a on i =0 left join TABLE_B as b on i =1 Note: Instead of a mutex view, you can also use a table that will have these 2 rows
-19589215 0 am using ScratchPadView for iphone app when am taking screenshot on scratchpad i have written some thing but its not showing the content UIGraphicsBeginImageContext(self.bounds.size ); [self.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *currentScreen = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); here am unable get the screenshot of updated scratchpad something done on scratchpad but it not showing in my screenshot ![Scratchpad screenshot][1]
-22672108 1 merging in pandas vs merging in RI'm afraid I do not quite understand the merging capabilities of pandas, although I much prefer python over R for now.
In R, I have always been able to merge dataframes very easily as follows:
> merge(test,e2s, all.x=T) Gene Mutation Chromosome Entrez 1 AGRN p.R451H chr1 375790 2 C1orf170 p.V663A/V683A chr1 84808 3 HES4 p.R44S chr1 57801 4 ISG15 p.S83N chr1 9636 5 PLEKHN1 p.S476P/S511P/S563P/S76P chr1 84069 However, I have been unable to reconstruct this in pandas with merge(how="left,right,inner,outer").. For example:
Outer yields a union, which makes sense: x = test.merge(e2s, how="outer") In [133]: x.shape Out[133]: (46271, 4) But inner yields an empty dataframe, even though Entrez_Gene_Id has been merged successfully:
In [143]: x = test.merge(e2s, how="inner") In [144]: x Out[144]: Empty DataFrame Columns: [Gene, Mutation, Chromosome, Entrez_Gene_Id] Index: [] [0 rows x 4 columns] The intersection should contain one row with the gene : HES4. Is there some sort of string matching I need to turn on for this?:
e2s:
57794 SUGP1 57795 BRINP2 57796 DKFZP761C1711 57798 GATAD1 57799 RAB40C 57801 HES4 57804 POLD4 57805 CCAR2 57817 HAMP test:
Gene Mutation Chromosome 0 PLEKHN1 p.S476P/S511P/S563P/S76P chr1 1 C1orf170 p.V663A/V683A chr1 2 HES4 p.R44S chr1 3 ISG15 p.S83N chr1 4 AGRN p.R451H chr1 5 RNF223 p.P242H chr1 Update:
As far as I know the columns are labelled so that they should merge fine, I only want to merge by the Gene column and keep all test rows:
In [148]: e2s.columns Out[148]: Index([u'Gene', u'Entrez_Gene_Id'], dtype='object') In [149]: test.columns Out[149]: Index([u'Gene', u'Mutation', u'Chromosome'], dtype='object') This was done by explicitly renaming the dataframes:
e2s.rename(columns={"Gene":u'Gene',"Entrez_Gene_Id":u'Entrez_Gene_Id'}, inplace=True) to dict:
{u'Chromosome': {0: u'chr1', 1: u'chr1', 2: u'chr1', 3: u'chr1', 4: u'chr1', 5: u'chr1'}, u'Gene': {0: u'PLEKHN1', 1: u'C1orf170', 2: u'HES4', 3: u'ISG15', 4: u'AGRN', 5: u'RNF223'}, u'Mutation': {0: u'p.S476P/S511P/S563P/S76P', 1: u'p.V663A/V683A', 2: u'p.R44S', 3: u'p.S83N', 4: u'p.R451H', 5: u'p.P242H'}} {u'Entrez_Gene_Id': {14118: u'SUGP1', 14119: u'BRINP2', 14120: u'DKFZP761C1711', 14121: u'GATAD1', 14122: u'RAB40C', 14123: u'HES4', 14124: u'POLD4', 14125: u'CCAR2', 14126: u'HAMP'}, u'Gene': {14118: 57794, 14119: 57795, 14120: 57796, 14121: 57798, 14122: 57799, 14123: 57801, 14124: 57804, 14125: 57805, 14126: 57817}}
-21907107 0 I think it's wrong argument type, it should be: include Geolocalizable
Add the controls in the Page's Init event and they will be preserved in viewstate when posting back. Make sure they have a unique ID.
See this link...
ASP.NET Add Control on postback
A very trivial example..
public partial class MyPage : Page { TextBox tb; protected override void OnInit(EventArgs e) { base.OnInit(e); tb = new TextBox(); tb.ID = "testtb"; Page.Form.Controls.Add(tb); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); //tb.Text will have whatever text the user entered upon postback } }
-6355262 0 Your views' text is centered manually by the margin. This approach isn't flexible as you can see. I'd remove those margins and set landroid:layout_gravity="center" instead. In addition, you should set the android:layout_weight for your TextViews cal and cal1 like 0.6 and 0.4 respectively. Change the weight slightly if that doesn't fit you.
I am trying to make a new columnn with conditional statements utilizing Pandas Version 0.17.1. I have two csv's both about 100mb's in size.
What I have:
CSV1:
Index TC_NUM 1241 1105.0017 1242 1105.0018 1243 1105.0019 1244 1105.002 1245 1105.0021 1246 1105.0022 CSV2:
KEYS TC_NUM UXS-689 3001.0045 FIT-3015 1135.0027 FIT-2994 1140.0156 FIT-2991 1910, 1942.0001, 3004.0004, 3004.0020, 3004.0026, 3004.0063, 3004.0065, 3004.0079, 3004.0084, 3004.0091, 2101.0015, 2101.0016, 2101.0017, 2101.0018, 2101.0050, 2101.0052, 2101.0054, 2101.0055, 2101.0071, 2101.0074, 2101.0075, 2206.0001, 2103.0001, 2103.0002, 2103.0009, 2103.0011, 3000.0004, 3000.0030, 1927.0020 FIT-2990 2034.0002, 3004.0035, 3004.0084, 2034.0001 FIT-2918 3001.0039, 3004.0042 What I want:
Index TC_NUM Matched_Keys 1241 1105.0017 FIT-3015 1242 1105.0018 UXS-668 1243 1105.0019 FIT-087 1244 1105.002 FIT-715 1245 1105.0021 FIT-910 1246 1105.0022 FIT-219 If the TC_NUM in CSV2 matches the TC_NUM from CSV1, it prints the key in a column on CSV1
Code:
dftakecolumns = pd.read_csv('JiraKeysEnv.csv') dfmergehere = pd.read_csv('output2.csv') s = dftakecolumns['KEYS'] a = dftakecolumns['TC_NUM'] d = dfmergehere['TC_NUM'] for crows in a: for toes in d: if toes == crows: print toes dfmergehere['Matched_Keys'] = dftakecolumns.apply(toes, axis=None, join_axis=None, join='outer')
-767774 0 If you sometimes need an expression and sometimes need a delegate, you have 2 options:
Expression<...> version, and just .Compile().Invoke(...) it if you want a delegate. Obviously this has cost.You need to convert the values to Number, there are plenty of ways to do it:
var test1 = +window.prompt("Number1"); // unary plus operator var test2 = Number(window.prompt("Number2")); // Number constructor var test3 = parseInt(window.prompt("Number3"), 10); // an integer? parseInt var test4 = parseFloat(window.prompt("Number4")); // parseFloat
-417078 0 ASP.NET - how to stop unrequired server validation I have used ValidatorEnable to disable a RequiredFieldValidator in javascript. However on postback the control being validated by the validator is still validated ... even though I disabled the validator on the client.
I understand why this is happening since I've only disabled the client validation ... however is there a nice way to determine that I've disabled the client validation and to then disable the server validation on postback?
-19210874 0 PHP/MySQL - Best way to work with dates in DD MMM YYYY format?I need to display dates in the DD MMM YYYY format on the website I'm working on. My first thought was to store the dates in a DATE type in MySQL, then convert to the proper format using PHP. However, this is just returning 01 Jan 1970 - not the actual date of 04 May 1891.
I found a few other places where people have asked similar questions and the answer was always something like SELECT date_format(dt, '%d/%m/%Y') which was giving me 04/05/1891. I want the month to be 3 characters (May, Jun, Jul, Aug, etc).
I thought about storing the dates as a VARCHAR but that seems like it would be bad practice. It looks like I will have to store the date as a string and will not be able to use the PHP date() function because it cannot handle dates prior to 1970.
I may want to do things like calculate ages which sounds painful when dealing with strings... I am wondering if anyone has a more elegant solution?
-9157550 0Monotouch is not a cross-compiler, and even if it were that alone would not cause a performance penalty.
Monotouch is a .Net compatible runtime that runs on iOS embedded within a normal c/obj-c program. It includes bindings for more or less the same things you can do from normal iOS apps. Monotouch apps are AOT compiled rather than JIT compiled so in most cases they run just as fast as "normal apps"
The fact that SenchaTouch is a javascript framework suggests to me that you will be running mainly interpretted code. I'm sure the Sencha people have done a good job but I would be suprised if it were faster than mono. Looking at Sencha, one advantage is that you can write for android, blackberry and iOS. You can share much of your code between MonoTouch and Mono for Android, you need two licenses and can't share everything.
-35273100 0 How to catch up full gcc compile commandFor example during use make or b2 you can't see command, because build system invokes gcc implicitly. I want to know full command, which build system send to compiler. conceptually. I want to catch up it independently on build system. Maybe on system level, maybe do you know another way. OS: linux.
you may use Session variable to store updated status and then check if it is available in otherpage.aspx,update textbox and reset it.
Insert Page
if (CodeClass.InsertData(txtFirstName.Text, txtLastName.Text, Gender) == true) { Session["status"]="InsertSuccess"; Response.Redirect("OtherPage.aspx"); } } Other Page
if (Session["status"]!=null) { txtLabel.Text = "Record inserted succesfully!"; Session["status"]=null; }
-36039768 0 You can use
(?im)^.*\bthe car\b(?!.*\bnot\b).* The regex demo is available here
Pattern breakdown:
(?im)- enable case-insensitive and multiline matching modes^ - start of a line (since (?m) is used).* - match 0+ any characters but a newline\bthe car\b - 2 whole words "the car" (a sequence of 2 words)(?!.*\bnot\b) - a negative lookahead that fails the match if there is a whole word "not" somewhere to the right of the car.* - the rest of the line up to the newline or end of stringI am the product manager for the OpenPlug tools.
Our tools are not the only ones that allow IPA signing on Windows (you mentioned marmalade, but there is also Adobe CS5/AIR/Flash Builder, and certainly others ...)
As far as I know, Apple hasn't banned any app built with those tools on the ground that they were developed on a non-Apple-branded computer.
For publishing your app you anyway need to access iTunes Connect from a Mac.
Having the possibility to sign IPAs on Windows facilitates the dev/debug cycle on device if you are a developer with a Windows host.
Technically, the signing tools are available open source from the Mach open source distribution of MacOSX. You can refer to the comments section of this post on Corona's blog (another app development tool) for discussion about legalities: http://blog.anscamobile.com/2010/03/does-flash-cs5-for-windows-violate-the-iphone-developer-agreement/.
The last time I looked at Apple's agreements, its only the "SDK" (i.e. xCode and associated iOS SDK) that was only allowed for use on Apple-branded computers only.
Hope this helps
Guilhem
-15871394 0this worked for me :)
-35072122 0select * from Common
where
common_id not in (select ISNULL(common_id,'dummy-data') from Table1)
and common_id not in (select ISNULL(common_id,'dummy-data') from Table2)
Shortest form which I have found looks like this:
debug.getinfo(1).source:match("@?(.*/)") Index 1, 2- other - depends on which function in call stack you want to query. 1 is last called function (where you're in). If you're running in global context, then probably 2 is more appropriate (haven't tested by myself)
-3352132 0 jQuery beforeScroll eventIs there a beforeScroll event in jQuery? Or can this type of event be replicated at all?
We have a scenario where we need perform an event before a div with overflow:scroll has been scrolled. The problem with using the .scroll event is that this is raised after the div has been scrolled rather than before.
-16219227 0First of all, you want
for (int x=0; x<= numOfStudents; x++) or when numOfStudents = 0 you'll never go into the loop.
Also, does addButtonActionPerformed have a for loop that contains the code you've given us? Otherwise, it seems like every time you go into that method numOfStudents will be 0 and when you exit it'll be 1, but the code is only executed for numOfStudents = 0. Am I missing something?
-38959172 0There is no way to get a set of IDs as a result of a bulk INSERT.
One option you have is indeed to run a SELECT query to get the IDs and use them in the second bulk INSERT. But that's a hassle.
Another option is to run the 2nd bulk INSERT into a temporary table, let's call it table3, then use INSERT INTO table2 ... SELECT FROM ... table1 JOIN table3 ...
With a similar use case we eventually found that this is the fastest option, given that you index table3 correctly. Note that in this case you don't have a SELECT that you need to loop over in your code, which is nice.
Whatever you trying to achieve, it seems you are over complicating things. However if you need to display Surname you need to set it in the DisplayMemberPath as DisplayMemberPath="Surname". Here's a tutorial on Custom Controls: How to Create Custom Control.
Below is a link for creating re-useable User control: Creating Re-useable User Controls.
-9335384 0Well, dosen't really solve the problem, but as the container size was full size and the window is full size, i just checked the screen resolution and change the rect accordingly.
-2810943 0A simple approach would be replacing the content of a div with the Flash video when clicked:
HTML
<div id="video-001"> <img src="video-thumb.jpg" /> </div> jQuery
$('#video-001').toggle(function() { $(this).html('<object whatevergoeshere...></object>'); }, function() { $(this).html('<img src="video-thumb.jpg" />'); }); This is a simple example but it can be improved a lot, maybe by inserting the image as the div background, saving the code in the cache of the element (with .data()), adding the click event to all div with a specific class...
Hope it helps :)
-17817307 0First of all, does the page load when you just try to render it or does that crash?
If that works, the next thing to check is that if you look in the web.config, there is a url that is specified the validation check. See what you have listed. This should be the default.
<setting name="HtmlEditor.ValidatorServiceUrl" value="http://validator.w3.org/check" /> If it's not set to that value, put that in and try again. If you are able to get to that page, see if it validates manually. If its able to check manually and return a successful result, then I'd suggest putting in a ticket to Sitecore support.
-32854037 0The routine dont validate entity, but fill the pre-existent entity.
protected virtual void UpdateModel<T>(T original, bool overrideForEmptyList = true) { var json = ControllerContext.Request.Content.ReadAsStringAsync().Result; UpdateModel<T>(json, original, overrideForEmptyList); } private void UpdateModel<T>(string json, T original, bool overrideForEmptyList = true) { var newValues = JsonConvert.DeserializeObject<Pessoa>(json); foreach (var property in original.GetType().GetProperties()) { var isEnumerable = property.PropertyType.GetInterfaces().Any(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IEnumerable<>)); if (isEnumerable && property.PropertyType != typeof(string)) { var propertyOriginalValue = property.GetValue(original, null); if (propertyOriginalValue != null) { var propertyNewValue = property.GetValue(newValues, null); if (propertyNewValue != null && (overrideForEmptyList || ((IEnumerable<object>)propertyNewValue).Any())) { property.SetValue(original, null); } } } } JsonConvert.PopulateObject(json, original); } public void Post() { var sample = Pessoa.FindById(12); UpdateModel(sample); }
-24789791 0 Copy specific Google Form response values into different Google Sheet I have a Google Form that has many questions, but I only want to record some of the responses into a separate, condensed spreadsheet. These are the responses I want to record:
First Name Last Name Company Role This is my script, which is triggered to execute on form submission:
function copyCondensedResponseData(e) { var array_to_paste_in_participant_attendance_sheet = []; array_to_paste_in_participant_attendance_sheet.push(e.namedValues["First Name"].toString()); array_to_paste_in_participant_attendance_sheet.push(e.namedValues["Last Name"].toString()); array_to_paste_in_participant_attendance_sheet.push(e.namedValues["Role"].toString()); array_to_paste_in_participant_attendance_sheet.push(e.namedValues["Company"].toString()); var participant_attendance_sheet = SpreadsheetApp.openById(/* id */).getSheets()[0]; participant_attendance_sheet.getRange(participant_attendance_sheet.getLastRow()+1,1).getValues()[0] = array_to_paste_in_participate_attendance_sheet; } But nothing is pasted into the participate_attendance_sheet. I know that typically you copy data from one sheet into another by calling getRange() and setValues(), but I think that's only if the data I want to copy is of the class Object [ ] [ ]. Any thoughts?
-14968488 0 Perl String Parsing to HashSo lets say I had the string.
$my str = "Hello how are you today. Oh thats good I'm glad you are happy. Thats wonderful; thats fantastic." I want to create a hash table where each key is a unique word and the value is the number of times it appears in the string i.e., I want it to be an automated process.
my %words { "Hello" => 1, "are" => 2, "thats" => 2, "Thats" => 1 }; I honestly am brand new to PERL and have no clue how to do this, how to handle the punctuation etc.
UPDATE:
Also, is it possible to use
split('.!?;',$mystring) Not with this syntax, but basically split at a . or ! or ? etc.. oh and ' ' (whitespace)
-23703133 0Your first problem is that -lpthread is a linker option, so it belongs on the linker line (the second command) rather than the compilation line. (Note that the order of the parameters can matter; I got it to work by putting -lpthread on last. I also tried using -pthread instead of -lpthread, which did appear to work and was also less sensitive to where it was put on the linker line. But again, it's a linker option, not a compile option.)
After fixing that, I was able to get your program to compile and run, but it exited with a different exception: terminate called without an active exception. To fix this problem, call thread_fct.join(); in main(). (All threads must be joined, detached, or moved-from before they go out of scope, or your program will abort.)
Why doesn't the line marked with //Dont work in the bottom of the code compile?
I want to reuse the WriteMessage method with different Classes, I try to use generics, but I'm not sure how to use it.
class ClassOne { public string MethodOne() { return ("ClassOne"); } public string MethodTwo() { return ("ClassOne -MethodTwo "); } } class ClassTwo { public string MethodOne() { return ("ClassTwo"); } public string MethodTwo() { return ("ClassOne -MethodTwo "); } } class Program { private static void Main() { var objectOne = new ClassOne(); WriteMessage(objectOne); var objectTwo = new ClassTwo(); WriteMessage(objectTwo); Console.ReadKey(); } public static void WriteMessage<T>(T objectA) { var text = objectA.MethodTwo(); //Dont Work Console.WriteLine("Text:{0}", text); } }
-9754655 0 using (XmlWriter writer = new XmlTextWriter(stream) { writer.WriteStartElement("c1") writer.WriteString("") writer.WriteFullEndElement() } EDIT: Here's testable code. It doesn't matter how you create the XmlWriter
public static void Main() { using (StringWriter sw = new StringWriter()) { using (XmlWriter xw = XmlWriter.Create(sw)) { xw.WriteStartElement("c1"); xw.WriteString(string.Empty); xw.WriteFullEndElement(); } Console.Write(sw.ToString()); // Prints <c1></c1> } } What implementation of XmlWriter are you using?
-19268903 0 Restoring buttons back to its positionI searched stackoverflow for answers buy am unable to find one so i am posting a question.A helping hand is much appreciated.
I am creating a quiz app.The layout contains six textview box and 12 buttons with letters.when user clicks on button textview gets filled with each letter and increments textview based on position so that all six textview box gets filled.i have also made buttons to disappear as soon as the text gets filled in textview.i am successful in implementing these steps but my question is how to make filled textview text empty so that the corresponding button gets reappeared?to be more clear i added onClickListener to textview but filled text in textview doesn't decrement. hope you have understand the question .i am still learning and am developing app from scratch.
switch(v.getId()) { case R.id.button1: { b1=(Button) findViewById(R.id.button1); String name1=b1.getText().toString(); tv.setText(name1); position++; b1.setVisibility(View.INVISIBLE); } break; case R.id.button2: b2=(Button) findViewById(R.id.button2); String name2=b2.getText().toString(); //blankbut.setText(name2); tv.setText(name2); position++; b2.setVisibility(View.INVISIBLE); break; case R.id.button3: b3=(Button) findViewById(R.id.button3); String name3=b3.getText().toString(); tv.setText(name3); //blankbut.setText(name3); position++; b3.setVisibility(View.INVISIBLE); break; case R.id.button4: b4=(Button) findViewById(R.id.button4); String name4=b4.getText().toString(); tv.setText(name4); //blankbut.setText(name4); position++; b4.setVisibility(View.INVISIBLE); break; case R.id.button5: b5=(Button) findViewById(R.id.button5); String name5=b5.getText().toString(); tv.setText(name5); //blankbut.setText(name5); position++; b5.setVisibility(View.INVISIBLE); break; case R.id.button6: b6=(Button) findViewById(R.id.button6); String name6=b6.getText().toString(); tv.setText(name6); //blankbut.setText(name6); position++; b6.setVisibility(View.INVISIBLE); break; case R.id.button7: b7=(Button) findViewById(R.id.button7); String name7=b7.getText().toString(); tv.setText(name7); // blankbut.setText(name7); position++; b7.setVisibility(View.INVISIBLE); break; case R.id.button8: b6=(Button) findViewById(R.id.button8); String name8=b8.getText().toString(); tv.setText(name8); //blankbut.setText(name8); position++; b8.setVisibility(View.INVISIBLE); break; case R.id.button9: b9=(Button) findViewById(R.id.button9); String name9=b9.getText().toString(); tv.setText(name9); //blankbut.setText(name9); position++; b9.setVisibility(View.INVISIBLE); break; case R.id.button10: b10=(Button) findViewById(R.id.button10); String name10=b10.getText().toString(); tv.setText(name10); //blankbut.setText(name10); position++; b10.setVisibility(View.INVISIBLE); break; case R.id.button11: b11=(Button) findViewById(R.id.button11); String name11=b11.getText().toString(); tv.setText(name11); //blankbut.setText(name11); position++; b11.setVisibility(View.INVISIBLE); break; case R.id.button12: b12=(Button) findViewById(R.id.button12); String name12=b12.getText().toString(); tv.setText(name12); //blankbut.setText(name12); position++; b12.setVisibility(View.INVISIBLE); break; }
-22612337 0 R shiny, load data based on input I have data for each day in server side and want to load data based on date input
On server side, I have this:
dateInput("date","Enter a date:",value = "2014-01-13")) On UI side,
library(shiny) library(googleVis) library(rpart.plot) load("data_2014_01_13_new.RData") #seg and fit are data in this file shinyServer(function(input, output) { output$values <- renderGvis({ gvisTable(seg[seg$rate >= input$test[1] & seg$rate <= input$test[2],]) }) output$plot <- renderPlot({ prp(fit,extra=T) }) }) I want to put load into server function and can load different data as date changes. Thanks!
-39322893 0This could be shortened heavily but I don't feel like rewriting your entire program. This should work as expected.
total_guess = 0 wins = 0 loss = 0 import random characters = ["rock", "paper", "scissors", "lizard", "spock"] computer = characters[random.randint(0,4)] print(computer) def valid(text, flag): error_message= "" while True: var = input(error_message + text) if flag == "s": if var.isalpha()==True: break else: error_message = "This is not valid, " elif flag =="i": if var.isdigit()==True: var = int(var) break else: error_message = user_name + " this is not a number, " elif flag == "g": if var == "rock" or var == "paper" or var == "scissors" or var == "lizard" or var == "spock": break else: error_message = user_name + " this is not valid! " return(var) user_name = valid("What is your name?", "s") num_rounds = valid(user_name +" how many rounds do you want?", "i") while True: while num_rounds > total_guess: player = valid(user_name + """ ,What do you want as your character: Rock, paper, scissors, lizard or spock""", "g" ) total_guess = total_guess + 1 if player == computer: print("Draw!") # -------------------------------------------- elif player == "Rock" or player == "rock": if computer == "paper" or computer == "spock" : loss = loss + 1 print(' '.join(("You lost", computer, "beats", player))) if computer == "scissors" or computer == "lizard": wins = wins + 1 print(' '.join(("You win", player, "beats", computer))) elif player == "Paper" or player == "paper": if computer == "scissors" or computer == "lizard": loss = loss + 1 print(' '.join(("You lost", computer, "beats", player))) if computer == "rock" or computer == "spock": wins = wins + 1 print(' '.join(("You win", player, "beats", computer))) elif player == "Scissors" or player == "scissors": if computer =="Spock" or computer == "rock": loss = loss + 1 print(' '.join(("You lost", computer, " beats ", player))) if computer =="paper" or computer == "lizard": wins = wins + 1 print(' '.join(("You win", player, "beats", computer))) elif player == "Lizard" or player =="lizard": if computer =="scissors" or computer == "rock": loss = loss + 1 print(' '.join(("You lost", computer, "beats", player))) if computer == "paper" or computer == "spock": wins = wins + 1 print(' '.join(("You win", player, "beats", computer))) elif player == "Spock" or player == "spock": if computer == "lizard" or computer == "paper": loss = loss + 1 print(' '.join(("You lost", computer, "beats", player))) if computer =="rock" or computer == "scissors": wins = wins + 1 print(' '.join(("You win", player, "beats", computer))) end_game = input("To exit enter N, to play again enter any key ") if end_game == 'n' or end_game == 'N': print("THANKS FOR PLAYING " + user_name + '!') break total_guess = 0
-4211328 0 This is VBA short-form for setting the value of a range of cells (or in this case, a single cell). So the example you've provided will actually insert the text value "FALSE" into cell AF6.
If the colour of the other cell is not being set in code, then I would suggest it was done through conditional formatting.
-257689 0Note that if you're creating a object that can be mutated after creation, the hash value must not change if the object is inserted into a collection. Practically speaking, this means that the hash value must be fixed from the point of the initial object creation. See Apple's documentation on the NSObject protocol's -hash method for more information:
If a mutable object is added to a collection that uses hash values to determine the object’s position in the collection, the value returned by the hash method of the object must not change while the object is in the collection. Therefore, either the hash method must not rely on any of the object’s internal state information or you must make sure the object’s internal state information does not change while the object is in the collection. Thus, for example, a mutable dictionary can be put in a hash table but you must not change it while it is in there. (Note that it can be difficult to know whether or not a given object is in a collection.)
This sounds like complete whackery to me since it potentially effectively renders hash lookups far less efficient, but I suppose it's better to err on the side of caution and follow what the documentation says.
-34505799 0 how to pass dynamic table name into mySQL Procedure with this query?I have create procedure and when i pass table name manually then its working fine, but when i pass dynamic table name then it says dbname.tblname doesn't exist.
DELIMITER $$ CREATE PROCEDURE `lmsonline`.`delProc`(tblName VARCHAR(20),sr INT) BEGIN DELETE FROM tblName WHERE srno=sr; SET @num := 0; UPDATE tblName SET srno = @num := (@num+1); ALTER TABLE tblName AUTO_INCREMENT = 1; END$$ DELIMITER ; and to execute i have CALL delProc('beginner',6);
Just adding another answer that works in a similar fashion to the one by Xin, but using a package (shinyjs) that natively supports enabling/disabling buttons, rather than having to deal with the messy javascript yourself. Using this package, you can simply call disable("download") or enable("download").
Here's a full example replicating the answer by Xin but with this package
library(shiny) library(shinyjs) runApp(shinyApp( ui = fluidPage( # need to make a call to useShinyjs() in order to use its functions in server shinyjs::useShinyjs(), actionButton("start_proc", "Click to start processing data"), downloadButton("data_file") ), server = function(input, output) { observe({ if (input$start_proc > 0) { Sys.sleep(1) # enable the download button shinyjs::enable("data_file") # change the text of the download button shinyjs::text("data_file", sprintf("<i class='fa fa-download'></i> Download (file size: %s)", round(runif(1, 1, 10000)) ) ) } }) output$data_file <- downloadHandler( filename = function() { paste('data-', Sys.Date(), '.csv', sep='') }, content = function(file) { write.csv(data.frame(x=runif(5), y=rnorm(5)), file) } ) # disable the downdload button on page load shinyjs::disable("data_file") } ))
-33587159 0 Try below - location is an Object, so you should be able to reference it with -> notation.
$city = $response->businesses[0]->location->city; display_address
$display_address = $response->businesses[0]->location->display_address[0];
-22793589 0 I'm writing a Google Glass Development book for Apress and just finished the chapter Network and Bluetooth, with some working samples to let Glass communicate with iPhone for data transfer. You're right that Glass as of now (API level 15) doesn't support Bluetooth Low Energy (BLE). I have implemented three ways to make the data transfer between Glass and iOS happen:
Let Glass talk to an Android device, such as Nexus 7 with Android 4.3 or above with BLE support, via Classic Bluetooth or socket, and Nexus 7 acts as a BLE central to talk to iOS as a BLE peripheral. Notice you shouldn't use BLE to send large data such as photo.
Let Glass talk to iOS directly via socket - you can use C socket code running as a server and Glass Java socket client, or vice versa. This would require your Glass and iOS device on the same Wifi, but can transfer large data.
Use a server-based solution - upload data from Glass to a server and let iOS get it via Apple Push Notification. I used this method to share photos on Glass with friends on WhatsApp and WeChat, both apps run on iOS.
Sample iOS code acting as socket server:
- (void) runSocketServer { int listenfd = 0; __block int connfd = 0; struct sockaddr_in serv_addr; __block char sendBuff[1025]; listenfd = socket(AF_INET, SOCK_STREAM, 0); memset(&serv_addr, '0', sizeof(serv_addr)); memset(sendBuff, '0', sizeof(sendBuff)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(6682); bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); listen(listenfd, 10); dispatch_async(dispatch_get_global_queue(0, 0), ^{ connfd = accept(listenfd, (struct sockaddr*)NULL, NULL); int count = 1; while (count++ < 120) { char rate[100]; sprintf(rate, "%i\n", bpm); write(connfd, rate, strlen(rate)); sleep(1); } close(connfd); }); } Sample Glass code acting as a socket client:
public void run() { String serverName = "192.168.1.11"; int port = 6682; try { socket = new Socket(serverName, port); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); do { result = input.readLine(); runOnUiThread(new Runnable() { public void run() { mTvInfo.setText(result); } }); } while (result != null); }); } catch(Exception e) { try { socket.close(); } catch (Exception e2) {}; e.printStackTrace(); } }
-19741157 0 Change
temp."px"; To
temp+"px"; That's it :)
-3474417 0Wikipedia has a long overview. I would hightlight rvalue references and lambdas.
-35434488 0You can do this with plain old html. Put a DIV around where the link should take you:
-# <DIV ID="FT001"><b>FT001:</b></DIV> I, as -# <DIV ID="FT002"><b>FT002:</b></DIV> I, as I'm not an HTML expert, but <A NAME="anchor" ... might be better than <DIV ....
Elsewhere in the same file you can reference it with this.
<a href="#FT001">Link to section elsewhere in this file</a> You might want to create an alias in your config file to make this more readable, like either of these:
ALAISES += "anchor{2}=<DIV ID=\"\1\"> \2 <DIV> ALAISES += "bookmark{2}=<DIV ID=\"\1\"> \2 <DIV> You can also reference the link like this.
[Link to elsewhere](#FT001)
-27745906 0 Sorry, the error was that I needed to get the CGColor property from UIColor.greenColor()
Once more, the Swift compiler seems not reliable on its messages...
-12592513 0 Extracting a list of files and creating a new file containing this listI am a researcher and my skill in Unix commands is limited. I am currently dealing with a folder containing about 1000 files and I have to extract some filenames from this folder and create another file (configuration file) containing these filenames.
Basically, the folder has filenames in the following format :
1_Apple_A_someword.txt 1_Apple_B_someword.txt 2_Apple_A_someword.txt 2_Apple_B_someword.txt 3_Apple_A_someword.txt 3_Apple_B_someword.txt and so on up until
1000_Apple_A_someword.txt 1000_Apple_B_someword.txt I just want to extract out all files which have "Apple_A" in them. Also, I want to create another file which has 'labels' (Unix variables) for each of these "Apple_A" files whose values are the names of the files. Also, the 'labels' are part of the filenames (everything up until the word "Apple") For example,
1_Apple=1_Apple_A_someword.txt 2_Apple=2_Apple_A_someword.txt 3_Apple=3_Apple_A_someword.txt and so on...till
1000_Apple=1000_Apple_A_someword.txt Could you tell me a one-line Unix command that does this ? Maybe using "awk" and "sed"
-13855435 0 Windows Phone Emulator 7.1 doesnt openI successfully installed windows phone SDK 7.1 in my pc but when I tried to open the Windows phone emulator it shows an error says "Windows phone emulator is not supported on this computer bcoz this computer does not have the required graphics processing unit configuration. An XNA framework game or page will not function without a graphics processing unit. A silverlight Application may run, but with reduced functionality"
I have OS which is win7 ultimate (32-bit), 1-GB DDR-II ram, Intel Dual Core Processor; I know that it needs 3GB ram but I have seen it in a forum that it can also be installed with 1-GB of ram & I don't think there is a problem of ram here but of graphics. I am a newbie in this stuff but desperately wants to learn to create apps please help!
-30814037 0Look at the file you give with the excelFormat item I would guess it is due to the following line in it:
<Table ss:ExpandedColumnCount="7" ss:ExpandedRowCount="68" x:FullColumns="1" x:FullRows="1" ss:DefaultRowHeight="15"> You can see that it has a mention of an ExpandedRowCount which is set to 68. A quick search for <Row in that same file gives 44 results. If you add your 22 lines this brings you up to 66 which is only 2 short. I'm not quite sure where this goes wrong since there is still a difference of 2, but I'd guess that this is your issue. Try changing the ExpandedRowCount attribute to be something higher and test again (with less than 22 items, exactly 22 items, and more than 22 items).
Answer of @Mangesh Parte can be short like,
<?php function load_external_jQuery() { wp_deregister_script( 'jquery' ); // deregisters the default WordPress jQuery $url = 'http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'; // the URL to check against $test_url = @fopen($url,'r'); // test parameters if( $test_url !== false ) { // test if the URL exists if exists then register the external file wp_register_script('jquery', $url); } else{// register the local file wp_register_script('jquery', get_template_directory_uri().'/js/jquery.js', __FILE__, false, '1.7.2', true); } wp_enqueue_script('jquery'); // enqueue the jquery here } add_action('wp_enqueue_scripts', 'load_external_jQuery'); // initiate the function ?>
-16181567 0 .. means to traverse one level up; you are using a relative path, not an absolute one like you should be. Drop the dots:
<img src="/foo/bar.png"> will load the image from the root of the domain.
Even @juergen has suggested better option and also guided you how to solve your problem in your way but if stil you are facing issue how to do then you can follow below query-
SELECT p.id AS pid, n1.image_1, n2.image_2, n3.image_3, big, small FROM photos AS p LEFT JOIN news AS n1 ON n1.image_1=p.id LEFT JOIN news AS n2 ON n2.image_2=p.id LEFT JOIN news AS n3 ON n1.image_3=p.id ORDER BY n.id DESC;
-10690230 0 zoom is a gesture with 2 fingers so you have to listen on touchmove with event.targetTouches.length == 2 and then read the X and Y coordinates from each finger
the image zoom centre will be event.targetTouches[0].pageX - event.targetTouches1.pageX and event.targetTouches[0].pageY - event.targetTouches1.pageY in relationship with your scrollposition or image position (attention to + or -)
and your scalefactor should be vectorLengthCurrent-vectorLengthStart
see at http://www.html5rocks.com/en/mobile/touch/
image: 
example:
image: left: -100px | startFinger[0].pageX: 50px | currentFinger[0].pageX: 55px | startFinger1.pageX: 150px | currentFinger1.pageX: 140px
so the centre should be: startFinger1.pageX - startFinger[0].pageX - left (only if startFinger1.pageX is greater | Y in the same way)
vector length: sqrt(x^2 + y^2);
-37387514 0 OpenLayers3 - Animated .fit to a specific extentI have created a map using OpenLayers3. I can succesfully zoom to a layer on the map using the following code:
map.getView().fit(extent, map.getSize()); However I woulld like something similiar in an animated way.
I know about the following animations:
ol.animation.pan ol.animation.zoom By using these I can't zoom to a layer, using ol.animation.pan I can only pan to a point (and not to a boundingbox) and using ol.animation.zoom I can zoom to a resolution (and not to a boundingbox). So what I am looking for is an animated .fit so I can zoom animated to an extent.
Any suggestions on how I can achieve that would be appreciated :)
-13417781 0In my case I have these messages when I show the sherlock action bar inderterminate progressbar. Since its not my library, I decided to hide the Choreographer outputs.
You can hide the Choreographer outputs onto the Logcat view, using this filter expression :
tag:^((?!Choreographer).*)$
I used a regex explained elsewhere : Regular expression to match string not containing a word?
-23112799 0 Can't save captured image with Android 4.2.2In my app I need to capture image with the standard camera app. So, what I did is:
public void TakePhotoProofs() { // fetching the root directory root = Environment.getExternalStorageDirectory().toString() + "/MyAppStoredImages"; // Creating folders for Image imageFolderPath = root + "/captured_images"; File imagesFolder = new File(imageFolderPath); if (!imagesFolder.exists()) { imagesFolder.mkdirs(); } // Generating file name by current date Time today = new Time(Time.getCurrentTimezone()); today.setToNow(); imageName = today.format("%Y-%m-%d-%H-%M-%S") + ".png"; // Creating image here File image = new File(imageFolderPath, imageName); fileUri = Uri.fromFile(image); imvPhotoFrame.setTag(imageFolderPath + File.separator + imageName); Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); startActivityForResult(takePictureIntent, CAMERA_IMAGE_REQUEST); } In this code snipped I faced with the following issue:
onActivityResult() the variable fileUri should contain path to captured image that in previous step should be saved in my folder /MyAppStoredImages/captured_imagesNote: if I run the standard camera app separately, the bottom frames (from step (4)) are not empty.
This behaviour has arisen after I updated my firmware from Android 4.1.2 Jelly Bean to Android 4.2.2 Jelly Bean. With Android 4.1.2 Jelly Bean all images were being captured properly.
Did someone have the same issue? What should I do in this case?
UPDATE: Using the proposition given by @Mohit in this post, I added the following line after putting EXTRA_OUTPUT:
takePictureIntent.putExtra("return-data", true); Now, it works properly with third-party camera app (I tested with CameraMX). But still I can't use my default camera app (via invocations described above, I can't save captured image. But separately this default app works properly too).
So, if you encountered the same problem, please, refer me to the correct way.
Just in case, this problem arose on the Samsung Galaxy Grand Duos i9082 and its default camera app after upgrading to Android 4.2.2)
-8887146 0What is your desired functionality? I assume: shifting which LED is on every 2 seconds, keeping all the other LEDs off? "Sliding LED"...
Also, I am assuming your target is an FPGA-type board.
There is no free "wait for X time" in the FPGA world. The key to what you are trying to do it counting clock cycles. You need to know the clock frequency of the clock that you are using for this block. Once you know that, then you can calculate how many clock rising edges you need to count before "an action" needs to be taken.
I recommend two processes. In one, you will watch rising edge of clock, and run a counter of sufficient size, such that it will roll over once every two seconds. Every time your counter is 0, then you set a "flag" for one clock cycle.
The other process will simply watch for the "flag" to occur. When the flag occurs, you shift which LED is turned on, and turn all other LEDs off.
-9591818 0 Common.Logging configuration. Troubles with log4net adapterGot the following exception
Failed obtaining configuration for Common.Logging from configuration section 'common/logging'.
while trying to run next code
Common.Logging.ILog logger = Common.Logging.LogManager.GetCurrentClassLogger(); App.Config:
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <sectionGroup name="common"> <section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" /> </sectionGroup> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> </configSections> <common> <logging> <factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4Net"> <arg key="configType" value="INLINE" /> </factoryAdapter> </logging> </common> <log4net> <root> <level value="ALL" /> <appender-ref ref="FileAppender" /> </root> <appender name="FileAppender" type="log4net.Appender.FileAppender" > <param name="File" value="log.txt" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %level %logger - %message%newline" /> </layout> </appender> </log4net> <connectionStrings> <add name="ManagementEntities" connectionString="metadata=res://*/Model.ManagementModel.csdl|res://*/Model.ManagementModel.ssdl|res://*/Model.ManagementModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\SQLEXPRESS;attachdbfilename=|DataDirectory|\Data\Management.mdf;integrated security=True;user instance=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /> </connectionStrings> </configuration>
-1622186 0 I propose two solutions. The first mimics what NetBeans IDE generates:
CC=gcc .PHONY: all clean all: post-build pre-build: @echo PRE post-build: main-build @echo POST main-build: pre-build @$(MAKE) --no-print-directory target target: $(OBJS) $(CC) -o $@ $(OBJS) clean: rm -f $(OBJS) target The second one is inpired by what Eclipse IDE generates:
CC=gcc .PHONY: all clean .SECONDARY: main-build all: pre-build main-build pre-build: @echo PRE post-build: @echo POST main-build: target target: $(OBJS) $(CC) -o $@ $(OBJS) @$(MAKE) --no-print-directory post-build clean: rm -f $(OBJS) target Note that in the first one, pre and post builds are always called regardless of whether the main build is determined to be up to date or not.
In the second one, the post-build step is not executed if the state of the main build is up to date. While the pre-build step is always executed in both.
-4992780 0for k, v in records.items(): if v is None: records[k] = 0
-29361160 0 How to handle 'half-open' connections- managing client-side socket crash We have a code of Client-Server written in 'C' underlying TCP protocol. The regular socket operations are being performed on both Client and Server. And select() function is being used to monitor multiple connections 'read/ write' mechanisms. The connection has been successfully ESTABLISHED. And using the same select() the connected client sends a message to server for releasing the connection. Up-to this we are happy.
The main problem comes when the Client has some issues and has crashed/ stuck-up/ hanged in the middle or because of some other reasons mentioned in here: Detection of Half-Open (Dropped) Connections. The author mentioned about the 'four-way' handshaking! But how can we know the status of the client that has crashed until it sends some signal to Server? Is there a way to know about whether my client is still running (alive) or has some problems (dead) such that the Server closes that particular socket connection that was established? Please let us know. Thank you all... :)
-2612294 0The nomenclature can be confusing. Instead of "first responder" think of it as "initial event target" i.e. the object that is the first responder becomes the initial target for all events. In some APIs this is also called the "focus" although in the Apple APIs that is usually reserved to describe windows.
At any given time, there is only one first-responder/intial-event-target in the app. Only individual objects/instances can become a first-responder/intial-event-target. Classes can merely define if their instance have the ability to become a first-responder/intial-event-target. A class need only provide the ability to become the app's first-responder/intial-event-target if it make sense to do so. For example, a textfield obviously needs the ability to trap events so that it can use those event to edit itself. By contrast, a static label needs no such capability.
Whether a particular class inherits from NSResonder has no bearing on whether the class (or a specific instance of the class) will let itself be set as the first-responder/intial-event-target. That ability comes solely from the instances' response to the canBecomeFirstResponder message. The same instance can refuse to be the first-responder/intial-event-target under one set of conditions and then allow it later when conditions change. Classes can of course hardwire the status if they wish.
In other words, first-responder/intial-event-target is a status of a particular instance at a particular time. The first-responder/intial-event-target is like a hot potato or a token that is handed off from instance to instance in the UI. Some classes refuse to grab the hot potato at all. Some always do and others grab it sometimes and ignore it others.
-17458933 0 Right way to use md5 secrets in confirming ok-ness of URL requests? When to clear the secret?I have some cases where I need to put a URL into a web page that, when clicked on, will fire some handling code on the server. I obviously want to prevent random bad guys from constructing their own URLs and doing things they shouldn't, so I'm working with this scheme, reverse-engineered from stuff I've seen on other sites:
/do_this/123/FABDYFYEYYDFBDHDFSThis is working OK for me, except for the part where the user's browser's session storage gets littered with no-longer-relevant session variables. There are some cases where I can (and do) delete a session variable once I'm done doing what I'm doing, but not always. I could probably be a little more clever about finding opportunities to clear the old variables, but the problem seems general enough that there may be a better way to do this (i.e., what I've come up with could be really stupid for any number of reasons I haven't thought of). Is there any advice out there for a good/better way of doing this sort of thing?
-15980707 0You can create a custom filter that inherits from FilterAttribute and implements IExceptionFilter. Then register it in global.asax.cs. Also you must enable custom errors handling in the web.config:
<customErrors mode="On"/> public class HandleErrorAndLogExceptionAttribute : FilterAttribute, IExceptionFilter { /// <summary> /// The method called when an exception happens /// </summary> /// <param name="filterContext">The exception context</param> public void OnException(ExceptionContext filterContext) { if (filterContext != null && filterContext.HttpContext != null) { if (!filterContext.IsChildAction && (!filterContext.ExceptionHandled && filterContext.HttpContext.IsCustomErrorEnabled)) { // Log and email the exception. This is using Log4net as logging tool Logger.LogError("There was an error", filterContext.Exception); string controllerName = (string)filterContext.RouteData.Values["controller"]; string actionName = (string)filterContext.RouteData.Values["action"]; HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName); // Set the error view to be shown ViewResult result = new ViewResult { ViewName = "Error", ViewData = new ViewDataDictionary<HandleErrorInfo>(model), TempData = filterContext.Controller.TempData }; result.ViewData["Description"] = filterContext.Controller.ViewBag.Description; filterContext.Result = result; filterContext.ExceptionHandled = true; filterContext.HttpContext.Response.Clear(); filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; } } }
-16048022 0 It means your dataArray is used to give a sorted array based on the comparison of the "1" property of each element of the original array.
For example if it is an array of strings, the second char is used as the comparator. If it is an array of arrays, the second element of each array is used.
Its a shortcut for defining an iterator function which extract the given property of each item.
Then reverse does what it has always done, reversing the array.
-12815078 0 How to get updated object from MongoI have a Match document that have ReferenceMany(Scores) on it. When I add a new Score to a Match, and return the Match, the new score isn't there. On the next request though, the score is there. How can I force Doctrine to update my Match in the same request?
Code:
$match = $dm->getRepository('Match')->find($matchId); // Save score. $dm->persist($score); // Add score to match $match->addScores($score); $dm->flush(); // <-- This doesn't help. return $match; // <-- Is missing the new Score.
-3615473 0 Perhaps, one way that I can think of is
All above would have been tricky from thread sync point not for few interesting collections present in System.Collections.Concurrent namespace. This would make the above logic much more simpler. For example, ConcurrentDictionary.GetOrAdd will allow to lookup and/or add the KeyProcessor object in thread-safe way.
-606342 0Can you explain what's confusing about it? Properties can be overridden like any other method.
public class Base { public virtual int Prop1 { get { ... } set { ... } } } public class Derived : Base { public override int Prop1 { get { ... } set { ... } }
-40777802 0 Adding individual values to a count query I have the query below that returns a count of a number of tickets. I also want the query to return the individual ticket numbers in the count. This is the query:
;WITH CTE AS ( select SR_Service_RecID from SR_Audit where Audit_Text like 'Ticket status has been changed from % to "Internal"%' OR Audit_Text like 'Ticket status has been changed from % to "Closed"%' OR Audit_Text like 'Ticket status has been changed from % to "First Contact Resolution"%' ) SELECT Board_Name, COUNT(DISTINCT A.SR_Service_RecID) AS 'Re-Opened Tickets' FROM CTE JOIN SR_Audit A ON CTE.SR_Service_RecID = A.SR_Service_RecID JOIN v_rpt_service vsrv ON vsrv.TicketNbr = A.SR_Service_RecID WHERE Audit_Text LIKE 'Ticket status has been changed from%"Re-Opened"%' AND vsrv.company_name <> 'XYZ Test Company' AND vsrv.date_entered BETWEEN @StartDate AND @EndDate AND Board_Name in (@BoardName) GROUP BY Board_Name It returns:
Board Name Count IT Services 4 I want it to return this:
Board Name Count Ticket Number IT Services 4 12346 IT Services 4 12445 IT Services 4 56345 IT Services 4 12384 How can I add the ticket numbers to the result?
-36366818 0There are well-tested wheels used to tear apart URLs into the component parts so use them. Ruby comes with URI, which allows us to easily extract the host, path or query:
require 'uri' URL = 'http://foo.com/a/b/c?d=1' URI.parse(URL).host # => "foo.com" URI.parse(URL).path # => "/a/b/c" URI.parse(URL).query # => "d=1" Ruby's Enumerable module includes reject and select which make it easy to loop over an array or enumerable object and reject or select elements from it:
(1..3).select{ |i| i.even? } # => [2] (1..3).reject{ |i| i.even? } # => [1, 3] Using all that you could check the host of a URL for sub-strings and reject any you don't want:
require 'uri' %w[ http://www.speedtest.net/ http://webcache.googleusercontent.com/search%3Fhl%3Den%26biw%26bih%26q%3Dcache:M47_v0xF3m8J ].reject{ |url| URI.parse(url).host[/googleusercontent\.com$/] } # => ["http://www.speedtest.net/"] Using these methods and techniques you can reject or select from an input file, or just peek into single URLs and choose to ignore or honor them.
-1088314 0You can also call an existing function with an invalid number of arguments.
-37363011 0Let try this query instead:
uniqBk = Bikehistory.where("JOIN ( SELECT id, DISTINCT bike_numbers FROM bikehistories ) as temp ON temp.id = id") .order(:bike_numbers)
-33602227 0 Use modulus operator %, this makes sure character stays in range between A to Z.
char c = 'A' + shift % 26; You can shift letters to the right, then once letter reaches Z, the next letter will be A
int main() { int row, col; for (row = 0; row < 26; row++) { for (col = 0; col < 26; col++) { char c = 'A' + (row + col) % 26; printf("%c ", c); } printf("\n"); } printf("\n"); return 0; }
-1738329 0 Should I send retain or autorelease before returning objects? I thought I was doing the right thing here but I get several warnings from the Build and Analyze so now I'm not so sure. My assumption is (a) that an object I get from a function (dateFromComponents: in this case) is already set for autorelease and (b) that what I return from a function should be set for autorelease. Therefore I don't need to send autorelease or retain to the result of the dateFromComponents: before I return it to the caller. Is that right?
As a side note, if I rename my function from newTimeFromDate: to gnuTimeFromDate the analyzer does not give any warnings on this function. Is it the convention that all "new*" methods return a retained rather than autoreleased object?
In Memory Management Programming Guide for Cocoa it says "A received object is normally guaranteed to remain valid within the method it was received" and that "That method may also safely return the object to its invoker." Which leads me to believe my code is correct.
However, in Memory Management in Cocoa it says "Assume that objects obtained by any other method have a retain count of 1 and reside in the autorelease pool. If you want to keep it beyond the current scope of execution, then you must retain it." Which leads me to think I need to do a retain before returning the NSDate object.
I'm developing with Xcode 3.2.1 on 10.6.2 targeting the iPhone SDK 3.1.2.

Here's the code in case you have trouble reading the screen shot:
//============================================================================ // Given a date/time, returns NSDate for the specified time on that same day //============================================================================ +(NSDate*) newTimeFromDate:(NSDate*)fromDate Hour:(NSInteger)hour Minute:(NSInteger)min Second:(NSInteger)sec { NSCalendar* curCalendar = [NSCalendar currentCalendar]; const unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit; NSDateComponents* comps = [curCalendar components:units fromDate:fromDate]; [comps setHour: hour]; [comps setMinute: min]; [comps setSecond: sec]; return [curCalendar dateFromComponents:comps]; }
-5229588 0 Hmmm, nice puzzle. FWIW: printf("%s 1 \n", str) prints ' 1 rty "what"' ?!? ... looks to me like what you are seeing on the console, right?) is:
qwerty "what"
followed by return (no line feed), overwritten by:
' 1 '
then \n
This suggests that the string you are supplying (from a file?) includes a terminating return character.
-32391663 0 PouchDB on Hybrid Cordova App Not workingAm new to Hybrid app development, Am using Cordova v5, Ionic and PouchDB for my app. It seems everything works fine on Ionic serve command, but any operation on PouchDB seems to be not working on actual devices running Android Lollipop.
Am explicitly specifying 'WebSQL' when creating pouchDB object. I don't know whether Am missing any steps.
Here is the code
var houselst = JSON.parse('<some json string>'); new PouchDB('SH_HouseVisitDB', { adapter: 'websql' }).destroy().then(function () { return new PouchDB('SH_HouseVisitDB'); }).then(function (db) { var doc = { "_id": "houselist", "items": houselst }; //insert the doc to pouchDB db.put(doc); db.get('houselist').then(function (doc) { vm.houselist = _.sortBy(doc.items, "name"); db.close(); }); } Any help will be greatly appreciated.
-36138295 0The classic answer to such questions is to create a SQL VIEW.
Views are like dynamic virtual tables - in queries you use the view name instead of a table name, and the DBMS runs the query defined by the view to produce the rows for the query on the view. You therefore see rows based on the data from the tables at the time you access the view, not at the time the view was created.
You would create this view with a statement such as
CREATE VIEW PROT_WITH_UNITS AS SELECT * FROM dna_extraction_protocols P JOIN measurement_units M ON P.volume_unit = M.id This will give you a view with all columns of both tables, pre-joined on (what I presume to be) the required foreign key.
If you get the definition wrong you can drop views just like tables, so you should get there eventually.
-2726557 0You could do this with a bit simpler logic using KeyPress instead, like this:
string buffer = ""; //buffer to store what the user typed: n, no, not, etc... void gkh_KeyPress(object sender, KeyPressEventArgs e) { buffer += e.KeyChar; //add key to the buffer, then check if we've made progress if (buffer.IndexOf("note") > -1) { this.Show(); //"notes" matched completely buffer = ""; //reset for another run } else if ("note".IndexOf(buffer) != 0) { buffer = ""; //Another key not in sequence was hit } }
-3434046 0 Problem in M3G rendering in J2ME I have made 3 planes and positioned them in a way that they make a corner of cube. (For some reasons I don't want to make a cube object). The 3 planes have 3 different Texture2Ds with different images. The strange problem is when I render the 3 objects and start rotating the camera, in some perspectives some parts of these 3 planes don't get rendered. For example when I look straight at the corner a hole is created which is shaped as a triangle. This is the image of the problem in a netbeans emulator:
I put the red lines there so you can see the cube better. The other strange thing is that the problem resolves when I set the scale of the objects to 0.5 or less. By the way the camera is in its default position and the cube's center is at (0,0,0) and each plane has a width and height of 2. Does anyone have any ideas why these objects have a conflict with each other and how could I resolve this problem.
Thanks in advance
-15868328 0I've found what happens, and it can be usefull for others. @Mark Ormston was not so far : Cookies set with path /cas are send by IE10 to URL beginings with /cas-services
In my case /cas and /cas-services are not in the same WebApp and each have its own JSESSIONID. Sending JSESSIONID created for /cas to /cas-services lead to the problem describe above.
To correct, I simply rename /cas-services with /app-services (I guess that everything not beginning with /cas should work).
JM.
-40713800 0 Refactor an XPath expression: specify common subexpressions only onceI would like to summarize sub-expressions of the XPath expression specified as the test attribute of an <xsl:if> instruction, which could appear multiple times (and as part of different expressions) in my xslt stylesheet. For example:
<xsl:if test=" preceding-sibling::node()[ (self::a and @attr1='a1') or (self::b and @attr2='b1') ] or following-sibling::node()[ (self::a and @attr1='a1') or (self::b and @attr2='b1') ] "> ... </xsl:if> As you can see the sub-expression (self::a and ...) is repeated but the nodes upon which the predicate is applied may be different.
So I am using wordpress to build a website with the soundcloud plugin. The shortcode for 3 out of 4 songs is working fine but the fourth just shows up as "Track currently not available". The track is playable on soundcloud just fine.
Here is the webpage where its happening:
http://lostintheholler.com/epk/?page_id=13
and here is the track on soundcloud:
https://soundcloud.com/lostintheholler/07-take-it-and-go
The wordpress embed code from soundcloud works fine too but it doesn't have the look you get from using the plugin.
Thanks!
-34917463 0 How to get value of selected item from dropdown in jquery UI tabs contentI am using jquery UI tabs and I have text filed and dropdown to select in tab's content, I am getting the value from text field but not from dropdown select item, can any one please help me, my project is in yii
<html lang="en"> <head> <meta charset="utf-8"> <title>jQuery UI Tabs - Vertical Tabs functionality</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script> <link rel="stylesheet" href="/resources/demos/style.css"> <script> $(function() { $( "#tabs" ).tabs().addClass( "ui-tabs-vertical ui-helper-clearfix" ); $( "#tabs li" ).removeClass( "ui-corner-top" ).addClass( "ui-corner-left" ); }); </script> <style> .ui-tabs-vertical { width: 55em; } .ui-tabs-vertical .ui-tabs-nav { padding: .2em .1em .2em .2em; float: left; width: 12em; } .ui-tabs-vertical .ui-tabs-nav li { clear: left; width: 100%; border-bottom-width: 1px !important; border-right-width: 0 !important; margin: 0 -1px .2em 0; } .ui-tabs-vertical .ui-tabs-nav li a { display:block; } .ui-tabs-vertical .ui-tabs-nav li.ui-tabs-active { padding-bottom: 0; padding-right: .1em; border-right-width: 1px; } .ui-tabs-vertical .ui-tabs-panel { padding: 1em; float: right; width: 40em;} </style> </head> <body> <?php echo $model->name;?> <div id="tabs"> <ul> <li><a href="#tabs-1">Nunc tincidunt</a></li> <li><a href="#tabs-2">Basic Information</a></li> <li><a href="#tabs-3">Report</a></li> <li><a href="#tabs-4">Set schedule</li> </ul> <div id="tabs-1"> <h2>Content heading 1</h2> <?php echo 'la la';?> </div> <div id="tabs-2"> <h2>Content heading 2</h2> </div> <div id="tabs-3"> <div class="form"> <?php $form=$this->beginWidget('CActiveForm', array( 'id'=>'message-form', 'htmlOptions'=>array('target'=>'_blank'), 'enableClientValidation'=>true, 'clientOptions'=>array( 'validateOnSubmit'=>true, ), )); ?> <p class="note">Fields with <span class="required">*</span> are required.</p> <?php echo $form->errorSummary($model_report_form); ?> <table class="table"> <tr> <td><?php echo $form->labelEx($model,'month'); $months = array( '01'=>'January', '02'=>'February', '03'=>'March', '04'=>'April', '05'=>'May', '06'=>'June', '07'=>'July', '08'=>'August', '09'=>'September', '10'=>'October', '11'=>'November', '12'=>'December', ); //$stat = array('13' => Yii::t('month','ALL')); echo $form->dropdownlist($model_report_form,'month',$months,array('empty' => '--Select a month--')); //echo $form->textField($model,'end_date'); ?></td> <td><?php echo $form->labelEx($model_report_form,'year'); $years = array( '2016'=>'2016', '2017'=>'2017', '2018'=>'2018', '2019'=>'2019', '2020'=>'2020', '2021'=>'2021', '2022'=>'2022', '2023'=>'2023', '2024'=>'2024', '2025'=>'2025', ); //$stat = array('3000' => Yii::t('year','ALL')); echo $form->dropdownlist($model_report_form,'year',$years,array('empty' => '--Select a year--')); //echo $form->textField($model,'end_date'); ?></td> </tr> <tr> <?php echo $form->hiddenField($model_report_form, 'employee',array('value'=>$model->employee_id)); ?> <?php echo $form->hiddenField($model_report_form, 'report_type',array('value'=>'1')); ?> </tr> </table> <div class="row buttons"> <?php echo CHtml::submitButton('Get Report',array('class'=>'btn btn-primary btn-block')); ?> </div> <?php $this->endWidget(); ?> </div><!-- form -->
-39281702 0 Anand S Kumar's answer doesn't round to the nearest quarter hour, it cuts off the minutes to the nearest 15 minutes below it.
Actually, in your example 2015-07-18 13:53:33.280 should round to 2015-07-18 14:00:00.000 since 53:33.280 is closer to 60 minutes than 45 minutes.
I found an more robust answer for rounding in this post.
For your situation this should work:
import datetime def round_time(time, round_to): """roundTo is the number of minutes to round to""" rounded = time + datetime.timedelta(minutes=round_to/2.) rounded -= datetime.timedelta(minutes=rounded.minute % round_to, seconds=rounded.second, microseconds=rounded.microsecond) return rounded dt['dtcolumn'] = df['dtcolumn'].apply(lambda x: round_time(x))
-20643311 0 You can use the collect_max UDF from Brickhouse ( http://github.com/klout/brickhouse ) to solve this problem, passing in a value of 1, meaning that you only want the single max value.
select array_index( map_keys( collect_max( carrier_id, meandelay, 1) ), 0 ) from flightinfo; Also, I've read somewhere that the Hive max UDF does allow you to access other fields on the row, but I think its easier just to use collect_max.
I am trying to write a method in Java that turns number grades into letter grades, but there is an error with the returns that I do not understand why. Any input would be appreciated.
import java.util.*; import static java.lang.System.out; public class Lab26 { public static void main(String[] args) { } public static String letterGrade(double grade) { String a = "A"; String b = "B"; String c = "C"; String d = "D"; String f = "F"; if (grade <= 100 && grade >= 90) { return a; } else if (grade < 90 && grade >= 80) { return b; } else if (grade < 80 && grade >= 70) { return c; } else if (grade < 70 && grade >= 60) { return d; } else if (grade < 60) { return f; } } }
-31597500 0 Update some json items in existing file i'm trying to do a simple script to manipulate some json, so i decode the json file , create a foreach to make some ifs looking for information with live games, live.json file:
{ Match: [ { Id: "348324", Date: "2015-07-19T21:30:00+00:00", League: "Brasileirao", Round: "14", HomeTeam: "Joinville", HomeTeam_Id: "1208", HomeGoals: "1", AwayTeam: "Ponte Preta", AwayTeam_Id: "745", AwayGoals: "1", Time: "67", Location: "Arena Joinville", HomeTeamYellowCardDetails: { }, AwayTeamYellowCardDetails: { }, HomeTeamRedCardDetails: { }, AwayTeamRedCardDetails: { } }, { Id: "348319", Date: "2015-07-19T21:30:00+00:00", League: "Brasileirao", Round: "14", HomeTeam: "Cruzeiro", HomeTeam_Id: "749", HomeGoals: "1", AwayTeam: "Avai FC", AwayTeam_Id: "1203", AwayGoals: "1", Time: "Finished", Location: "Mineirão", HomeTeamYellowCardDetails: { }, AwayTeamYellowCardDetails: { }, HomeTeamRedCardDetails: { }, AwayTeamRedCardDetails: { } } Check the comments in the code i specify what i want in each part.
<?php $json_url = "http://domain.com/live.json"; // the file comes with live games $json = file_get_contents($json_url); $links = json_decode($json, TRUE); foreach($links["Match"] as $key=>$val) { if($val['Id'] == "live games id") // i want to live.json games ids match with the games with the same id in file.json // i only want to update the items below, and { $links["Match"][$key]['Time'] = ['Time']; // in the end i just want to get the item Time to update file.json in item time for the game with the same id $links["Match"][$key]['HomeGoals'] = ['HomeGoals']; // similar to what i want with Time $links["Match"][$key]['AwayGoals'] = ['AwayGoals']; } } $fp = fopen( "file.json","w+"); // this file have the list of all games including the ones that came from live.json, the structure are exactly the same. fwrite($fp,json_encode($links)); fclose($fp); ?> The content of new file.json
{ Match: [ { Id: "348324", Date: "2015-07-19T21:30:00+00:00", League: "Brasileirao", Round: "14", HomeTeam: "Joinville", HomeTeam_Id: "1208", HomeGoals: "1", AwayTeam: "Ponte Preta", AwayTeam_Id: "745", AwayGoals: "1", Time: "69", Location: "Arena Joinville", HomeTeamYellowCardDetails: { }, AwayTeamYellowCardDetails: { }, HomeTeamRedCardDetails: { }, AwayTeamRedCardDetails: { } }, { Id: "348319", Date: "2015-07-19T21:30:00+00:00", League: "Brasileirao", Round: "14", HomeTeam: "Cruzeiro", HomeTeam_Id: "749", HomeGoals: "1", AwayTeam: "Avai FC", AwayTeam_Id: "1203", AwayGoals: "1", Time: "Finished", Location: "Mineirão", HomeTeamYellowCardDetails: { }, AwayTeamYellowCardDetails: { }, HomeTeamRedCardDetails: { }, AwayTeamRedCardDetails: { } } Somebody can help ? What is the best approach to do this ?
-3734371 0 How to avoid cyclic behaviour with Castle Windsor's CollectionResolver?I am using Castle Windsor 2.5 in my application. I have a service which is a composite that acts as a distributor for objects that implement the same interface.
public interface IService { void DoStuff(string someArg); } public class ConcreteService1 : IService { public void DoStuff(string someArg) { } } public class ConcreteService2 : IService { public void DoStuff(string someArg) { } } public class CompositeService : List<IService>, IService { private readonly IService[] decoratedServices; CompositeService(params IService[] decoratedServices) { this.decoratedServices = decoratedServices; } public void DoStuff(string someArg) { foreach (var service in decoratedServices) { service.DoStuff(someArg); } } } The problem I have is that using config such as that shown below causes Windsor to report that "A cycle was detected when trying to resolve a dependency."
windsor.Register( Component .For<IService>() .ImplementedBy<CompositeService>(), Component .For<IService>() .ImplementedBy<ConcreteService1>(), Component .For<IService>() .ImplementedBy<ConcreteService2>() ); This cyclic behaviour seems to be at odds with the standard (non-collection based) behaviour that can be used to implenent the decorator pattern, where the component being resolved is ignored and the next registered component that implements the same interface is used instead.
So what I'd like to know is whether or not there is a way to make Windsor exclude the CompositeService component when it's resolving the IService services for the decoratedServices property. The decoratedServices property should contain two items: an instance of ConcreteService1, and an instance of ConcreteService2. I'd like to do this without explicitly specifying the dependencies.
Yes, you can just use +- operators if you want to add or subtract two numbers.
If you want to truncate the result back to 16 bits, just assign the result to a 16 bit wire/register, and it will automatically drop the upper bits and just assign the lower 16 bits to out. In some cases this may create a lint warning, so you may want to assign the result to an intermediate variable first, and then do an explicit part select.
wire [15:0] out; wire [15:0] A; wire [31:0] A_rotate; A_rotate = {A,A} << N; out = A_rotate[15:0];
-15837751 0 Can an aggregates invariant include a rule based on information from elsewhere?
Aggregates can always use the informations in their own states and the argument that their commands recieves.
Someone use to access applicative services via singletons, service locators and so on, but IMO, that's a smell of tightly coupled applications. They forget that methods' arguments are effective dependency injectors! :-)
In DDD can an aggregates invariant include a rule based on information in a another aggregate?
No.
Except if the second aggregate is provided via commands' arguments, of course.
WARNING ! ! !
I have an entity called Asset (equipment)...
... (and a) second aggregate called AssetType...
The last time that I had to cope with a similar structure, it was a pain.
Chances are that you are choosing the wrong abstractions.
have I got my invariant wrong?
Probably... Did you asked to the domain expert? Does he talks about "TagTypes"?
You should never abstract on your own.
Entities of type X holding a reference to an instance of an X-Type are almost always a smell of over-abstraction, that in the hope of reuse, makes the model rigid and inflexible to business evolution.
ANSWER
If (and only if) the domain expert actually described the model in these terms, a possible approach is the following:
AssetType class with a factory method that turns an IEnumerable<Tag> into a TagSet and throws either MissingMandatoryTagException or UnexpectedTagException if some of the tag is missing or unexpected. Asset class, a command RegisterTags would accept an AssetType and an IEnumerable<Tag>, throwing the MissingMandatoryTagException and WrongAssetTypeException (note how important are exceptions to ensure invariants).edit
something like this, but much more documented:
public class AssetType { private readonly Dictionary<TagType, bool> _tagTypes = new Dictionary<TagType, bool>(); public AssetType(AssetTypeName name) { // validation here... Name = name; } /// <summary> /// Enable a tag type to be assigned to asset of this type. /// </summary> /// <param name="type"></param> public void EnableTagType(TagType type) { // validation here... _tagTypes[type] = false; } /// <summary> /// Requires that a tag type is defined for any asset of this type. /// </summary> /// <param name="type"></param> public void RequireTagType(TagType type) { // validation here... _tagTypes[type] = false; } public AssetTypeName Name { get; private set; } /// <summary> /// Builds the tag set. /// </summary> /// <param name="tags">The tags.</param> /// <returns>A set of tags for the current asset type.</returns> /// <exception cref="ArgumentNullException"><paramref name="tags"/> is <c>null</c> or empty.</exception> /// <exception cref="MissingMandatoryTagException">At least one of tags required /// by the current asset type is missing in <paramref name="tags"/>.</exception> /// <exception cref="UnexpectedTagException">At least one of the <paramref name="tags"/> /// is not allowed for the current asset type.</exception> /// <seealso cref="RequireTagType"/> public TagSet BuildTagSet(IEnumerable<Tag> tags) { if (null == tags || tags.Count() == 0) throw new ArgumentNullException("tags"); TagSet tagSet = new TagSet(); foreach (Tag tag in tags) { if(!_tagTypes.ContainsKey(tag.Key)) { string message = string.Format("Cannot use tag {0} in asset type {1}.", tag.Key, Name); throw new UnexpectedTagException("tags", tag.Key, message); } tagSet.Add(tag); } foreach (TagType tagType in _tagTypes.Where(kvp => kvp.Value == true).Select(kvp => kvp.Key)) { if(!tagSet.Any(t => t.Key.Equals(tagType))) { string message = string.Format("You must provide the tag {0} to asset of type {1}.", tagType, Name); throw new MissingMandatoryTagException("tags", tagType, message); } } return tagSet; } } public class Asset { public Asset(AssetName name, AssetTypeName type) { // validation here... Name = name; Type = type; } public TagSet Tags { get; private set; } public AssetName Name { get; private set; } public AssetTypeName Type { get; private set; } /// <summary> /// Registers the tags. /// </summary> /// <param name="tagType">Type of the tag.</param> /// <param name="tags">The tags.</param> /// <exception cref="ArgumentNullException"><paramref name="tagType"/> is <c>null</c> or /// <paramref name="tags"/> is either <c>null</c> or empty.</exception> /// <exception cref="WrongAssetTypeException"><paramref name="tagType"/> does not match /// the <see cref="Type"/> of the current asset.</exception> /// <exception cref="MissingMandatoryTagException">At least one of tags required /// by the current asset type is missing in <paramref name="tags"/>.</exception> /// <exception cref="UnexpectedTagException">At least one of the <paramref name="tags"/> /// is not allowed for the current asset type.</exception> public void RegisterTags(AssetType tagType, IEnumerable<Tag> tags) { if (null == tagType) throw new ArgumentNullException("tagType"); if (!tagType.Name.Equals(Type)) { string message = string.Format("The asset {0} has type {1}, thus it can not handle tags defined for assets of type {2}.", Name, Type, tagType.Name); throw new WrongAssetTypeException("tagType", tagType, message); } Tags = tagType.BuildTagSet(tags); } }
-27998642 0 Laravel assertions full list PHP Laravel framework provides assertion methods like ->assertTrue(), ->assertFalse() for unit testing. However, I cannot find a full list of them. Are they documented somewhere? If not, where can I find them in Laravel source?
the answer is YES and NO. it depends on the processed data dynamic range
you should use more fixed point formats for different stage of signal processing
This means you need some number of fixed point formats
To be more specific then you need add the block diagram of your processing pipeline
The real question always stays if such implementation is faster then floating point ...
Suppose I have a function:
public static IList GetAllItems(System.Type T) { XmlSerializer deSerializer = new XmlSerializer(T); TextReader tr = new StreamReader(GetPathBasedOnType(T)); IList items = (IList) deSerializer.Deserialize(tr); tr.Close(); return items; } In order to retrieve a list of Articles, I would like to call GetAllItems(typeof(Article)) instead of GetAllItems(typeof(List<Article>)) but still return a list.
Question: how can I, without changing the function declaration/prototype, avoid requiring unnecessary List<> portion when calling this function?
That is, I am looking for something like this:
public static IList GetAllItems(System.Type T) { /* DOES NOT WORK: Note new List<T> that I want to have */ XmlSerializer deSerializer = new XmlSerializer(List<T>); TextReader tr = new StreamReader(GetPathBasedOnType(T)); IList items = (IList) deSerializer.Deserialize(tr); tr.Close(); return items; }
-25526875 0 PHP Global Variables across .php files I have two files that get loaded on a page (body.php and footer.php).
In body I have:
<?php global $pageName = "foo";?> In footer I have:
<?php echo $pageName;?> However, it echo's out nothing. Am I missing something?
-5914626 0 Extracting html tables from websiteI am trying to use XML, RCurl package to read some html tables of the following URL http://www.nse-india.com/marketinfo/equities/cmquote.jsp?key=SBINEQN&symbol=SBIN&flag=0&series=EQ#
Here is the code I am using
library(RCurl) library(XML) options(RCurlOptions = list(useragent = "R")) url <- "http://www.nse-india.com/marketinfo/equities/cmquote.jsp?key=SBINEQN&symbol=SBIN&flag=0&series=EQ#" wp <- getURLContent(url) doc <- htmlParse(wp, asText = TRUE) docName(doc) <- url tmp <- readHTMLTable(doc) ## Required tables tmp[[13]] tmp[[14]] If you look at the tables it has not been able to parse the values from the webpage. I guess this due to some javascipt evaluation happening on the fly. Now if I use "save page as" option in google chrome(it does not work in mozilla) and save the page and then use the above code i am able to read in the values.
But is there a work around so that I can read the table of the fly ? It will be great if you can help.
Regards,
-8694330 0You can simplify to:
SELECT expire_date - (expire_date - now()) - interval '1 month' FROM "License" WHERE license_id = 10 This is valid without additional brackets because subtractions are evaluated from left to right.
In my first version the one necessary pair of brackets was missing, though.
This form of the query also prevents an error in the case that license should not be unique. You would get multiple rows instead. In that case, and if you should need it, add LIMIT 1 guarantee a single value.
@Milen diagnosed the cause of the error correctly. Experiment with these statements to see:
SELECT interval (interval '1 month'); -- error SELECT (interval '1 month')::interval; -- no error However, the cure is simpler. Just don't add another cast, it is redundant.
-23629056 0 WinForms and WebService in 1 solutionHow to have a WinForms app that has a ASP.NET WebSite as part of the Solution.
What I would like to do is as my WinForms app start the ASP.NET Service also starts.
When the Winforms app closes, I want to shutdown the ASP.NET Service.
Main Objective
Essentially my objective is to be able to view a Silverlight XAP file in my WinForms BrowserControl.
The XAP will not function correctly because of security issues, and it needs to access files (images/videos) from the filesystem.
-34358625 0Correct way to solve this issue is as follows:
Template.DoPolls.helpers({ polls: function() { var user = Meteor.userId() return Polls.find({voters: {$ne: user}}); } }); where $ne look over the voters array and if it finds the userId then doesn't show that poll.
To achieve the opposite (so only polls where the user has voted the helper would be:
Template.PollsDone.helpers({ polls: function() { var user = Meteor.userId() return Polls.find({voters: {$in: [ user ] }}); } });
-36542604 0 div does not cover full width <!DOCTYPE html> <html lang="en-us"> <head> <title>Golden Ratio</title> <style> html, body { padding: 0; margin: 0; } .wrapper { background-color:#DFE2DB; margin: 0 auto; padding: 10px; width: 1080px; border-radius: 10px; border: 5px solid #fff; box-shadow: 7px 7px 5px #888888; } .banner{ border: 5px solid #558C89; height: 200px; } .content_area{ float:left; width:750px; margin: 20px 0 20px 0; padding: 10px; height:400px; border: 2px solid #D9853B; } .sidebar{ float:right; width:250px; height:400px; margin: 20px 10px; padding: 10px; border: 2px solid #2B2B2B; } footer{ clear:both; width:auto; color:#fff; height:40px; padding:10px; text-shadow:0.1em 0.1em #E9E581; text-align:center; border: 3px solid #fff; } .announcement_section{ height:40px; border: 2px solid #4499cc; } #nav ul ul { display: none; } #nav ul li:hover > ul { display: block; } #nav ul{ background: #efefef; background: linear-gradient(top, #efefef 0%, #bbbbbb 100%); background: -moz-linear-gradient(top, #efefef 0%, #bbbbbb 100%); background: -webkit-linear-gradient(top, #efefef 0%,#bbbbbb 100%); box-shadow: 0px 0px 9px rgba(0,0,0,0.15); padding: 0 20px; border-radius: 10px; list-style: none; position: relative; display: inline-table; } #nav ul:after { content: ""; clear: both; display: ; } #nav ul li { float: left; } #nav ul li:hover { background: #4b545f; background: linear-gradient(top, #4f5964 0%, #5f6975 40%); background: -moz-linear-gradient(top, #4f5964 0%, #5f6975 40%); background: -webkit-linear-gradient(top, #4f5964 0%,#5f6975 40%); } #nav ul li:hover a { color: #fff; } #nav ul li a { display: block; padding: 25px 40px; color: #757575; text-decoration: none; } #nav ul ul { background: #5f6975; border-radius: 0px; padding: 0; position: absolute; top: 100%; } #nav ul ul li { float: none; border-top: 1px solid #6b727c; border-bottom: 1px solid #575f6a; position: relative; } #nav ul ul li a { padding: 15px 40px; color: #fff; } #nav ul ul li a:hover { background: #6699aa; } #nav ul ul ul { position: absolute; left: 100%; top:0; } </style> </head> <body bgcolor="#bbccdd"> <div class="wrapper"> <div class="banner"> <h1>banner here</h1> </div> <div id="nav"> <ul> <li><a href="#">Home</a></li> <li><a href="#">Registration</a> <ul> <li><a href="#">Registration FAQs</a></li> <li><a href="#">How to register</a></li> <li><a href="#">Register now</a> <ul> <li><a href="#">register1</a></li> <li><a href="#">register1</a></li> </ul> </li> </ul> </li> <li><a href="#">About Us</a> <ul> <li><a href="#">register2</a></li> <li><a href="#">register2</a></li> </ul> </li> <li><a href="#">Contact Us</a></li> </ul> </div> <div class="content_area"> <h1>content area</h1> </div> <div class="sidebar"> <h1>News here</h1> </div> <footer> <p>All rights reserved</p> </footer> </div> </body> </html> My code as above has one problem: my navigation bar does not extend to cover the full width but everything else works fine. what might be the problem. I have tried width:100% on the nav but seems not work. how do i fix this
-23569833 0$("#output1 > ins,#output1 del").first()
-10965542 0 Adding one character to string In C++:
If I want to add 0x01 to the string text I would do: text += (char)0x01;
If I want to add 0x02 to the string text I would do: text += (char)0x02;
If I want to add 0x0i (were i is an unsinged int between 0 and 9), what could I do?
EDIT: I probably wasn't quite clear. So by 0x01, I mean the character given in Hex as 01. So in the above if i is the integer (in decimal) say 3, then I would want to add 0x03 (so this is not the character given in decimal as 48 + 3).
-6112638 0One difference I can think of is, the way you bind HTML/ASP controls
--HTML button control-- <input type = "button" id = "myButtonHTML" /> --ASP button control-- <asp:button runat = "server" id = "myButtonASP" /> the way you bind this in javascript will be as follows
--HTML control-- document.getElementById("#myButtonHTML").value AND --ASP control-- document.getElementById("#myButtonASP.ClientID").value
-12428700 0 Adding belong_to and has_many lines to your models makes Rails aware of their relationship and generates helper methods, but does not create FKs at the database level. To do that, you need to create and run a migration:
rails g migration add_level_id_to_students level_id:integer then rake db:migrate
If you want to generate a model with the foreign key part of it, you can use the references shortcut: rails g model Student name:string level:references
Check out the Rails guides for more information!
-4754972 0 CodeBlocks: How to run after building from custom MakefileI have set up CodeBlocks to build from a custom Makefile. Build is working fine, but I am not able to run the code from CodeBlocks.
To build the project in command prompt, I use simple commands make and to clean it is make clean. It generates the executable: main that I run by ./main
I am trying to map this to the settings available in codeblocks which has the following values.
$make -f $makefile $target $make -f $makefile $file$make -f $makefile clean$targetHow can I do the mapping and how to run the project?
-34566973 0It means literally in the shape of the Greek letter rho, which is "ρ". The idea is that if you map the values out as a graph, the visual representation forms this shape. You could also think of it as "d" shaped or "p" shaped. But look carefully at the font and notice that the line or stem extends slightly past the loop, while it doesn't on a rho. Rho is a better description of the shape because the loop never exits; i.e., there shouldn't be any lines leading out of the loop. That and mathematicians love Greek letters.
You have some number of values which do not repeat; these form a line or the "stem" of the "letter". The values then enter a loop or cycle, forming a circle or the "loop" of the "letter".
For example, consider the repeating decimals 7/12 (0.5833333...) and 3227/55 (5.81441441444...). If you make your sequence the digits in the number, then you can graph these out to form a rho shape. Let's look at 3227/55.
You can graph it like so:
5 -> 8 -> 1 ^ \ / v 4 <- 4 You can see this forms a "ρ" shape.
-38978542 0 I am getting a segmentation error in PRIME1 on spoj. How should I eradicate it?My answer to problem PRIME1 please explain me where am I wrong. I am receiving a segmentation error.
here it is:
#include<cstdlib> #include<iostream> using namespace std; int main(int argc, char** argv) { int t=0,i=0,m=0,n=0; cin>>t; while(t--&&t<=10) { cin>>m>>n; if(m>=1&&n-m<=100000) { int prime[n]; for(i=0;i<n;i++) prime[i]=1; for (int i=2; i*i<=n; i++) { if (prime[i] == true) { for (int j=i*2; j<=n; j += i) prime[j] = false; } } for (int k=m+1; k<n; k++) if (prime[k]) cout <<k<<endl; } } return 0; }
-19963428 0 Use Inversion Of Control (IOC) and the Service Locator pattern to create a shared data service they both talk too. I notice your mvvm-light tag; I know a default Mvvm-light project uses a ViewModelLocator class and SimpleIOC so you can register a data service like below.
public class ViewModelLocator { static ViewModelLocator() { ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default); SimpleIoc.Default.Register<IDataService, DataService>(); } } An interface is used so we can swap out the DataService at will and even have a different one for design time. So you will create an interface that defines methods you will use and just make sure your DataService implements them. It is in your DataService implementation you will use the shared context / source.
public class DataService: IDataService { //USE SAME SOURCE (example EF) private SharedSourceEntities context; (blah blah)... } After you can inject it into both view models either in the constructor or calling the service locator.
Dependency Injection:
public class ViewModelOne: ViewModelBase { private readonly IDataService dataService; public ViewModelOne(IDataService dataService) { this.dataService = dataService; } } public class ViewModelTwo: ViewModelBase { private readonly IDataService dataService; public ViewModelTwo(IDataService dataService) { this.dataService = dataService; } } Service location:
SimpleIoc.Default.GetInstance<IDataService>();
-10699434 0 std::exception and boost::exception virtually: struct ConfigurationException : virtual std::exception, virtual boost::exception.catch (const std::exception& e).catch block).error_info to attach additional information (like your title and message).And in general, be careful when mixing Qt with exceptions.
-41001800 0Works for me (VS 2015 / v140) with the following minor modification:
#include <iostream> struct A {}; struct B {}; constexpr A aaa = {}; constexpr B bbb = {}; using A_type = decltype(aaa); using B_type = decltype(bbb); template <typename T> void foo(T, A_type) { std::cout << "a"; } template <typename T> void foo(T, B_type) { std::cout << "b"; } int main() { foo(0, aaa); foo(0, bbb); } But this variant yields the same error (not sure what to make of it):
template <typename T> struct TypeWrapper { using type = T; }; template <typename T> void foo(T, typename TypeWrapper<decltype(aaa)>::type) { std::cout << "a"; } template <typename T> void foo(T, typename TypeWrapper<decltype(bbb)>::type) { std::cout << "b"; }
-22245436 0 Default lazy loading is on or off in Nhibernate 2.x? I am migrating NHibernate 2.x to 3.x. I want to know the default value of Lazy loading in 2.x ? I use .Net 3.5 and asp.net MVC 1.0. I dont see any settings configured for lazy loading in nHibernate 2.x. I want to migrate for improving performance and introduce lazy loading.
Help appreciated.
-2851664 0I got it all sorted out now. My hook_theme is this:
function cssswitch_theme() { return array( 'cssswitch_display' => array( 'arguments' => array('node'), ), 'cssswitch_node_form' => array( 'arguments' => array('form' => NULL), 'template' => 'cssswitch-node-form.tpl.php', ), ); } I created the file themes/garland/cssswitch-node-form.tpl.php Then I can have control over where to put any form elements like this:
<style> #edit-hour-start-wrapper, #edit-minute-start-wrapper, #edit-ampm-start-wrapper, #edit-hour-end-wrapper, #edit-minute-end-wrapper, #edit-ampm-end-wrapper { float:left; margin-right:25px; } </style> <div id="regform1"> <?php print drupal_render($form['title']); ?> <?php print drupal_render($form['cssfilename']); ?> <fieldset class="group-account-basics collapsible"> <legend>Time Start</legend> <?php print drupal_render($form['hour_start']); ?> <?php print drupal_render($form['minute_start']); ?> <?php print drupal_render($form['ampm_start']); ?> </fieldset> <fieldset class="group-account-basics collapsible"><legend>Time end</legend> <?php print drupal_render($form['hour_end']); ?> <?php print drupal_render($form['minute_end']); ?> <?php print drupal_render($form['ampm_end']); ?> </fieldset> </div> <?php print drupal_render($form['options']); ?> <?php print drupal_render($form['author']); ?> <?php print drupal_render($form['revision_information']); ?> <?php print drupal_render($form['path']); ?> <?php print drupal_render($form['attachments']); ?> <?php print drupal_render($form['comment_settings']); ?> <?php print drupal_render($form); ?>
-15338582 0 MySQL - cannot add foreign key I have a table in MySQL InnoDB created like that:
CREATE TABLE `users` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `type` enum('MANUAL','FACEBOOK') NOT NULL DEFAULT 'MANUAL', `role` enum('COOK','HOST','ALL') NOT NULL DEFAULT 'ALL', `about_me` varchar(1000) DEFAULT NULL, `food_preferences` varchar(1000) DEFAULT NULL, `cooking_experience` varchar(1000) DEFAULT NULL, `with_friend` bit(1) DEFAULT b'0', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 Next I try added a table with such a statement (no foreign keys added while creating the table as had problem with that):
CREATE TABLE `messages` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `from` bigint(20) NOT NULL, `to` bigint(20) NOT NULL, `content` varchar(10000) NOT NULL, `timestamp_sent` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `timestamp_read` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 Having tables created, I need to finally add foreign keys on 'from' and 'to' fields referencing 'users'.'id' field:
ALTER TABLE `messages` ADD CONSTRAINT `messages_users_fk` FOREIGN KEY (`from` , `to` ) REFERENCES `users` (`id` , `id` ) ON DELETE SET NULL ON UPDATE CASCADE , ADD INDEX `messages_users_fk_idx` (`from` ASC, `to` ASC) The error I get is ERROR: Error 1822: Failed to add the foreign key constaint. Missing index for constraint 'messages_users_fk' in the referenced table 'users'. But 'users' table has a PRIMARY index on 'id'...
Also tried to make a smaller step and add foreign key just for 'from field:
ALTER TABLE `messages` ADD CONSTRAINT `messages_users_fk` FOREIGN KEY (`from` ) REFERENCES `users` (`id` ) ON DELETE SET NULL ON UPDATE CASCADE , ADD INDEX `messages_users_fk_idx` (`from` ASC) ; The error is slightly different: ERROR: Error 1825: Failed to add the foreign key constraint on table 'messages'. Incorrect options in FOREIGN KEY constraint 'cook4food/messages_users_fk'.
The types of the fields are the same (bigint(20) NOT NULL) as it was suggested as the cause of the problem in other StackOverflow threads. My tables are not partitioned (MySQL manual states this as a limitation for having foreign key constraints in InnoDB). The 'messages' table stores no rows currently, so data stored can't be the issue in any manner. I'm stuck, please help.
-21669432 0 OAuth 2.0 authentication for mobile clientI am developing an app using node.js which will also have an mobile client. I am looking to make the authentication using OAuth 2.0. I have my own external server which will do client validation and generate tokens. Please help me know as to how can i achieve this using OAuth2orize or any other really good module.
-17506399 0Ok, I found out the answer and it's particularly simple. (Finally for days)
All I gotta do is just remove the collection, as well change the filter into checked. I also changed the additional_toppings into additional_topping_ids to return the array and I also add the accessible attribute.
Here are the codes:
f.input :additional_toppings, as: :check_boxes, checked: food.additional_topping_ids attr_accessible :name, :price, :quantity, :picture, :category_id, :info , :favourite, :weekly, :unlimited, :toppings, :tag_list, :additional_topping_ids has_many :categorizations has_many :additional_toppings, :through => :categorizations
-19918860 0 Your option #1 is not appropriate as written but close to an approach you should probably consider. You can add nest the views of different UIViewControllers however when you do so you should use the methods described in Managing Child View Controllers in a Custom Container so that the parent controller correctly manages its child controllers.
What does pipe character do in vim command mode?
For example, :vimgrep /pattern/ file | copen
Does it act like a pipe in Linux Command Line? Contents of vimgrep gets piped to copen?
Or does it separate commands like ; in Command Line?
I can do the following to check if the browser doesn't support column-count css3 property then use my own code:
if (!('WebkitColumnCount' in document.body.style || 'MozColumnCount' in document.body.style || 'OColumnCount' in document.body.style || 'MsColumnCount' in document.body.style || 'columnCount' in document.body.style)) {//my own code here} But how can I check that background-image animation support?
This type of changing image source with css3 only works on chrome browsers.
0%{background-image: url(image-1);} 50%{background-image: url(image-2);} 100%{background-image: url(image-3);} So, I wanted to know is there any technique that we can test that it is supported by the browser or not?
Update
I just tried like this code which is even not checking @keyframes style support:
if (('@keyframes' in document.body.style || '@-webkit-keyframes' in document.body.style)) { //if(!('from' in @keyframes || 'from' in @webkit-keyframes)){ //code in here alert('test'); //} } So even can I not test that @keyframes supported by browser or not?
Solution:
I've found from mdn
var animation = false, animationstring = 'animation', keyframeprefix = '', domPrefixes = 'Webkit Moz O ms Khtml'.split(' '), pfx = ''; if( elm.style.animationName !== undefined ) { animation = true; } if( animation === false ) { for( var i = 0; i < domPrefixes.length; i++ ) { if( elm.style[ domPrefixes[i] + 'AnimationName' ] !== undefined ) { pfx = domPrefixes[ i ]; animationstring = pfx + 'Animation'; keyframeprefix = '-' + pfx.toLowerCase() + '-'; animation = true; break; } } }
-27728804 0 First of all, Where(x => x is Video) can be replaced by OfType<Video>().
Second, for fluent syntax it's better to use ParallelEnumerable.ForAll extension method:
media.OfType<Video>() .AsParallel() .ForAll(this.Update)
-10192785 0 how to configure a vps server to send emails on linux I am planning to rent a vps outside my primary site
I want to configure this vps to send emails only not receive.
say at my primary site I have an smtp server smtp.xyz.com
I don't want to use this smtp server for the new vps
how can I configure sendmail/postfix to send emails from this vps?
-20698630 0An accept handler may only take an error code as a parameter, see: AcceptHandler.
I recommend making acceptor a member of CServerSocket then changing the call to async_accept to:
acceptor.async_accept(*socket, std::bind(&CServerSocket::OnAccept, this, std::placeholders::_1)); and accessing acceptor within the OnAccept member function.
The problem is that you're assigning the return value of volunteer.time_in.push back to volunteer.time_in. The return value is the new length of the array, not the array itself.
So change that line to just:
volunteer.time_in.push(date);
-38318805 0 Count the number of occurrences of each word I'm trying to count the number of occurrences of each word in the function countWords I believe i started the for loop in the function properly but how do I compare the words in the arrays together and count them and then delete the duplicates? Isn't it like a fibonacci series or am I mistaken? Also int n has the value of 756 because thats how many words are in the array and wordsArray are the elements in the array.
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> int *countWords( char **words, int n); int main(int argc, char *argv[]) { char buffer[100]; //Maximum word size is 100 letters FILE *textFile; int numWords=0; int nextWord; int i, j, len, lastChar; char *wordPtr; char **wordArray; int *countArray; int *alphaCountArray; char **alphaWordArray; int *freqCountArray; char **freqWordArray; int choice=0; //Check to see if command line argument (file name) //was properly supplied. If not, terminate program if(argc == 1) { printf ("Must supply a file name as command line argument\n"); return (0); } //Open the input file. Terminate program if open fails textFile=fopen(argv[1], "r"); if(textFile == NULL) { printf("Error opening file. Program terminated.\n"); return (0); } //Read file to count the number of words fscanf(textFile, "%s", buffer); while(!feof(textFile)) { numWords++; fscanf(textFile, "%s", buffer); } printf("The total number of words is: %d\n", numWords); //Create array to hold pointers to words wordArray = (char **) malloc(numWords*sizeof(char *)); if (wordArray == NULL) { printf("malloc of word Array failed. Terminating program.\n"); return (0); } //Rewind file pointer and read file again to create //wordArray rewind(textFile); for(nextWord=0; nextWord < numWords; nextWord++) { //read next word from file into buffer. fscanf(textFile, "%s", buffer); //Remove any punctuation at beginning of word i=0; while(!isalpha(buffer[i])) { i++; } if(i>0) { len = strlen(buffer); for(j=i; j<=len; j++) { buffer[j-i] = buffer[j]; } } //Remove any punctuation at end of word len = strlen(buffer); lastChar = len -1; while(!isalpha(buffer[lastChar])) { lastChar--; } buffer[lastChar+1] = '\0'; //make sure all characters are lower case for(i=0; i < strlen(buffer); i++) { buffer[i] = tolower(buffer[i]); } //Now add the word to the wordArray. //Need to malloc an array of chars to hold the word. //Then copy the word from buffer into this array. //Place pointer to array holding the word into next //position of wordArray wordPtr = (char *) malloc((strlen(buffer)+1)*sizeof(char)); if(wordPtr == NULL) { printf("malloc failure. Terminating program\n"); return (0); } strcpy(wordPtr, buffer); wordArray[nextWord] = wordPtr; } //Call countWords() to create countArray and replace //duplicate words in wordArray with NULL countArray = countWords(wordArray, numWords); if(countArray == NULL) { printf("countWords() function returned NULL; Terminating program\n"); return (0); } //Now call compress to remove NULL entries from wordArray compress(&wordArray, &countArray, &numWords); if(wordArray == NULL) { printf("compress() function failed; Terminating program.\n"); return(0); } printf("Number of words in wordArray after eliminating duplicates and compressing is: %d\n", numWords); //Create copy of compressed countArray and wordArray and then sort them alphabetically alphaCountArray = copyCountArray(countArray, numWords); freqCountArray = copyCountArray(alphaCountArray, numWords); int *countWords( char **wordArray, int n) { return NULL; int i=0; int n=0; for(i=0;i<n;i++) { for(n=0;n<wordArray[i];n++) { } } }
-8990789 0 Facebook share - phonegap I use this link to share url on facebook: http://m.facebook.com/sharer.php?u=http://google.com and it works fine on mobile devices.
How can I share text? I tried with &text= and &t= but when I click "Share" it opens a page that says: "Post a link to your profile" and share doesn't work.
Any help?
Thanks!
-28989357 0 Unable to click radio button in Internet explorer using Selenium webdriverI am not able to get the radio button clicked using Selenium web driver.
The html is as follows
<input name="PersonalDetails.Paperless" class="input-validation-error" id="Paperless" type="radio" data-val-required="Contract notes selection is required" data-val="true" value="true"/> The code to click is below. It works in Chrome and FireFox but not in Ie
driver.FindElement(By.CssSelector("label[for='OnlineAndPost']")).Click();
-25770507 0 Creating instances of a covariant type class from instances of a non-covariant one Suppose I've got a simple type class whose instances will give me a value of some type:
trait GiveMeJustA[X] { def apply(): X } And I've got some instances:
case class Foo(s: String) case class Bar(i: Int) implicit object GiveMeJustAFoo extends GiveMeJustA[Foo] { def apply() = Foo("foo") } implicit object GiveMeJustABar extends GiveMeJustA[Bar] { def apply() = Bar(13) } Now I have a similar (but unrelated) type class that does the same thing but is covariant in its type parameter:
trait GiveMeA[+X] { def apply(): X } In its companion object we tell the compiler how to create instances from instances of our non-covariant type class:
object GiveMeA { implicit def fromGiveMeJustA[X](implicit giveMe: GiveMeJustA[X]): GiveMeA[X] = new GiveMeA[X] { def apply() = giveMe() } } Now I'd expect implicitly[GiveMeA[Foo]] to compile just fine, since there's only one way to get a GiveMeA[Foo] given the pieces we have here. But it doesn't (at least not on either 2.10.4 or 2.11.2):
scala> implicitly[GiveMeA[Foo]] <console>:16: this.GiveMeA.fromGiveMeJustA is not a valid implicit value for GiveMeA[Foo] because: hasMatchingSymbol reported error: ambiguous implicit values: both object GiveMeJustAFoo of type GiveMeJustAFoo.type and object GiveMeJustABar of type GiveMeJustABar.type match expected type GiveMeJustA[X] implicitly[GiveMeA[Foo]] ^ <console>:16: error: could not find implicit value for parameter e: GiveMeA[Foo] implicitly[GiveMeA[Foo]] ^ If we get rid of our irrelevant GiveMeJustA instance, it works:
scala> implicit def GiveMeJustABar: List[Long] = ??? GiveMeJustABar: List[Long] scala> implicitly[GiveMeA[Foo]] res1: GiveMeA[Foo] = GiveMeA$$anon$1@2a4f2dcc This is in spite of the fact that there's no way we can apply GiveMeA.fromGiveMeJustA to this instance to get a GiveMeA[Foo] (or any subtype of GiveMeA[Foo]).
This looks like a bug to me, but it's possible that I'm missing something. Does this make any sense? Is there a reasonable workaround?
-1354539 0I don't believe there is complete documentation prepared for the WPF Toolkit components at this time.
There are beta docs for the DataGrid itself here, but I couldn't find anything w.r.t. the virtualization extensions, sorry!
-6271459 0Here is the WMI way to find it. I give you the PowerShell writting, but you can transform it for VBScript or C# easily
PS C:\> (Get-WmiObject Win32_NTDomain).DomainName Be careful, the Domain part of the 'pre windows 2000 domain' can be completly different from the user Principal Name (user@domain) use to logon onto Active-Directory. the DOMAIN is the Primary Domain Controleur name or the Netbios domain name. DOMAIN is created during domain creation, by default it's part of the DNS name, but it can be completly changed during domain creation.
You can find it with nETBIOSName attribute :
ldifde -f netbios.ldf -d "CN=Partitions,CN=Configuration,DC=your-DNS-Name" -r "(netbiosname=*)" Edited
Here is the CSharp code
ManagementObjectSearcher domainInfos1 = new ManagementObjectSearcher("select * from WIN32_NTDomain"); foreach (ManagementObject domainInfo in domainInfos1.Get()) { Console.WriteLine("Name : {0}", domainInfo.GetPropertyValue("Name")); Console.WriteLine("Computer/domain : {0}", domainInfo.GetPropertyValue("Caption")); Console.WriteLine("Domain name : {0}", domainInfo.GetPropertyValue("DomainName")); Console.WriteLine("Status : {0}", domainInfo.GetPropertyValue("Status")); }
-28490926 0 OK guys, here is the answer.
Change the session state from InProc, in my case to SQLServer, it's been 22 hours since a login redirect, which hasn't happened before, so I think it's safe to say the problem is solved and that was the answer.
-5848186 0 regex to replace 0 in list but not 0 of 10, 20, 30, etc. - using js replaceI'm trying to create a regex to replace zeros in list with an empty value but not replace the zeros in ten, twenty, thirty, etc.
list = 0,1,0,20,0,0,1,,1,3,10,30,0
desired list = ,1,,20,,,1,,1,3,10,30,
Using this in the javascript replace function
Any help/tips appreciated!
-13499017 0 Tracking php process on frameworkI have a php framework is running on linux machine basicly every requests redirect to index.php by .htaccess
Options +FollowSymLinks IndexIgnore */* RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} !.*jpg$|!.*gif$|!.*png$|!.*jpeg$|!.*bmp$ RewriteRule . index.php One of my php started to run %100 CPU i want to track which progress is that but when i check process with
ps aux | grep 23791
user 23791 0.3 0.8 30460 15288 ? S 12:32 0:01 /usr/bin/php /home/user/public_html/index.php As normal, request redirect to index.php.But i have to find which request is this.
Is there any way to debug this problem ?
Thanks.
-32578695 0 Sublime text2, Replace all messes up the upper-case lower-caseThe replace all option messes up the lower-case formation in Sublime Text 2. For example:
When I want to replace all the classes named "example1" to "hidethis"
I get "hideThis".
This is getting annoying, especially when I am going to do this procedure to URLs.
Is there any way to disable that option?
-3884911 0function createMarker(latlng, imageURL, imageSize) { var marker = new GIcon(G_DEFAULT_ICON, imageURL); marker.iconSize = imageSize; marker.shadow = null; return new GMarker(latlng, { icon: marker }); } You'll also want to set iconSize if you're using a maker that isn't the same size as the standard one.
-23224993 0 Reverse comma separated column values in SQL ServerI have following column which contains values separated by comma. How do I convert it to a result set which gives following out put in SQL Server?
DECLARE @TBL AS TABLE (COLUMN1 NVARCHAR(100)) INSERT INTO @TBL SELECT 'AUD,BRL,GBP,CAD,CLP' SELECT COLUMN1 FROM @TBL COLUMN1 ------- AUD,BRL,GBP,CAD,CLP Result I wanted:
COLUMN1 ------- AUD BRL GBP CAD CLP
-21386161 0 SVN confusion: "local add, incoming add upon merge" What do the words actually refer to? I'm pretty new to subversion and the docs just aren't making sense to me. I was wondering if someone could break down this error message (from svn st) into plain English, as well as the other one I get local delete, incoming delete upon merge.
To be precise about my question:
local add (or local delete) refer to?incoming add (or incoming delete) refer to?What's mystifying to me is that the branch has absolutely nothing to do with the files that receive these errors. In other words, it doesn't add or delete any of these files locally (what I presume local add/delete means). Besides, if I had deleted the file locally, why would that be in conflict with a deletion in the repo (incoming) anyway?
How I got here: I merged trunk into my branch and am trying to commit to my branch.
P.S. I've (tried to) read Managing trunk and feature branches: local delete, incoming delete upon merge, but there's too much terminology. Other questions/answers I've read here on SO don't seem to apply or else are hard to understand.
-36522860 0 Android studio - unwanted tab draggingI have an EXTREMELY annoying problem with Android Studio. Scenario:
1) Switch tabs by clicking on a tab;
2) First action in the new tab is to highlight some code via the mouse.
In some cases dragging the mouse after the left click drags the tab as if I'd clicked on the tab and wanted to reposition it.
I have not been able to discern any pattern to the phenomenon; for example, the time between switching tabs and the left click, the position of the left click.
Any suggestions as to how to stop this?
-13304185 0 Where to submit new feature request for BigQuery?This is not a technical question. But I do want to know where I can submit feature request for
google-bigquery?
I came across a few issues when importing json data using command-line tool bq load, but the error message did not provide valuable info for me to locate the error at all.
e.g.,
Too many errors encountered. Limit is: 0. Failure details: - Expected '"' found '4' - Expected '"' found '3' - Expected '"' found '4' - Expected '"' found '3' It will be very helpful if the error message contains the line number.
-4562298 0 How to edit a file in Vim with all lines ending in ^M except the last line ending in ^M^JI have a bunch of files that I need to look at. All lines in these files end in ^M (\x0D) except the very last line that ends in ^M^J (\x0D\x0A).
Obviously, Vim determines the filetype to be DOS with the effect that the file's entire content is displayed on one single line like so:
some text foo^Mmore text and^Ma few control-m^Ms and more and more Since I don't want to change the files' content: is there a setting in Vim that allows to look at these files with the new lines as I'd expect them to be?
-7569781 0 Currency formatting language?I am using a GridView and I need to show the currency in Arabic culture so I used this code which is working very well,
DataFormatString="{0:c}"
The results will be like this : د.ك. 55.000 Now what I want is to change it like this : 55.000 K.D ???
-27654349 0 How to avoid my android application to be shown in the "recent apps" list?I developed an android application and I want to avoid it to be shown in the "recent apps" list.
Is it posssible to do that in my code?If yes, How to do that?

Yes, but what is the point?
Response.Cookies.Add(new HttpCookie("UserID", "JLovus") {Expires = DateTime.Now.AddMinutes(30)});
-22503443 0 How Can I Do Real Time Video Transmission With NDK on Android First of all, we don't know why we are using NDK but java hasn't got a library that helping to do media stuff. We are confused about using socket on java side or c/c++ side. We are planning to use socket on java and do media stuff on c/c++ but we don't know it's possible or not.
We are waiting your suggestions. Thanks in advance.
-33062662 0You can set background on animation complete callback something like this:
$('#SwWcSbDoTh').on('click',function(){ $('#B').animate({opacity: 1,complete:function(){ $("body").css("opacity","0.25");}},1000); });
-26709268 0 Anyways, I get the answer. All we have to make a call to.
getCompleteInfo() Rest is on manipulation of the output.
-752490 0 Security risks of an un-encrypted connection across an international WAN?The organisation for which I work has an international WAN that connects several of its regional LANs. One of my team members is working on a service that receives un-encrypted messages directly from a FIX gateway in Tokyo to an app server in London, via our WAN. The London end always initiates the authenticated connection, and at no point do these messages leave our WAN.
But our local security guru suggests that we should be encrypting these messages as a WAN apparently has significantly more security risk than a LAN. How much easier is it really to break into a WAN than a LAN? And what other security risks does a WAN pose in this context?
UPDATE: Many thanks for your answers. I've decided to encrypt the connection, mainly because it's clear that the WAN does introduce extra security vulnerabilities due to the hardware being outside of our physical control.
-27269665 0There is a command to show all the commit logs history since the beginning in a branch
git log after execting this command, you will find that each commit or log has commit id and Author with its date, copy the commit ID and right this command:
git show COMMIT_ID The command above will show the commit details by the author assigned to this commit id
Another solution it to write something like this:
git whatchanged --since '04/14/2013' --until '05/22/2014' The code above it like git log however with filters (range)
-12156209 0 How recive data from SQL Server to Android Application, in autonomous manner?I have created a web service which, querying a SQL Server, retrives several tables. I'm consuming this web service using KSoap2 package in Android application, and I want maintain alligned the tables on SQL Server and tables on Android Application. Many of the tables in SQL Server remain the same over time, but some others change frequently. I need an automatic mechanism for update the tables on Android Application, on the initiative of Server. I think I need a socket on Android application, for listening a signal transmitted from SQL Server, the meaning of which is "the data in some tables are changed". So, then, I can use the web service call for retrieves new data. Is this possible? anyone has suggestions?
-27962283 0You can try this http://jsfiddle.net/buhr164g/4/
$(function(){ var p ='http://localhost.com/sampleimage'; for(var i=0;i<10;i++) { $("body").append('<img class="profile-pic" src="'+p+'_'+i+'.jpg"/>'); } $(".profile-pic").error(function(){ /* Do error processing */ }).attr('src',"http://journal.appconnect.in/wp-content/uploads/2013/08/runner_small.gif"); });
-14542067 0 Sounds like you should be using radio buttons instead. To do that with check boxes you'll need to manually uncheck the boxes on the .checked event.
-22098359 0 How to trigger UpdateProgress on initial pageload in asp.netQuestion: Why does my UpdateProgress not show during the initial page load but does for subsequent postbacks via button click?
The only way I have managed to get this working is with a timer, which I'm not keen on. Is there another way?
Can someone explain why doSearch() causes the updateprogress to work from a button click but not on pageload via docoment ready?
Code:
Js handler:
<script> $(document).ready(doSearch); function doSearch() { $('#<%= UpdatePanel1Trigger.ClientID %>').click(); return false; } </script> aspx:
//if i click this button the updateprogress works //and the panel loads <asp:Button ID="btnSearch" runat="server" Text="Search" CssClass="form-control" OnClientClick="return doSearch();" /> <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" OnLoad="UpdatePanel1_Load" ChildrenAsTriggers="true"> <ContentTemplate> <asp:Button ID="UpdatePanel1Trigger" runat="server" style="display:none" OnClick="UpdatePanel1Trigger_Click" /> <%--gridview that takes a while to load--%> </ContentTemplate> </asp:UpdatePanel> <asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1" DisplayAfter="1"> <ProgressTemplate> <asp:Image ID="imgUpdateProgress1" runat="server" ImageUrl="~/Images/spinner.gif" AlternateText="Loading ..." ToolTip="Loading ..."/> </ProgressTemplate> </asp:UpdateProgress> Codebehind:
protected void UpdatePanel1Trigger_Click(object sender, EventArgs e) { if (!String.IsNullOrEmpty(m_search)) { performSearch(); //loads data for gridview in updatepanel } }
-17093710 0 The // seems to be working correctly,
See this tutorial on operators.
// = Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed. 9//2 is equal to 4 and 9.0//2.0 is equal to 4.0
for 4/2 to equal 2.0 you need to specify a float. For example : 4/float(2) evaluates to 2.0. The ints 4 and 2 are not already defined as floats when you divide.
Hope it helps!
-32245312 0NUnit version 3 will support running tests in parallel, this works good with a Selenium Grid:
Adding the attribute to a class: [Parallelizable(ParallelScope.Self)] will run your tests in parallel with other test classes.
• ParallelScope.None indicates that the test may not be run in parallel with other tests.
• ParallelScope.Self indicates that the test itself may be run in parallel with other tests.
• ParallelScope.Children indicates that the descendants of the test may be run in parallel with respect to one another.
• ParallelScope.Fixtures indicates that fixtures may be run in parallel with one another.
NUnit Framework-Parallel-Test-Execution
-37024635 0 How to cd to a directory on remote machine and run the script present in that directoryWhen I do this
ssh host@someip "cd /target && ls" the files on remote machine are displayed.
Now, I am trying to run a file on the remote machine.
ssh host@someip "cd /target && ./file.sh" When i do this it reaches the folder named target on the remote machine but the file is executed on local machine. How to make file.sh also run on remote machine ?
-564591 0My simple answer combined with those answer is:
Therefore it usually fall into this habit/practice easily but it needs some time to get used to:
program your logic (not the UI) in functional programming language such as F# or even using Scheme or Haskell. Also functional programming promotes thread safety practice while it also warns us to always code towards purity in functional programming. If you use F#, there's also clear distinction about using mutable or immutable objects such as variables.
Since method (or simply functions) is a first class citizen in F# and Haskell, then the code you write will also have more disciplined toward less mutable state.
Also using the lazy evaluation style that usually can be found in these functional languages, you can be sure that your program is safe fromside effects, and you'll also realize that if your code needs effects, you have to clearly define it. IF side effects are taken into considerations, then your code will be ready to take advantage of composability within components in your codes and the multicore programming.
-39232832 0 How to stop tab change from running fragment onCreateView in AndriodI have three tabs using the implementation below and they perform very well. When tab is changed the proper fragment is load and so on. The problem is that, when i get to the last tab and comeback to the first fragment, its like its oncreateview method is always triggered again running the other codes it in causing duplicates. Any help will be greatly appreciated.
//Activity on the tab is based
public class Dashboard extends AppCompatActivity { private TabLayout tabLayout; private ViewPager viewPager; private MyViewPagerAdapter myViewPagerAdapter; private int[] tabIcon = {R.drawable.ic_home, R.drawable.ic_message, R.drawable.ic_person}; android.support.v7.widget.Toolbar toolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dashboard); //Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); //ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager); setupViewPager(viewPager); //Tablayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); tabLayout.getTabAt(0).setIcon(tabIcon[0]); tabLayout.getTabAt(1).setIcon(tabIcon[1]); tabLayout.getTabAt(2).setIcon(tabIcon[2]); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { switch(tab.getPosition()) { case 0: viewPager.setCurrentItem(0); toolbar.setTitle("Home"); break; case 1: viewPager.setCurrentItem(1); toolbar.setTitle("Messages"); break; case 2: viewPager.setCurrentItem(2); toolbar.setTitle("Profile"); break; } } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); } private void setupViewPager(ViewPager viewPager){ myViewPagerAdapter = new MyViewPagerAdapter(getSupportFragmentManager()); myViewPagerAdapter.addFragments(new CategoryFragment(), "Categories"); myViewPagerAdapter.addFragments(new MessagesFragment(), "Messages"); myViewPagerAdapter.addFragments(new ProfileFragment(), "Profile"); viewPager.setAdapter(myViewPagerAdapter); } //View Pager Adapter public class MyViewPagerAdapter extends FragmentPagerAdapter { ArrayList<Fragment> fragments = new ArrayList<>(); ArrayList<String> tabTitles = new ArrayList<>(); public void addFragments(Fragment fragments, String titles){ this.fragments.add(fragments); this.tabTitles.add(titles); } public MyViewPagerAdapter(FragmentManager fm) { super(fm); } @Override public int getCount() { return fragments.size(); } @Override public Fragment getItem(int position) { return fragments.get(position); } @Override public CharSequence getPageTitle(int position) { //return tabTitles.get(position); return null; } } @Override public void onBackPressed() { super.onBackPressed(); } }
//Main first fragment code public class CategoryFragment extends Fragment {
private DBHandler dbHandler; private ListView listView; private ListAdapter adapter; ArrayList<Categories> categoriesList = new ArrayList<Categories>(); public CategoryFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_home, container, false); //Setting up the basic categories dbHandler = new DBHandler(view.getContext()); //Get Categories from database final Cursor cursor = dbHandler.getCategories(0); if (cursor != null) { if(cursor.moveToFirst()){ do{ Categories categories = new Categories(); categories.set_id(cursor.getInt(0)); categories.set_categoryname(cursor.getString(2)); categories.set_categoriescaption(cursor.getString(3)); categoriesList.add(categories); }while (cursor.moveToNext()); } cursor.close(); } listView = (ListView) view.findViewById(R.id.categories); adapter = new CategoryAdapter(view.getContext(), R.layout.cursor_row, categoriesList); listView.setAdapter(adapter); listView.setOnItemClickListener( new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Integer cid = (int) (long) adapter.getItemId(position); TextView categoryname = (TextView) view.findViewById(R.id.cursor); String cname = categoryname.getText().toString(); Intent i = new Intent(view.getContext(), CategoryList.class); i.putExtra("categoryname", cname); i.putExtra("categoryid", cid); startActivity(i); } } ); return view; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } }
So when i swipe back here from the last tab. OncreateView runs again. How can i handle that and prevent duplicates. Thank you
-16627980 0<?php $fruits = array( array('name'=>'banana', 'color'=>'yellow' , 'shape'=>'cylinder'), array('name'=>'apple', 'color'=>'red' , 'shape'=>'sphere'), array('name'=>'orange', 'color'=>'orange' , 'shape'=>'sphere') ); $result = false; foreach($fruits as $subarray) { if( in_array('apple', $subarray) ) { $result = true; break; } } echo "result is ", ($result ? "TRUE" : "FALSE"); ?>
-10781084 0 If my app deletes a post it made to a user's wall, will all likes and shares made by other people also be deleted? Lets say I have a FB app I've created, and for whatever reason the server code for the app is responsible for posting stories to the app user's wall (using a token).
Now let's say we want to take down that post at a later date - easy, right? Because the app created the post, it owns it, and using the ID it received originally it can take that post down. (I presume the ID I get back is actually an "object id" referring to my content, rather than specifically to the post on the user's wall - correct?)
Here's the thing though. What if one or more friends of the user shared that story to their own wall - what if this happened a number of times, spreading through the friend relationship tree further and further. Does my app still have the power to remove all of these posts, because it created the original post?
Additionally, what if the original user deleted the post themselves from their wall, but not until it had been shared by his/her friends? Would this have the same effect (delete everywhere), or would it only be that one specific post being removed? Would my app get an error when it tried to delete the post itself if the post had already been deleted by the user?
The reason I ask is because, if my app deleted the original post that it made to the user's wall, I would want all of the shared posts or likes to also be deleted, no matter where they were down the friend chain. I don't want to delete my original post and assume all is well, only to discover that because it was shared several times down the chain that it is still visible somewhere.
In case it's relevant, the "post" my app will make would require a custom image and a specific return URL - I tried the /user_id/links graph API and it didnt work (there's a bug with it). So I'd be most likely using /user_id/feed to make the post.
The title might seems weird, but I don't really know how to describe this situation as I'm a beginner in JavaScript.
Here's the code :
a={}; var b=a; b['a']='x'; console.log(a); the result will be:
Object { a="x"} shouldn't it be a blank object because I set 'x' to variable b only ?
-35007108 0You can coerce a CF type to an NS type by first re-binding the CFMakeCollectable function so that it takes 'void *' and returns 'id', and then using that function to perform the coercion:
ObjC.bindFunction('CFMakeCollectable', [ 'id', [ 'void *' ] ]); var cfString = $.CFStringCreateWithCString(0, "foo", 0); // => [object Ref] var nsString = $.CFMakeCollectable(cfString); // => $("foo") To make this easier to use in your code, you might define a .toNS() function on the Ref prototype:
Ref.prototype.toNS = function () { return $.CFMakeCollectable(this); } Here is how you would use this new function with a CFString constant:
ObjC.import('CoreServices') $.kUTTypeHTML.toNS() // => $("public.html")
-35367787 0 Org.json.JSONException: Unterminated string at character I am getting the error when creating a JSONObject by passing a string.
Org.json.JSONException: Unterminated string at character My JSON string is:
{"Count":741,"Data":[{rec1....},{rec2...}, etc]} This seems to only happen on Linux as I developed in Windows and it worked fine. Also, the issue seems to stem from the string being too long. I cut the array by more than half and the issue went away.
What can I do to fix this issue or if there is a workaround?
-9824257 0
Please go through this link: Nine Options for Managing Persistent User State in Your ASP.NET Application
-38366218 0A MiddleWare helped me.
Route::group(array('middleware' => 'resolve_domain'), function () { Route::get('/', 'WhitePapersController@getHomepage'); }); And in MiddleWare -
public function handle($request, Closure $next) { $params = explode('.', $request->getHost()); $sub_domains = config('admin_configs.editions'); // Predefined sub-domain $edition = false; if(!empty($params[0]) && in_array($params[0], $sub_domains, true)) { $edition = $params[0]; } define('DOMAIN_EDITION', $edition); // Set constant to be used. return $next($request); }
-9144194 0 It's a python code.
>>> import re >>> s = '<span class="address">413 W. Street</span><br><span class="phone">218-999-1020</span>, <span class="region">WA</span> <span class="postal-code">87112</span><br>' >>> re.findall(r'address">(.*?)<.*phone">(.*?)<.*region">(.*?)<.*postal-code">(.*?)<', s) [('413 W. Street', '218-999-1020', 'WA', '87112')] >>> Is Task a specific case where we rely on the native javascript implementation of Task?
Exactly. You'll notice that Task the type but not Task the tag (thing on the right) are exported from the module, so you can't actually access the latter. It's a placeholder to make the type system happy.
Instead, the Native JavaScript implementation knows what tasks really are, which is a JS object. Any native module dealing with Tasks (either the Task module or any third-party library like elm-http) is in on the secret. However, the Task module exports a good number of helper functions that you can have a lot of control over tasks using only the already published libraries.
Clarification Edit: Yes, you need to use a third-party library to get a task that actually does some effect in the outside world. To actually run that task, you need to send it out a port; until you do that a Task is just a description of the work to do.
-31927562 0see following functions in help for potential insight to your issue
if you are having trouble with a valid, but mismatched buffer, then take a look at what the following function can do for you behaviorally on the system
lrs_set_send_buffer() If, on the other hand, you are looking for generic timeout functions, take a look at the following. These are also available in the product documentation/function reference under Winsock/Timeout functions
lrs_set_accept_timeout() lrs_set_connect_timeout() lrs_set_recv_timeout() lrs_set_recv_timeout2() lrs_set_send_timeout()
-36485869 0 Your conversion atof in this code
for(k = 0; k < 361; k++) { val = atof(result[k]); cal[k] = val; } is going out of bounds of the array 'result'
You only allocate memory to elements in the result array when you have data to put in it
result[i] = malloc(strlen(value) + 1);
If less than 361 records were created you are reading from unallocated memory - hence the error.
You need to keep a record of how many results you have read in and then use that value to ensure that you remain in range as you process the result array.
There is no difference between files based on the file extension.
-36187713 0Postman 4.0.5 has a feature named Manage Cookies located below the Send button which manages the cookies separately from Chrome it seems.
-1110589 0You could use the static ForEach method:
Array.ForEach(x => fis.Add(new FileInfo(x))); However, you can easily replace the entire function with this one line:
IList<FileInfo> fis = Directory.GetFiles(path). Select(f => new FileInfo(f)).ToList();
-32729559 0 How do I write regex to validate EIN numbers? I want to validate that a string follows this format (using regex):
valid: 123456789 //9 digits valid: 12-1234567 // 2 digits + dash + 7 digits Here's an example, how I would use it:
var r = new Regex("^[1-9]\d?-\d{7}$"); Console.WriteLine(r.IsMatch("1-2-3")); I have the regex for the format with dash, but can't figure how to include the non-dash format???
-40281397 0 "The remote name could not be resolved" error when calling API from serverOn my website I have some calls to an API.
In client side, with AJAX, it works perfectly but from server side (MVC and C#) I'm getting the following error:
The remote name could not be resolved 'api.website.com'
This is the code that calls the API:
JsonSerializerSettings settings = new JsonSerializerSettings(); settings.ContractResolver = new CamelCasePropertyNamesContractResolver(); var data = JsonConvert.SerializeObject(email); WebClient client = new WebClient(); client.Headers.Add(HttpRequestHeader.ContentType, "application/json"); var resp = client.UploadString(@"http://api.website.com/functions/email", data); Any help would be very much appreciated.
-28241767 0 CSS content of input value before the input in a td elementI have to print a pretty hefty page / form / table combination and when I print I have multiple text input elements that I can't seem to reduce the width to use only the width needed to display the text without excess width. That excess width effects the ten required columns I have to print.
So I've attempted to use CSS Content to move the text from the text input elements in to the parent table data elements. Here is example HTML and CSS:
<td><input type="text" value="Deadly Ninja Robots" /></td> The CSS I have tried:
form fieldset input[type='text'] {display: none;} form fieldset input[type='text']:before {content: form fieldset input[type='text'](value) ": ";} How do I take the value of text input elements and display them inside the table data element that is the direct parent of the text input element itself?
-4058739 0The error lies on the client side, so you want to use a 4xx status code. I'd go with 400 - Bad Request:
-104844 0 Default Printer in Unmanaged C++The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
I'm looking for a way to find the name of the Windows default printer using unmanaged C++ (found plenty of .NET examples, but no success unmanaged). Thanks.
-29174740 0If everything in one employee table with field "manager" pointing to employee id, then what kind of relationship is that? Recursive? Many to one?
-33755356 0Put an @ before the jar file path as below:
curl --data-binary @/opt/hadoop/spark-jobserver/job-server-api/target/scala-2.10/job-server-api_2.10-0.6.1-SNAPSHOT.jar localhost:8090/jars/test
-25576808 0 I found a working solution which was rather simple, all I did was use the std::wifstream as the first parameter of the boost::property_tree::read_xml method.
Basically three lines of code:
boost::property_tree::wptree pt; std::wifstream f(L"C:/äöå/file.xml"); boost::property_tree::read_xml(f, pt);
-21414697 0 Try this:
gci *.txt |% {write-host "`r$($_.name)" -NoNewline; Start-Sleep -Seconds 1}
-28714815 0 Calculating CRC initial value instead of appending the CRC to payload Most of the CRCs I've implemented were appending the calculated CRC value to the message (payload) and checking for a zero result at the receiver after all bytes incl. CRC value were fed through the CRC register. Obviously this is a quite standard approach.
Now I would like to use a different approach:
What is the best approach to do this? Does one have a good idea or some pointers where to dig deeper?
ps: Why I want to do this? In some applications (ROM) I cannot append data as the data is stored at the end of address space of a ROM. So I'd like to either preload the CRC register or prepend the value to the message.
-35943513 0You need to make a concatenation in php
in your example use "." instead of "+"
$string = $userNode->getFirstName() . $userNode->getLastName();
-12420251 0The expression [[]] actually consists of two concatenated subexpressions: [[] and ].
[[] is character class that matches only [ characters. Having [ is only possible at the very beginning of a character class.] is just a normal character if outside of a character class.Both are concatenated thus your expression matches any character of [ followed by ], which results in matching [].
I think you are probably looking for datetime2(6) in SQL Server 2008.
-40313233 0Defines a date that is combined with a time of day that is based on 24-hour clock. datetime2 can be considered as an extension of the existing datetime type that has a larger date range, a larger default fractional precision, and optional user-specified precision.
the <div class="container"> sets the width of the content inside to a fixed width that depends on the viewport width (see http://getbootstrap.com/css/#overview-container) . To let the content stretch to the full available width, change it into <div class="container-fluid">
Try just:
bash <(curl -s http://mywebsite.com/myscript.txt)
-14342691 0 System commands dont work when running over passenger I have a sinatra app with a page that shows some information about the application. Some of which is generated by running commands on page load. Everything works fine on my MacBook when running in unicorn and everything works fine on the production server when running in unicorn but swap to Apache/Passenger and suddenly the commands start returning nil.
For example to get a list of committers I use:
comitters = `cd /path/to/app && git shortlog -s -n` This works perfectly until run in the apache/passenger setup.
Is there some option within passenger that disables system commands?
-19227018 0Your regular expression is self-contradictory.
You are bounding your pattern on word boundaries, and then including a non-word character in the string you're looking for. Since the '.' character isn't a word character, there will never be any strings that are delimited by word boundaries that include the '.'.
Put another way, since the '.' is itself a word boundary, you are looking for [word-boundary][word-boundary][word], which cannot occur.
Just take out the word boundaries in your REGEXP:
WHERE INET_NTOA(ip) REGEXP '\.111'
-11696380 0 Here's a reasonably straightforward working example that produces the output you want:
import play.api.libs.json._ val json = Json.parse(""" {"1342558874663000":{"TEMPERATURE_C":"253","TEMPERATURE_F":"775"}, "1342558854606000" :{"TEMPERATURE_C":"254","TEMPERATURE_F":"776"}} """).as[JsObject] Json.toJson(json.fields.flatMap { case (epoch, obj) => obj.as[JsObject].fields.map(epoch -> _) }.groupBy(_._2._1).mapValues( _.map { case (epoch, (_, v)) => Seq(epoch, v.as[String]) } )) The trick here is to flatten the list and then rebuild the structure you need.
-18501096 0This is the concept of Reflection. You should be able to do something like the following (untested) code snippet:
/** * @return {@code true} if all of the values of the fields in {@code obj} are * contained in the set of {@code values}; {@code false} otherwise. */ public boolean containsAllValues(HashSet<Object> values, MyClass obj) { Field[] fields = MyClass.class.getFields(); for (Field field : fields) { Object fieldValue = field.get(obj); if (values.contains(fieldValue)) { return false; } } return true; }
-30964205 0 Setting GlassFish-Mysql Connection Pool on Openshift I just created a new application with the DIY cartridge and add a MySQL cartridge to it as well. I also was able to deploy the application online. I cannot use the GlassFish administration console with OpenShift but I need to set up JDBC resources, connection pools. I'm trying to edit the domains.xml of my remote glassfish server using that of my local glassfish server. I'm still unable to connect to the database. This is what I've done so far:
<jdbc-connection-pool is-isolation-level-guaranteed="false" datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" name="SamplePool" res-type="javax.sql.DataSource"> <property name="User" value="adminvcsHiYw"></property> <property name="DatabaseName" value="timetable"></property> <property name="serverName" value="127.8.28.2"></property> <property name="PortNumber" value="3306"></property> <property name="URL" value="jdbc:mysql://127.8.28.2:3306/timetable"></property> <property name="Password" value="_R-LrpYIcdUf"></property> </jdbc-connection-pool> This is the output of rhc tail -a appname
==> app-root/logs/mysql.log <== 150621 7:55:43 InnoDB: highest supported file format is Barracuda. 150621 7:55:43 InnoDB: Waiting for the background threads to start 150621 7:55:44 InnoDB: 5.5.41 started; log sequence number 1686690 150621 7:55:44 [Note] Server hostname (bind-address): '127.8.28.2'; port: 3306 150621 7:55:44 [Note] - '127.8.28.2' resolves to '127.8.28.2'; 150621 7:55:44 [Note] Server socket created on IP: '127.8.28.2'. 150621 7:55:44 [Warning] 'proxies_priv' entry '@ root@ex-std-node534.prod.rhcloud.com' ignored in --skip-name-resolve mode. 150621 7:55:44 [Note] Event Scheduler: Loaded 0 events 150621 7:55:44 [Note] /opt/rh/mysql55/root/usr/libexec/mysqld: ready for connections. Version: '5.5.41' socket: '/var/lib/openshift/5585ff875004465b5500013a/mysql//socket/mysql.sock' port: 3306 MySQL Community Server (GPL) ` What am I doing wrong? Can anyone help?
-5037323 0 Writing "Code::Blocks" Without the ColonsThis is a bit of a silly question, but please bear with me. ;)
I just got the Code::Blocks IDE and I'm enjoying it thoroughly. However, since the : character isn't allowed in Windows folder names, I'm unsure of what to call the folder I keep all my projects in. (I name each folder after its IDE.)
Should it be written as "Code Blocks," "CodeBlocks," or something else...?
-24171668 0You can launch your softwares from the terminal binaries themselves to get a new terminal for each. It would depend on the terminal you use. With konsole you can have
konsole -e command [args] ... With gnome-terminal you do:
gnome-terminal -e command [args] & With xterm:
xterm -e command [args] & Probably refer as well to a similar thread: Run multiple .sh scripts from one .sh script? CentOS
-20045738 0 DLL deployment increases startup time of Sitecore siteWe have a Sitecore 6.6 instance which is used to host multiple sites. It is hosted in IIS 7.5. We developed custom Sitecore sublayouts and pipelines which are used across websites.
When any dll is deployed in bin folder, the Sitecore site takes long time to startup (8-10 mins). But when IIS is reset, startup time is less (30-40 seconds).
What could be the reason for application startup time to be more for DLL deployment than IIS Reset ? Any suggestions to improve the application startup time for DLL deployment ?
Update 1: The startup time after DLL deployment impacts our build process as it increases the overall build deployment time in all environments (DEV,STG,LIVE).
Profiling snapshot of w3wp process revealed two major hotspots:
Update 2: After following the deployment suggested by Vicent, profiling snapshot of w3wp process revealed major hotspot at
Sitecore.Web.UI.WebControls.Sublayout.GetUserControl(Page)
Further analysis of memory dump showed that thread was waiting for JIT compilation of newly deployed DLL.
-25282476 0Most simple, without caring about delegates
if(textBox1.InvokeRequired == true) textBox1.Invoke((MethodInvoker)delegate { textBox1.Text = "Invoke was needed";}); else textBox1.Text = "Invoke was NOT needed";
-15547702 0 It would help if you could point to the page where the problem is reproducible, even if that means that you create a page yourself, put it in dropbox and make it public.
Did you even try to replicate the problem with the html and ruby code that you have posted? I am asking because the problem is not reproducible with the provided code. Take a look yourself:
> browser.ul( :class =>'a').li( :class =>'b').link(:class =>'c').span(:class =>'d') => #<Watir::Span:0x..fa66c75ff618434cc located=false selector={:class=>"d", :tag_name=>"span"}> > browser.ul( :class =>'a').li( :class =>'b').link(:class =>'c').span(:class =>'d').text => "text" As far as I understood, you are surprised that when you provide some code, Watir returns an element, but when you want to execute a method on the element, it complains that it can not find the element.
Take a closer look at the ruby object that represents element on a page:
#<Watir::Span:0x..fa66c75ff618434cc located=false selector={:class=>"d", :tag_name=>"span"}> Please notice located=false. As far as I know, that means that watir creates a ruby object before trying to access it, so the first line of your code does not raise any exceptions. But then when you try to use the element, watir can not find it on the page and complains.
A few recommendations I would like to make (based on the app we've built which also uses Table Storage exclusively).
Account or Subscription. You can use a GUID to uniquely identify an account.Individual User Login Scenario
So an individual user logs in using their username/password. You retrieve the information about the user and there you find out that the user is an individual user based on the account type.
Team Owner Login Scenario So when a team owner logs in, based on the login you will find out that the user is a team owner. If the team owner needs to find the list of all the users in the team, you do another query (it will be the PartitionKey query only) which will give you information about all the users in the team.
Team User Login Scenario
So when a team user logs in, based on the login you will find out that the user is a team user. Since the user is a team user, he/she need not query the table to find out about other users in the team. Even if they do, you will do another query (same as team owner query) to get the list of users in a team.
-254416 0An EXISTS operator might be faster than the subquery:
SELECT t1.Index, MIN(t1.[Date]), MAX(t1.[Date]) FROM myTable t1 WHERE EXISTS (SELECT * FROM myTable t2 WHERE t2.Index = t1.Index AND t2.[Date] >= '1/1/2000' AND t2.[Date] < '1/1/2001') GROUP BY t1.Index It would depend on table size and indexing I suppose. I like G Mastros HAVING clause solution too.
Another important note... if your date is actually a DATETIME and there is a time component in any of your dates (either now or in the future) you could potentially miss some results if an index had a date of 12/31/2000 with any sort of time besides midnight. Just something to keep in mind. You could alternatively use YEAR([Date]) = 2000 (assuming MS SQL Server here). I don't know if the DB would be smart enough to use an index on the date column if you did that though.
EDIT: Added GROUP BY and changed date logic thanks to the comment
-9848319 0 Is there a more succinct Linq expression for inserting a constant between every item in a list?Here's what I have at the moment:
public List<double> GetStrokeDashArray(List<double> dashLengths, double gap) { return dashLengths .SelectMany(dl => new[] { dl, gap }) .Take(dashLengths.Count * 2 - 1) .ToList(); } Results for GetStrokeDashArray(new List<double> { 2, 4, 7, 11, 16 }, 2);
2, 2, 4, 2, 7, 2, 11, 2, 16
-26757900 0 This is because you are fixing the content that pushes "tasks-column" to the right. The simple way to do what you want is just to move "info" inside col-md-4, like this:
<div class="row"> <div class="col-md-4"> <div class="info"> <!--some fixed Markup --> </div> </div> <div class="col-md-8 tasks-column"> <!--some Markup --> </div> </div> Hope this helps!
-13323367 0You can also use WriteConsoleOutput() but you'll need to manage positioning of these characters explicitly as it doesn't use the cursor.
-26230390 0I suggest that you still use select but go with Angular-UI's ui-select:
It's a wrapper for and AngularJS native implementation of Select2
-27432943 0Code you use for uploading images won't work in Azure. Just imagine how this should work if you scale up nubmer of instances. You should use Azure blob storage to upload files in Azure. You can google for good tutorial, but to make a long story short you should do the following:
1.) Create Azure Storage Account at manage.windowsazure.com
2.) Setup storage connection string (you can get AccountKey from you storage account)
<configuration> <appSettings> <add key="StorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=storagesample;AccountKey=nYV0gln9fT7bvY+rxu2iWAEyzPNITGkhM88J8HUoyofpK7C8fHcZc2kIZp6cKgYRUM74lHI84L50Iau1+9hPjB==" /> </appSettings> </configuration> In Your code
3.) Add following namespaces
using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Blob; 4.) Initialize Storage Connection
CloudStorageAccount storageAccount = CloudStorageAccount.Parse( ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); 5.) Create container, if it diesn't exist
// Retrieve a reference to a container. CloudBlobContainer container = blobClient.GetContainerReference("mycontainer"); // Create the container if it doesn't already exist. container.CreateIfNotExists(); container.SetPermissions( new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob }); 6.) Specify object name
// Retrieve reference to a blob named "myblob". CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob");
7.) Upload fata
MemoryStream ms = new MemoryStream();
Image img = Image.FromStream(model.ImageUpload.InputStream);
img.Save(ms, ImageFormat.Jpeg);// Create or overwrite the "myblob" blob with contents from file. blockBlob.UploadFromStream(ms.ToArray());
Code you linked to will look like this:
[HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(ImageViewModel model) { var validImageTypes = new string[] { "image/gif", "image/jpeg", "image/pjpeg", "image/png" }
if (model.ImageUpload == null || model.ImageUpload.ContentLength == 0) { ModelState.AddModelError("ImageUpload", "This field is required"); } else if (!imageTypes.Contains(model.ImageUpload.ContentType)) { ModelState.AddModelError("ImageUpload", "Please choose either a GIF, JPG or PNG image. } if (ModelState.IsValid) { var image = new Image { Title = model.Title, AltText = model.AltText, Caption = model.Caption } if (model.ImageUpload != null && model.ImageUpload.ContentLength > 0) {CloudStorageAccount storageAccount = CloudStorageAccount.Parse( ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); // Retrieve a reference to a container. CloudBlobContainer container = blobClient.GetContainerReference("uploads");
// Create the container if it doesn't already exist. container.CreateIfNotExists(); container.SetPermissions( new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob }); -20503552 0blockBlob = container.GetBlockBlobReference(model.ImageUpload.FileName);
var imageUrl = blockBlob.Uri;MemoryStream ms = new MemoryStream();
Image img = Image.FromStream(model.ImageUpload.InputStream);
img.Save(ms, ImageFormat.Jpeg);// Create or overwrite the "myblob" blob with contents from file. blockBlob.UploadFromStream(ms.ToArray()); image.ImageUrl = imageUrl; }
db.Create(image); db.SaveChanges(); return RedirectToAction("Index"); } return View(model); }
If waiting and upgrading the gsa software to v 7.2,.coming mid December is an option you will have wild card search built in.
Otherwise you have to dig deeper. A possible option is a document filter. If you are interested in that option I might be able to help.
I have developed such a document filter.
-24791964 0This code is not very elegant, but it does the job.
clear input obs v2 v3 v4 v5 v6 1 . 3 . . 1 2 2 . . 4 5 3 . 7 . . . 4 1 . 1 . 4 end gen strL nonmiss="" foreach var of varlist v2-v6 { replace nonmiss=nonmiss+" "+"`var'" if !missing(`var') } list nonmiss
-22727318 0 How can I get a CAAnimation to call a block every animation tick? Can I somehow have a block execute on every "tick" of a CAAnimation? It could possibly work like the code below. If there's a way to do this with a selector, that works too.
NSString* keyPath = @"position.x"; CGFloat endValue = 100; [CATransaction setDisableActions:YES]; [self.layer setValue:@(toVal) forKeyPath:keyPath]; CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:keyPath]; animation.duration = 1; animation.delegate = self; __weak SelfClass* wself = self; animation.eachTick = ^{ NSLog(@"Current x value: %f", [wself valueForKeyPath:keypath]); }; [self.layer addAnimation:animation forKey:nil];
-32982553 0 Reading lines from text file and null point exception for(File d : documents) { if(d.isFile()) count++; { BufferedReader inputStream = null; try { inputStream = new BufferedReader(new FileReader(d)); String line; while ((line = inputStream.readLine()) !=null) { //condition to check the hyphen at end of line if(line.charAt(line.length() -1) == 45) { line = line.replace(line.charAt(line.length() -1),' '); String line2 = inputStream.readLine(); line = line.trim()+line2; } System.out.println(line); } finally { try { if(inputStream != null) inputStream.close(); } catch(IOException e) { } } } // System.out.println("\n" + tokens1); //System.out.println("\n" + count); } } catch(Exception e) { System.out.println("Null point exception"); } When I remove the condition to check hyphen, it reads all the lines in the files and displays null pointer exception at the end. When I include this condition, it reads the file but whenever it finds first empty line, it stops and throws a null pointer exception.
-344492 0I install some set of *nix command utilities and process explorer at a bare minimum.
Also, on XP systems I disable any theming and use the windows classic coloration. Vista just doesn't look or work right without the Aero theme so I can't do that on Vista without going almost completely nuts.
Also forgot, I install Chrome. (Used to be Firefox but Chrome is nicer out of the box)
-30042382 0 Linux -> automatic deletion of files older than 2 daysI am trying to write something that runs in the background under linux (ubuntu server). I need a service of some sort that deletes files that are older than 2 days from the files system (own cloud storage folder).
What is the best way to approach this?
-18043512 0It is almost impossible to answer your question in the scope of a SO "answer" - you will need to read up on implementation of parallel processing for the particular architecture of your machine if you want the "real" answer. Short answer is "it depends". But your program could be running on both processors, on any or all of the four cores; they key to understand here is that you can control that to some extent with the structure of your program, but the neat thing about OMP is that usually "you ought not to care". If threads are operating concurrently, they will usually get a core each; but if they need to access the same memory space that may slow you down since "short term data" likes to live in the processor's (core's) cache, and that means there is a lot of shuffling data going on. You get the greatest performance improvements if different threads DON'T have to share memory.
-38514855 0 Toolbar/Nav drawer not working with tabbed viewI'm having an issue getting my toolbar and navigation drawer to show on a new layout file. It's working for the whole app, except the new tabbed layout view.
I try to activate it in the onCreate of the new java class:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.workout_days); mToolBar = activateToolbar(); setUpNavigationDrawer(); I no longer get an error, but the toolbar still doesn't show up. I'm wondering if it's something wrong with my layout file.
baseactivity:
public static final int HOME = 1; public static final int MY_WORKOUT = 2; public static final int MAXES = 3; public static final int PROGRESS = 4; public static final int WORKOUTS = 5; public static final int HELP = 6; private Class mNextActivity; public static String mTitle = AppConstant.SHIEKO_WORKOUT; public static int mType = HOME; protected Toolbar mToolBar; private NavigationDrawerFragment mDrawerFragment; protected Toolbar activateToolbar() { if(mToolBar == null) { mToolBar = (Toolbar) findViewById(R.id.app_bar); setSupportActionBar(mToolBar); switch (mType) { case HOME: getSupportActionBar().setTitle(AppConstant.SHIEKO_WORKOUT); break; case MY_WORKOUT: getSupportActionBar().setTitle(AppConstant.MY_WORKOUT); break; case MAXES: getSupportActionBar().setTitle(AppConstant.SET_MY_MAXES); break; case PROGRESS: getSupportActionBar().setTitle(AppConstant.MY_PROGRESS); break; case WORKOUTS: getSupportActionBar().setTitle(AppConstant.WORKOUTS); break; case HELP: getSupportActionBar().setTitle(AppConstant.FEEDBACK); } } return mToolBar; } Here is my activity: I also have 3 other fragment xml pages that are for the 3 tabs, those do not include the toolbar or nav bar as it's my understanding they are below the tabview.. correct me if I'm wrong please..
<?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.DrawerLayout android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent"> <!--<RelativeLayout--> <!--android:layout_width="match_parent"--> <!--android:layout_height="match_parent">--> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="0dp"> <include android:id="@+id/app_bar" layout="@layout/toolbar" /> <android.support.design.widget.TabLayout android:id="@+id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content"/> </android.support.design.widget.AppBarLayout> <android.support.v4.view.ViewPager android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior"/> <!--</RelativeLayout>--> <fragment android:name="com.bestworkouts.sheikoworkout.NavigationDrawerFragment" android:id="@+id/fragment_navigation_drawer" tools:layout="@layout/fragment_navigation_drawer" android:layout_width="280dp" android:layout_height="match_parent" android:layout_gravity="start" app:layout="@layout/fragment_navigation_drawer" /> </android.support.v4.widget.DrawerLayout> Thanks in advance!
-37505115 0When items are added to a recycler view or a list view you need to notify the adapter that these changes have occurred which you aren't doing.
In onProgressUpdate you'd want to call adapter.notifyItemInserted(position) to tell the RecyclerView to refresh. To do this you'd need a callback or a listener in your AsyncTask because it doesn't have a reference to your adapter, and it shouldn't.
See here for all the notify calls you have the ability to use: https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html
-19323136 0In javascript, make an ajax function,
function myAjax() { $.ajax({ type: "POST", url: 'your_url/ajax.php', data:{action:'call_this'}, success:function(html) { alert(html); } }); } Then call from html,
<a href="" onclick="myAjax()" class="deletebtn">Delete</a> And in your ajax.php,
if($_POST['action'] == 'call_this') { // call removeday() here }
-10138357 0 Option 1:
.widgettitle.sbg_title {font-size:1.6em;}
Option 2:
.sbg_title {font-size:1.6em;}
Option 3:
.widgettitle {font-size:1.6em;}
Your code does essentially the same as:
SqlString dbString = resultReader.GetSqlString(0); string outputString = dbString.ToString(); string itself is a UNICODE string (specifically, UTF-16, which is 'almost' the same as UCS-2, except for codepoints not fitting into the lowest 16 bits). In other words, the conversions you are performing are redundant.
Your web app most likely mangles the encoding somewhere else as well, or sets a wrong encoding for the HTML output. However, that can't be diagnosed from the information you provided so far.
-6786927 0Use Calendar.getActualMaximum()
To get the max date of the month
cal.getActualMaximum(Calendar.DAY_OF_MONTH) and for minimum
cal.getActualMinimum(Calendar.DAY_OF_MONTH) Note : cal is an instance of Calendar
in order to show additional data you can use Grid or StackPanel or whatever suits your needs with visibility collapsed and when the user clicks the item it will be set to show. Here I demonstrated how you can do this with a simple ListView:
This is my MainPage:
<Page x:Class="App1.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="using:App1" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" Name="DummyPage" mc:Ignorable="d"> <Page.Resources> <local:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter" /> </Page.Resources> <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <ListView Name="lvDummyData" HorizontalAlignment="Center" VerticalAlignment="Center" IsItemClickEnabled="True" ItemClick="lvDummyData_ItemClick" SelectionMode="Single"> <ListView.ItemTemplate> <DataTemplate> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <TextBlock Text="{Binding FirstName}" /> <StackPanel Grid.Row="1" Margin="0,20,0,0" Visibility="{Binding ShowDetails, Mode=OneWay, Converter={StaticResource BoolToVisibilityConverter}}"> <TextBlock Text="{Binding LastName}" /> <TextBlock Text="{Binding Adress}" /> </StackPanel> </Grid> </DataTemplate> </ListView.ItemTemplate> </ListView> </Grid> </Page> This is my code behind:
using System.Collections.ObjectModel; using System.ComponentModel; using Windows.UI.Xaml.Controls; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace App1 { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page, INotifyPropertyChanged { public ObservableCollection<DummyData> DummyData { get; set; } private DummyData tempSelectedItem; public MainPage() { DummyData = new ObservableCollection<DummyData>(); DummyData.Add(new DummyData() { Adress = "London", FirstName = "Shella", LastName = "Schranz", ShowDetails = false }); DummyData.Add(new DummyData() { Adress = "New York", FirstName = "Karyl", LastName = "Lotz", ShowDetails = false }); DummyData.Add(new DummyData() { Adress = "Pasadena", FirstName = "Jefferson", LastName = "Kaur", ShowDetails = false }); DummyData.Add(new DummyData() { Adress = "Berlin", FirstName = "Soledad", LastName = "Farina", ShowDetails = false }); DummyData.Add(new DummyData() { Adress = "Brazil", FirstName = "Cortney", LastName = "Mair", ShowDetails = false }); this.InitializeComponent(); lvDummyData.ItemsSource = DummyData; } private void lvDummyData_ItemClick(object sender, ItemClickEventArgs e) { DummyData selectedItem = e.ClickedItem as DummyData; selectedItem.ShowDetails = true; if (tempSelectedItem != null) { tempSelectedItem.ShowDetails = false; selectedItem.ShowDetails = true; } tempSelectedItem = selectedItem; } public event PropertyChangedEventHandler PropertyChanged; public void RaisePropertyChangeEvent(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class DummyData : INotifyPropertyChanged { public string FirstName { get; set; } public string LastName { get; set; } public string Adress { get; set; } private bool showDetails; public bool ShowDetails { get { return showDetails; } set { showDetails = value; RaisePropertyChangeEvent(nameof(ShowDetails)); } } public event PropertyChangedEventHandler PropertyChanged; public void RaisePropertyChangeEvent(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } In my code-behind I have a variable tempSelectedItem which holds the previous clicked item so that you can hide its information.
In order to display and hide the information accordingly we need a simple BoolToVisibilityConverter:
using System; using Windows.UI.Xaml; using Windows.UI.Xaml.Data; namespace App1 { public class BoolToVisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { bool boolValue = (bool)value; return boolValue ? Visibility.Visible : Visibility.Collapsed; } public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotImplementedException(); } } } Hope this helps.
-6743850 0Yes is the answer but it's only the string.
You can use <input name="test[]" />
and you will receive an array of all inputs with name "test[]" in an array with name "test"
You can read for all this in here
-22195255 0That's normal as your object is a reference type. You should make a deep copy in order to reflect the changments in your history list
try something like this
private void Employee_PropertyChanged(object sender, PropertyChangedEventArgs e) { var empCloned = DeepClone(this); History.Add(empCloned); //throw new NotImplementedException(); } Deep Copy
private T DeepClone<T>(T obj) { using (var ms = new MemoryStream()) { var formatter = new BinaryFormatter(); formatter.Serialize(ms, obj); ms.Position = 0; return (T) formatter.Deserialize(ms); } }
-19485803 0 Heroku runs a case-sensitive filesystem, whereas your OS may not be case-sensitive. Try changing that require to this instead:
require 'card' As a general rule of thumb, most files within Ruby are required using lowercase letters with underscores serving as a word separator, like this:
require 'card_shuffler'
-30531045 0 After the upload you can simply call delete_transient( 'wc_attribute_taxonomies' );
That's where the transients are created: http://oik-plugins.eu/woocommerce-a2z/oik_api/wc_get_attribute_taxonomies/
-34449301 0 postgresql function insert multiple rows which values are represented by arrayI have the table:
--------------------------------------- id (integer) | name (character varying) --------------------------------------- I want to insert multiple rows represented by array of character varying. I have the function code:
create or replace function add_task_state( TEXT ) returns void as $$ declare _str_states character varying[]; begin _str_states = string_to_array($1,','); insert into task_states (name) values ???; end; $$ language plpgsql; How I can do this?
-5732159 0You can do exactly the same thing in C++:
std::ifstream reader( xmlInputStream.c_str() ); if ( !reader.is_open() ) { // error handling here... } std::string xml; std::string line; while ( std::getline( reader, line ) ) { xml += line + '\n'; } It's probably not the best solution, but it's already fairly good. I'd probably write something like:
std::string xml( (std::istringstream_iterator<char>( reader )), (std::istringstream_iterator<char>()) ); (Note that at least one set of the extra parentheses are needed, due to an anomaly in the way C++ would parse the statement otherwise.)
Or even:
std::string readCompleteFile( std::istream& source ) { return std::string( std::istringstream_iterator<char>( source ), std::istringstream_iterator<char>() ); } (Look ma, no variables:-)!) Both of these solutions preserve the newlines in the original file, so you don't need to put them back in after reading.
-27083955 0first, you have to give a class or id to your select HTML element.
<select class="chosen" .... //same html/php code Then in your javascript code, you call the jQuery chosen plugin to change this select to a chosen element like this:
$(document).ready(function(){ $('.chosen').chosen(); }) and it should work, you don't have to change anything in you php code, just give a class or id to you your select element so you can get if with jQuery selector. I advice you to read the chosen documentation
-30335945 0Do you need all of this data present on the Windows machine? Or are you going to be accessing it intermittently?
You might try just mounting your S3 bucket.
It will still be remote but will act like a normal mounted drive in Windows. If you need to do some data crunching then copy just the files you need at that moment to the local disk. You can mount S3 with S3browser,Cloudberry, or a hundred other S3 clients.
-7359513 0What appeared to be happening in this case was that when the code was copied to a new part of the page the init() function was called again. Which then meant that two connections where in process.
Therefore the fan box double populated itself.
-12436171 0I may be missing something here, but you can call the render method on the prototype of Super in your Sub.render function :
Super = Backbone.View.extend({ render : function(){ console.log('super render'); return this; } }); Sub = Super.extend({ render : function(){ console.log('sub render'); Super.prototype.render.call(this); return this; } }); var view = new Sub(); view.render(); And a Fiddle http://jsfiddle.net/WATqe/
-5781483 0Is this just an example, or the real application?
In trading room environments, market data applications are extremely sensitive to delays of even a few milliseconds, and a lot of time and money is invested to minimise delays.
This makes the set of technologies you're talking about completely inappropriate; C/C++/Java apps communicating over raw TCP sockets or through a high performance middleware are the only way to get the necessary performance. Internet distribution has unpredictable delays.
Of course, if you're talking about the low-end of the market, where 'realtime' means the user won't get bored waiting for a response, as opposed to liveness of data, then there are many possible technologies. AJAX may be suitable, using either XML or JSON payload.
What type of data source do the quotes come from? Is it's a database, XML/JSON AJAX makes sense; if it's message-orientated middleware, then sockets are much better.
Do you need to have real-time updates, and is it acceptable for individual updates to get aggregated?
-9715113 0To start with, I'd suggest using DateTime.ParseExact or TryParseExact - it's not clear to me whether your sample is meant to be December 2nd or February 12th. Specifying the format may well remove your FormatException.
The next problem is working out which time zone you want to convert it with - are you saying that 11:58 is a local time in some time zone, or it's already a UTC time?
DateTimeStyles.AssumeLocal | DateTimeStyles.AdjustToUniversal to do it as part of parsing.DateTimeStyles.AssumeUniversalTimeZoneInfo to perform the conversion.Also, if it's a local time you'll need to consider two corner cases (assuming you're using a time zone which observes daylight saving time):
You should decide how you want to handle these cases, and make sure they're covered in your unit tests.
Another option is to use my date and time library, Noda Time, which separates the concepts of "local date/time" and "date/time in a particular time zone" (and others) more explicitly.
-38218640 0 Is it possible to write an extension for a specific swift Dictionary ... [String : AnyObject]?I am trying to write an extension for this:
extension [String : AnyObject] { } It throws and error. I was also trying to come up with something similar as this:
extension Dictionary: [String : AnyObject] { } It also fails.
Is there a solution that works similar as this (I can't remember proper syntax)?
extension Dictionary where ?? is [String : AnyObject] { }
-2724522 0 XSL ignores my whitespace even with the I'm making a header in my XSL code that includes multiple fields of information, i.e. "Name: Bob Birthdate: January 1 1900," etc. I enclosed them in tags as such:
<xsl:text> Gender: Male </xsl:text> But on the page, the whitespace around Gender/Male is being ignored. Is there something I'm missing?
Thanks in advance.
-11846110 0Also you may want to select show updates/new packages and show installed packages.
Btw. I think it is called Google Play now instead of Google Market.
-36683661 0Based on 3kings's response as an answer:
I used
compareAnswers(String input) {} in conjunction with
compareAnswers(input); and it worked! Thank you!
-39671829 0found two ways of achieving my problem
1.from @trevjonez(trevor jones)
Where<SomeModel> query = SQLite.select() .from(SomeModel.class) .where(SomeModel_Table.date_field.greaterThan(someValue)); if(someCondition) { query = query.and(SomeModel_Table.other_field.eq(someOtherValue)); } else { query = query.and(SomeModel_Table.another_field.isNotNull()); } Cursor cursor = query.query(); //do stuff with cursor and close it — 2.from @zshock using ConditionalGroup
ConditionGroup conditionGroup = ConditionGroup.clause(); conditionGroup.and(YourTable_Table.id.eq(someId); if (someCondition) { conditionGroup.and(YourTable_Table.name.eq(someName); } return SQLite.select() .from(YourTable.class) .where(conditionGroup) .queryList();
-15484503 0 How to create Quadtree Copy constructor with Recursion I am working on a copy constructor for a Quadtree. Here's what I have so far:
//Copy Constructor Quadtree :: Quadtree(const Quadtree & other) { root = copy(other.root); resolution = other.resolution; } //Copy Constructor helper function Quadtree::QuadtreeNode *Quadtree :: copy (const QuadtreeNode* newRoot) { if (newRoot != NULL) { QuadtreeNode *node = new QuadtreeNode(newRoot->element); node->nwChild = copy(newRoot->nwChild); node->neChild = copy(newRoot->neChild); node->swChild = copy(newRoot->swChild); node->seChild = copy(newRoot->seChild); return node; } else return NULL; } I'm not sure where I am going wrong, but I am receiving memory leaks and Valgrind is pointing out that I have uninitialized values. Help please?
Attached, is my buildTree function - where I actually create the tree. I may be doing something wrong here?
void Quadtree :: buildTree (PNG const & source, int theResolution) { buildTreeHelp (root, 0, 0, theResolution, source); } void Quadtree :: buildTreeHelp (QuadtreeNode * & newRoot, int xCoord, int yCoord, int d, PNG const & image) { if (d == 1) { RGBAPixel pixel = *image(xCoord, yCoord); newRoot = new QuadtreeNode(pixel); return; } newRoot = new QuadtreeNode (); newRoot = NULL; buildTreeHelp(newRoot->nwChild, xCoord, yCoord, d/2, image); buildTreeHelp(newRoot->neChild, xCoord + d/2, yCoord, d/2, image); buildTreeHelp(newRoot->swChild, d/2, yCoord + d/2, d/2, image); buildTreeHelp(newRoot->seChild, d/2 + xCoord, d/2 + yCoord, d/2, image); }
-22372128 0 How is a getting incremented?
a is increased by the a++ in while(a++<=2);.
a++ will return the value of a and add one to it, so when a is 3, a++<=2 will be false, but a still get added by one.
Your label which contains the image is being replaced with label123 in the BorderLayout.CENTER position, which doesnt have any image attached. You could use:
label123.setIcon(ii); If you want the 2 labels to be shown, you could place the text-based label123 in the SOUTH location:
jframe.add(label123, BorderLayout.SOUTH); Note: Use JLabel instead of Label.
Ok, so I am working on a homework assignment, and I am using SWING to make a GUI for a Java project, and I am running into troubles with JList.
I have a customer object that I have made and set attributes to, and I want to add the object into a TreeMap. I want to hook up the Treemap so that any and all objects that are in the map will populate (the name attribute anyway) inside of the JList.
I have done a lot of looking around, and am seeing a lot about coding these things from scratch but little dealing with Swing implementation. I put my customer object into my map and then I would like for my JList to reflect the map's contents, but I don't know how to hook it up.
customers.put(c.getName(), c); this.customerList.(What can I do here? add Customer object?? I can't find what I need); Thanks for your help!!!
-20295442 0I don't know why PhoneCallListener stops execution, however I solved this by putting "phoneListener = new PhoneCallListener();" in the onCreate method.
-1193975 0All of Ryan's suggestions are good. Here are two more (variations on his point # 2).
In the Global.asax, you can use the Application_BeginRequest to do something like this:
if (Request.UserHostAddress != "127.0.0.1" && !Request.UserHostAddress.StartsWith("172.16") && Request.Url.AbsolutePath.Contains("AdminFolderName")) { Response.Redirect("~/somenonproectedpageornoaccessmessagepage.aspx", true); } or use a MasterPage for each aspx page in that folder and put the following in the Page_Load
if (Request.UserHostAddress != "127.0.0.1" && !Request.UserHostAddress.StartsWith("172.16")) { Response.Redirect("http://www.kwiktrip.com", true); }
-29847824 0 This works for me
.directive('updateinfo',['$compile', function($compile) { function link(scope, element, attrs) { function update(){ var str = '<input type="text" ng-model="log1" />'; element.html(str); } update(); element.replaceWith($compile(element.html())(scope)); } return { link: link }; }]);
-1425215 0 I used to be in the same situation, becoming known as the go-to guy. Then one day a PM said something to me that made me realize why I was always becoming that guy.
It's ok to say no sometimes.
Sometimes you need to push back on tasks and say, politely, no you can't do that or you can do that so long as this other task they also need is delayed or even handed off to another.
A task tracking system also helps with this. If you have a publicly available system then when people ask you to do something you can add it to the list, or have them add it. And then they can see what your task list is and where their task falls on it.
Also, only accept requests from your immediate manager. If the CEO comes down and asks you to do something, that's fine, but double check with your manager for confirmation. Often they can handball the task on or get the task pushed back up the chain.
-12522258 0So your nodes have a name: property and a children: array property.
Databases typically store trees in tables as
node-id, parent-id, value1, ..., valueN (you can get certain advantages if you store depth-first visit order and depth-first return order; ask in comments if you need the details).
If you make a single query and get this data into JSON, you will have something like (for your illustration),
[{id: "0", parent: "-1", name: "A2"}, {id: "1", parent: "0", name: "A3"}, {id: "2", parent: "1", name: "A31"}, {id: "3", parent: "2", name: "A311"}, {id: "4", parent: "2", name: "A312"}] You can convert this into {name: children:} format with the following code:
// data is an array in the above format function toTree(data) { var childrenById = {}; // of the form id: [child-ids] var nodes = {}; // of the form id: {name: children: } var i, row; // first pass: build child arrays and initial node array for (i=0; i<data.length; i++) { row = data[i]; nodes[row.id] = {name: row.name, children: []}; if (row.parent == -1) { // assume -1 is used to mark the root's "parent" root = row.id; } else if (childrenById[row.parent] === undefined) { childrenById[row.parent] = [row.id]; } else { childrenById[row.parent].push(row.id); } } // second pass: build tree, using the awesome power of recursion! function expand(id) { if (childrenById[id] !== undefined) { for (var i=0; i < childrenById[id].length; i ++) { var childId = childrenById[id][i]; nodes[id].children.push(expand(childId)); } } return nodes[id]; } return expand(root); } See http://jsfiddle.net/z6GPB/ for a working example.
-36239903 0 What's the difference between Remove and Exclude when refactoring with PyCharm?The official PyCharm docs explain Exclude when it comes to refactoring: One can, say, rename something with refactoring (Shift+F6), causing the Find window to pop up with a Preview. Within, it shows files which will be updated as a result of the refactor. One can right-click on a file or folder in this Preview and choose Remove or Exclude. What's the difference?
The accepted answer ignores a very important aspect: extended precision floating point. The CPU may be doing calculations with a bit-size that exceeds your storage size. This will particularly be true if you use float but can also be true of double and other floating point types.
To show the problem, the following assert may actually fail depending on how the compilation was done and how the chip behaves.
void function( float a ) { float b = a / 0.12345; assert( b == (a/0.12345) ); } Now, in this reduced example it will likely always pass, but there are many cases where it will not. Simply look at GCC Bug 323 and look at how many defects are marked as duplicates. This extended precision causes problems for many people, and it may also cause problems for you.
If you need a guarantee what you'll need to do is make a comparison function that takes two float parameters and guarantee that the function is never inlined (stored floats are not subject to extended precision). That is, you must ensure those floats are actually stored. There is also a GCC option called "store-float" I believe which forces storage, perhaps it can be used here on your individual function.
-40414462 0Here's an alternative using a ChartWrapper instead of a chart.
var opts = { "containerId": "chart_div", "dataTable": datatable, "chartType": "Table", "options": {"title": "Now you see the columns, now you don't!"} } var chartwrapper = new google.visualization.ChartWrapper(opts); // set the columns to show chartwrapper.setView({'columns': [0, 1, 4, 5]}); chartwrapper.draw(); If you use a ChartWrapper, you can easily add a function to change the hidden columns, or show all the columns. To show all the columns, pass null as the value of 'columns'. For instance, using jQuery,
$('button').click(function() { // use your preferred method to get an array of column indexes or null var columns = eval($(this).val()); chartwrapper.setView({'columns': columns}); chartwrapper.draw(); }); In your html,
<button value="[0, 1, 3]" >Hide columns</button> <button value="null">Expand All</button> (Note: eval used for conciseness. Use what suits your code. It's beside the point.)
Suppose I have an undirected weighted connected graph. I want to group vertices that have highest edges' value all together (vertices degree). Using clustering algorithms is one way. What clustering algorithms can I consider for this task? I hope it is clear; any question for clarification, please ask. Thanks.
-41030411 0can you format your data in question. I am not sure whether I get youe point?
CREATE TABLE #tt([name] VARCHAR(10),[date] DATE,skill INT,seconds INT, calls int ) INSERT INTO #tt SELECT 'bob','9/2/2016',706,12771,56 UNION all SELECT 'bob','9/2/2016',707,4061,16 UNION all SELECT 'bob','9/2/2016',708,2577,15 UNION all SELECT 'bob','9/2/2016',709,2156,6 SELECT * FROM ( SELECT t.name,t.date,c.* FROM #tt AS t CROSS APPLY(VALUES(LTRIM(t.skill)+'sec',t.seconds),(LTRIM(t.skill)+'calls',t.seconds)) c(t,v) ) AS A PIVOT(MAX(v) FOR t IN ([706sec],[706calls],[707sec],[707calls],[708sec],[708calls],[709sec],[709calls])) p name date 706sec 706calls 707sec 707calls 708sec 708calls 709sec 709calls ---------- ---------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- bob 2016-09-02 12771 12771 4061 4061 2577 2577 2156 2156
if the count of skill is not fix, you can use dynamic script:
DECLARE @col VARCHAR(max),@sql VARCHAR(max) SELECT @col=ISNULL(@col+',[','[')+LTRIM(skill)+'sec],['+LTRIM(skill)+'calls]' FROM #tt GROUP BY skill SET @sql=' SELECT * FROM ( SELECT t.name,t.date,c.* FROM #tt AS t CROSS APPLY(VALUES(LTRIM(t.skill)+''sec'',t.seconds),(LTRIM(t.skill)+''calls'',t.seconds)) c(t,v) ) AS A PIVOT(MAX(v) FOR t IN ('+@col+')) p' EXEC (@sql)
-41043440 0 Excel MDX linked server fails connection test My first post after 2 years of learning to write SQL and using SQL Server, most of my questions have been answered researching on this website, however I cannot find the answer to my question below:
I am creating a new linked server, grabbing data from Excel using an MDX query in my SQL script. For example:
SELECT * into raw.example FROM openquery( Test1, 'MDX CODE/etc etc' I clicked on my database > Server Objects > Linked Servers > New Linked Server >
Linker Server: TESTEXAMPLE Server Type: other data source Provider: Microsoft OLE DB Provider for Analysis Services 10.0 Product Name: Test1 Data Source: Name of server Provider String: Location: Catalog: OLAP After I click "ok" to create this linked server this message comes up:
The linked server has been created but failed a connection test. Do you want to keep the linked server?
OLE DB provider 'MSOLAP' cannot be used for distributed queries because the provider is configured to run in single-threaded apartment mode. (Microsoft SQL Server, Error: 7308)
I am not sure why it isn't connecting. Is it a server issue where I have to ask for permission to access it? Or do I somehow need to revert away from the provider being configured to run in a single-threaded apartment mode?
I am doing this on my local SQL Server Express Edition machine. Whereas before my script and OPENQUERY/MDX query worked on a remote desktop server etc.
I have looked at other posts but those solutions do not solve my problem.
-35316888 0It depends when you start from (0,0) or at a random location in the matrix.
If it is (0,0) ; use Depth First to go until the end of one branch then the others. Use Breadth First to iterate through all neigbouring nodes at a step. Check only down and right nodes.
If it is at a random location in the matrix, you need to trace all 4 neighbouring nodes.
-11881861 0It's because the file permissions are not the only protection you're encountering.
Those aren't just regular text files on a file system, procfs is a window into process internals and you have to get past both the file permissions plus whatever other protections are in place.
The maps show potentially dangerous information about memory usage and where executable code is located within the process space. If you look into ASLR, you'll see this was a method of preventing potential attackers from knowing where code was loaded and it wouldn't make sense to reveal it in a world-readable entry in procfs.
This protection was added way back in 2007:
This change implements a check using "ptrace_may_attach" before allowing access to read the maps contents. To control this protection, the new knob /proc/sys/kernel/maps_protect has been added, with corresponding updates to the procfs documentation.
Within ptrace_may_attach() (actually within one of the functions it calls) lies the following code:
if (((current->uid != task->euid) || (current->uid != task->suid) || (current->uid != task->uid) || (current->gid != task->egid) || (current->gid != task->sgid) || (current->gid != task->gid)) && !capable(CAP_SYS_PTRACE)) return -EPERM; so that, unless you have the same real user/group ID, saved user/group ID and effective user/group ID (i.e., no sneaky setuid stuff) and they're the same as the user/group ID that owns the process, you're not allowed to see inside that "file" (unless your process has the CAP_SYS_PTRACE capability of course).
I have problems with pattern. I need to process some text for example:
<div>{text1}</div><span>{text2}</span> After the process I need to get in place of {text1} and {text2} some words from dictionary. I'm preparing ui interface for diffrent languages. This is in PHP. For now I have something like this but this doesn't work:
function translate_callback($matches) { global $dict; print_r($matches); return 'replacement'; } function translate($input) { return preg_replace_callback('/(\{.+\})/', 'translate_callback', $input); } echo translate('<div>{bodynum}</div><span>{innernum}</span>'); This is test scenarion but I can't find the way to define pattern because this one in code match
{bodynum}</div><span>{innernum} but I want pattern that will match
{bodynum} and then {innernum} Can somebody help me with this. Thanks.
The Solution:
To match any character between { and }, but don't be greedy - match the shortest string which ends with } (the ? stops + being greedy).
So the pattern now looks like: '/{(.+?)}/' and is exacly what I want.
-4957005 0Looks like you can't just pass touches in and have it respond to them :(
You would have to use the [UIScrollView setContentOffset:animated:] method to move the scrollview yourself.
A better way of intercepting the touches might be to put a view in front of the scrollview - grab any touches you want to listen to and then pass it to the next responder in the chain.
You would make a subclass of UIView that overrode the touch handling methods, something like :
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { if (scrollViewShouldGetThisTouch) [self.nextResponder touchesBegan:touches withEvent:event]; } and just make this view have the same frame as your scrollview but be infront of it in the ui (transparent of course!).
OR
You could subclass UIScrollView - though this might result in odd errors if Apple ever change the implementation of a UIScrollView. I'd choose the other option!
-25674365 0I solved my own problem with the following steps: 1. Deleted MSCOMCTL.OCX from \Windows\Syswow64 2. Opened the Access form that was giving me a problem, and Access reinstalled MSCOMCTL.OCX automatically. 3. Opened a command window with the "Run As Administrator" option 4. Navigated to \Windows\Syswow64 5. Ran "regsvr32 /u MSCOMCTL.OCX" 6. Ran "regsvr32 MSCOMCTL.OCX" 7. Reopened Access and it worked! Note: You will need to do this in System32, NOT Syswow64 for 64-bit office. Dumb naming standard, I know.
@t_m , Thanks for your help!
-12008953 0 mysql - how to get all differences from one table to another (huge amount of rows ~ 500k)In the
`synchro_newitems` table I have all new items (from external source) ~ about 500k rows. It has one column:
`new_ids` In the
`synchro_olditems` table I have all current items (also from external source) ~ about 500k rows. It has one column:
`old_ids` I must get only the new items from synchro_newitems:
(NEW ITEMS) = synchro_newitems (-) synchro_olditems
I tried do that by insert the differences to the 3rd table:
INSERT INTO `synchro_diff` (`id`) SELECT DISTINCT new_ids FROM synchro_newitems LEFT JOIN synchro_olditems ON synchro_newitems.new_ids = synchro_olditems.old_ids WHERE synchro_olditems.old_ids IS NULL (similarly with "NOT IN")
It's works for small amount of rows. But fails when there are 500 000 rows to compare.
I've tried simple:
DELETE FROM synchro_newitems WHERE exists(SELECT * FROM synchro_olditems) But it dosent work.. Do you know some smart method to do that?
-12982138 0You only have to change the client.
Change its Naming.lookup() string, from "localhost" to the server's hostname or IP address. The server's Naming string in the bind() or rebind() call does not change from "localhost", because the server and its Registry are always on the same host.
If you are using Registry instead of Naming, again you only have to change the client's LocateRegistry.getRegistry() call.
-39808850 0Could be your result is already JSON parsed the
function getLocation(){ var name = $("#username").val(); console.log('getLocation()'); if(name != ''){ $.ajax({ type: 'GET', url: '../../' + name, async: true, success:function(data){ var marker = new L.marker(data.location); marker.addTo(map); $("#username").val(''); }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert('Not found'); } }); } } or if you obtain an array
function getLocation(){ var name = $("#username").val(); console.log('getLocation()'); if(name != ''){ $.ajax({ type: 'GET', url: '../../' + name, async: true, success:function(data){ var marker = new L.marker(data[0].location); marker.addTo(map); $("#username").val(''); }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert('Not found'); } }); }
-26701215 0 Download from gitHub How I can download this file from GitHub?
https://github.com/TorgeirH90/Programming/tree/master/C%23/Paratroopers%20Mono/Paratroopers%20Mono
-36629637 0 how to fetch records equal to pageSize while using queryForCursor in SolrTemplateI want to fetch records from solr using cursors as I have large resultset size. I m using SolrTemplate.queryForCursor() method by passing query object to this. But the resultCursor which is of type Cursor has all data in it. I want to stop reading from cursor when my pageSize is hit.
Criteria query = new Criteria("UserName").is ("abc"); query.setRows(10); // As i want to have fetch 10 records at a time Cursor<T> resultCusrsor = solrTemplate.queryForCursor(query,Entity.class); while(resultCursor.hasNext() ){ System.out.println( "Result : " + resultCusrsor.next()); } The while loop here keeps printing all records by fetching 10 at a time. If my pagesize is 100, I want to fetch 10 records 10 times using cursor, but how do I stop at 100th record?
-19026042 0BTW: The function I mention here are the WinApi functions...
-28719610 0I use this:
var nr = 48.00 * 3; alert( nr.toFixed(2) );
-32641886 0 The border is going to push the text to the right as it should. Have you tried making the text shift to the left with a negative margin (margin-left: -2px) when the hover occurs if possible? Or adding a bit of padding (2px) in this case when not on hover and taking it away on hover.
-31429463 0Got help from our friends at TI E2E forums on this topic.
The reason I was unable to see the Configure and Associate menu options was due to the selected perspective. Code Composer 5 uses TI's default CCS Edit perspective which hides the expected menu options. If you change to the default Eclipse C/C++ perspective then the menu option shows up and configuration of the project to use SonarQube can be completed.
-40210616 0Ok how about this. It's a mashup between reshape and base R.
I used your dataset once you posted it. Thanks for providing it.
data <- structure(list(Water.Year = structure(1:6, .Label = c("1953-1954", "1954-1955", "1955-1956", "1956-1957", "1957-1958", "1958-1959", "1959-1960", "1960-1961", "1961-1962", "1962-1963", "1963-1964", "1964-1965", "1965-1966", "1966-1967", "1967-1968", "1968-1969", "1969-1970", "1970-1971", "1971-1972", "1972-1973", "1973-1974", "1974-1975", "1975-1976", "1976-1977", "1977-1978", "1978-1979", "1979-1980", "1980-1981", "1981-1982", "1982-1983", "1983-1984", "1984-1985", "1985-1986", "1986-1987", "1987-1988", "1988-1989", "1989-1990", "1990-1991", "1991-1992", "1992-1993", "1993-1994", "1994-1995", "1995-1996", "1996-1997", "1997-1998", "1998-1999", "1999-2000", "2000-2001"), class = "factor"), May = c(55.55, 23.49, 9.87, 18.03, 17.46, 11.37), Jun = c(43.62, 81.35, 51.59, 28.61, 15.14, 29.48), Jul = c(30.46, 46.71, 55.36, 24.36, 20.09, 19.48), Ago = c(26.17, 29.33, 63.03, 22.01, 16.97, 16.86), Set = c(26.76, 67.83, 154.08, 28.51, 27.24, 21.01), Oct = c(41.74, 133.3, 98.15, 53.72, 35.78, 19.78), Nov = c(19.92, 37.62, 104.06, 115.78, 20.35, 18.69), Dic = c(41.25, 30.16, 32.85, 32.04, 22, 18.86), Ene = c(28.77, 21.07, 22.89, 25.44, 13.27, 14.89), Feb = c(20.96, 19.38, 17.3, 14.53, 10.37, 10.4), Mar = c(12.47, 13.87, 15.68, 10.78, 8.77, 8.79), Abr = c(10.51, 10.63, 10.88, 9.33, 7.69, 8.99)), .Names = c("Water.Year", "May", "Jun", "Jul", "Ago", "Set", "Oct", "Nov", "Dic", "Ene", "Feb", "Mar", "Abr"), row.names = c(NA, 6L), class = "data.frame") I decided to use the year information you had from before and just add in calendar year based on that. Since we know May-Dec is Year 1, and Jan-Apr is Year 2. Maybe a bit convoluted but it gets the job done.
df = separate(data, Water.Year, c("year1","year2")) library(reshape2) fixDF<-melt(df) fixDF$CalendarYear<-rep(NA,nrow(fixDF)) fixDF$CalendarYear[min(which(fixDF$variable=="May")):max(which(fixDF$variable=="Dic"))]<-df$year1 fixDF$CalendarYear[min(which(fixDF$variable=="Ene")):max(which(fixDF$variable=="Abr"))]<-df$year2 fixDF<-fixDF[,3:5] colnames(fixDF)<-c("Month","Flow.Measurement", "Calendar.Year")
-40147679 0 Here is my solution, hope will help.. :D
in your model.. i copy paste code bellow but i change a little..
function login ($username, $password) { $this->db->where('username' , $username); $this->db->where('password', $password); $query = $this->db->get('users'); if ($query->result())//if any record { $rows = $query->row(); $data = array( 'user_name' => $rows->username, 'logged_in' => TRUE, 'validated' => true ); $this->session->set_userdata($data); return true; } else { return false; } } delete your session_start() in controller,, and then in your application/config/autoload.php
in this $autoload['libraries'] = array(); => add session like this $autoload['libraries'] = array('session');
Thankyou.. :D
-35038315 0If you want to still break from if, you can use while(true)
Ex.
$count = 0; if($a==$b){ while(true){ if($b==$c){ $count = $count + 3; break; // By this break you will be going out of while loop and execute remaining code of $count++. } $count = $count + 5; // break; } $count++; } Also you can use switch and default.
$count = 0; if($a==$b){ switch(true){ default: if($b==$c){ $count = $count + 3; break; // By this break you will be going out of switch and execute remaining code of $count++. } $count = $count + 5; // } $count++; }
-38715869 0 getServicelocator() makes error. So it needs alternative way. And extends AbstractTableGateway or ServiceLocatorAwareInterface have errors.
Factory implementation will help Controller to get objects.
*User sample code will be similar to album.
1) factory class ( RegisterControllerFactory.php) * copied function createUser in controller
namespace Users\Controller\Factory; use Users\Controller\RegisterController; use Zend\ServiceManager\FactoryInterface; use Zend\ServiceManager\ServiceLocatorInterface; use Zend\ServiceManager\Exception\ServiceNotCreatedException; class RegisterControllerFactory { public function __invoke($serviceLocator) { $sm = $serviceLocator; $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); $resultSetPrototype = new \Zend\Db\ResultSet\ResultSet(); $resultSetPrototype->setArrayObjectPrototype(new \Users\Model\User); $tableGateway = new \Zend\Db\TableGateway\TableGateway('user' /* table name */, $dbAdapter, null, $resultSetPrototype); $user = new \Users\Model\User(); $userTable = new \Users\Model\UserTable($tableGateway); $controller = new RegisterController($userTable, $serviceLocator ); return $controller; } } 2) controller( RegisterController ) namespace Users\Controller;
use Zend\Mvc\Controller\AbstractActionController; use Zend\View\Model\ViewModel; use Users\Form\RegisterForm; use Users\Form\RegisterFilter; use Users\Model\User; use Users\Model\UserTable; use Zend\ServiceManager\ServiceLocatorInterface; class RegisterController extends AbstractActionController { protected $userTable; protected $serviceManager; public function __construct(UserTable $userTable, ServiceLocatorInterface $serviceManager) { $this->userTable = $userTable; $this->serviceManager = $serviceManager; } public function indexAction() { $form = new RegisterForm(); $viewModel = new ViewModel(array('form' => $form)); return $viewModel; } public function processAction() { if (!$this->request->isPost()) { return $this->redirect()->toRoute(NULL , array( 'controller' => 'register', 'action' => 'index' )); } $post = $this->request->getPost(); $form = new RegisterForm(); $inputFilter = new RegisterFilter(); $form->setInputFilter($inputFilter); $form->setData($post); if (!$form->isValid()) { $model = new ViewModel(array( 'error' => true, 'form' => $form, )); $model->setTemplate('users/register/index'); return $model; } // Create user $this->createUser($form->getData()); return $this->redirect()->toRoute(NULL , array( 'controller' => 'register', 'action' => 'confirm' )); } public function confirmAction() { $viewModel = new ViewModel(); return $viewModel; } protected function createUser(array $data) { /*able to delete or modify */ $sm = $this->serviceManager; $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); $resultSetPrototype = new \Zend\Db\ResultSet\ResultSet(); $resultSetPrototype->setArrayObjectPrototype(new \Users\Model\User); $tableGateway = new \Zend\Db\TableGateway\TableGateway('user' /* table name */, $dbAdapter, null, $resultSetPrototype); $user = new User(); $user->exchangeArray($data); $userTable = new UserTable($tableGateway); $userTable->saveUser($user); return true; } } 3) module.config.php
return array( 'controllers' => array( 'invokables' => array( 'Users\Controller\Index' => 'Users\Controller\IndexController', 'Users\Controller\login' => 'Users\Controller\LoginController', //delete 'Users\Controller\Register' ), 'factories' => array( 'Users\Controller\Register' => 'Users\Controller\Factory\RegisterControllerFactory', ), ),
-7045593 0 Try:
$(".blah").find($("input:text")).each(function(){ alert("Value inside "+$(this).attr("name")+" is #### " + this.value); });
-33394480 0 Remove the curly braces from around \@labs - they're converting the array you've created into an anonymous hash before passing it to to_json:
#!/usr/bin/perl -w use JSON -support_by_pp; use strict; my @labs = (); push (@labs, {id=>'1', title=>'Lab1'}); push (@labs, {id=>'2', title=>'Lab2'}); my $json_text = to_json \@labs, {ascii=>1, pretty => 1}; print $json_text; output:
[ { "title" : "Lab1", "id" : "1" }, { "title" : "Lab2", "id" : "2" } ]
-34674321 0 How can I use ProjectLocker instead of Git in laravel? Is there any setting available in Laravel to use ProjectLocker or other repository ?
-491951 0Host a Web service that logs the IP address of the requestor. Call the Web service in your application at startup. Location is tied to IP address and you could probably figure it out from there. :)
-2690048 0Finally fixed in 3.0.0.4.
-23161405 0You forgot the curly braces for the else-statement of your "recursive case" ...
This does work:
private static void combos(String counter) { if (counter.length() == userinput) //base case System.out.println(counter); else { combos(counter + "A"); combos(counter + "B"); combos(counter + "C"); } }
-1380703 0 Django's ORM will have trouble working with this table unless you add a unique primary key column.
If you do add a primary key, then it would be trivial to write a method to query for a given product ID and return a list of the values corresponding to that product ID. Something like:
def names_for(product_id): return [row.namestring for row in ProductName.objects.filter(product_id=product_id)] This function could also be a custom manager method, or a method on your Product model, or whatever makes most sense to you.
EDIT: Assuming you have a Product model that the product_id in this table refers to, and the only use you'll have for this table is to look up these names for a given product, your other option is to leave this table out of the ORM altogether, and just write a method on Product that uses raw SQL and cursor.execute to fetch the names for that product. This is nice and clean and doesn't require adding a unique PK to the table. The main thing you lose is the ability to administer this table via Django modelforms or the admin.
-26555085 0Change the line:
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False
To:
ActiveWorksheet.UsedRange.Copy
Activeworksheet.Range("A1").PasteSpecial Paste:=xlPasteValues
from product in context.Products where product.ProductCategory_Id == productcatid group product by product.Attribute_1 into g select g;
-34172900 0 The first version:
>>> a = [[]] * 3 creates a list that contains three times the same list. Look the ids of the elements:
>>> [id(x) for x in a] [4454962120, 4454962120, 4454962120] While this:
>>> b = [[], [], []] creates three different lists:
>>> [id(x) for x in b] >>> [4454963720, 4455011592, 4454853448] You can create a large list containing different sub-lists with a list comprehension:
>>> size = 100 >>> long_list = [[] for x in range(size)] Now appending to the first sub-list:
>>> long_list[0].append(10) >>> long_list[:10] changes only the first sub-list:
>>> long_list[:10] [[10], [], [], [], [], [], [], [], [], []]
-1423262 0 Jquery UI datePicker I have this code
$("#calendar").datepicker({ dateFormat: 'yy-mm-dd', onSelect: function(dateText, inst) { $('.selected-date').html(dateText); } }); I am looking for a way to send the date in 1 format to the database with ajax(not shown) and also update a div with a different date format. What is the best way to do this?
Update # 1
$("#calendar").datepicker({ dateFormat: 'yy-mm-dd', onSelect: function(dateText, inst) { var fmt2 = $.datepicker.formatDate("mm-dd-yy", dateText); $(".selected-date").html(fmt2); } }); Update # 2
$("#calendar").datepicker({ dateFormat: 'yy-mm-dd', onSelect: function(dateText, inst) { var d = new Date(dateText); var fmt2 = $.datepicker.formatDate("DD, d MM, yy", d); $(".selected-date").html(fmt2); } });
-3337441 0 MySQL - Searching in a multiple value field In my database table I have the following fields:
Table Supplier:
A supplier can have multiple vehicles. The field 'vehicles' will store multiple values. At the moment I am delimiting the values on a 'pipe' symbol, although this can be changed to a comma if need be.
On my front-end form I have a checkbox list - a user can select multiple vehicles. The back end script needs to do a search and bring back all suppliers that contain any of the specified vehicle id's.
So in other words we are searching with multiple values in a multiple value field.
The checkbox list name is vehicle_type[] and will end up in the $_POST array as (for example):
Array ( [0] => 1 [1] => 4 [2] => 6 ) Is this possible to do? I could obviously do this using a join table but ideally I would like to do it this way. I am using PHP as my scripting language if that helps.
-10702766 0This is, at it has been stated, not the optimal way to load resources, but if you absolutely must have a java.io.File reference, then try following:
URL url = null; try { URL baseUrl = YourClass.class.getResource("."); if (baseUrl != null) { url = new URL(baseUrl, "yourfilename.ext"); } else { url = YourClass.class.getResource("yourfilename.ext"); } } catch (MalformedURLException e) { // Do something appropriate } This gives you a java.net.URL and it can be used in a java.io.File constructor.
Something that you could do is to send 2 parameters to the url :
In your asp file, just get the 2 parameters content, make a base 64 decode, and write it in a file named as the filename parameter ...
-33726965 0The context of a process (psw, state of registers,pc...) is saved in the PCB of the process, in the kernel space of memory, not in the stack. Yes, there is one stack for each user process and more, one stack for each thread in the user space memory. In the kernel, the data structures are shared by the multiples codes of the function in the kernel. The stack is used for the call of procedure and for the local variables, not for saving the context.
-11675476 0You can solve this problem easily by removing a couple of texts.
Because there are a wrong annotation in "js/jquery.wt-rotator.js".
From :
//Line: 1842 //set delay //this._delay = this._$items[i].data("delay"); To :
//set delay this._delay = this._$items[i].data("delay");
-36078935 0 how to extends a module in typescript I'm still new to typescript, so any direction would be appreciated. Thanks!
file A:
module SoundManager { export class SoundManager { } export function init($s: string):void { } } file B:
module SoundM { class SoundM extends SoundManager { } export function init($s:string): void { super.init($s); } } this will return the error:
-12546153 0Error TS2507 Type 'typeof SoundManager' is not a constructor function type.
At the Servers side you can just check for:
if(isset($_POST['name'])) { } // only send the mail if this is true. There are also many client side solutions. You could also write your own using Javascript. You will have to still include the checks on the server-side tho since "client-side security does not work".. The user could just disable Javascript and submit the form without the checks running.
Here is an example for a JS library that does form validation:
http://rickharrison.github.com/validate.js/
I found it by googling for javascript form validation
So I think I figured it out. It boils down to a chicken or egg scenario. When you register a generic class via the RegisterGeneric method, Autofac will not automatically register the closed types unless it detects them somewhere in your object graph as a dependency.
Ctor 1 doesn't trigger closed generics to be registered:
public MessageHandlerFactory(IEnumerable<IMessageHandler> handlers){ }
Ctor 2 does trigger closed generics to be registered:
public MessageHandlerFactory(IEnumerable<IMessageHandler> handlers, MessageHandler<ComplexMessage> complexHandler, MessageHandler<SimpleMessage> simpleHandler ){} Once I manually registered the closed generics using the code below, Autofac began injecting them as part of the IEnumerable<IMessageHandler> dependency seen on Ctor 1
builder.RegisterType(typeof(MessageHandler<ComplexMessage>)).AsImplementedInterfaces(); builder.RegisterType(typeof(MessageHandler<SimpleMessage>)).AsImplementedInterfaces();
-7664927 0 I use tooltipsy, this is an EXCELLENT tooltip program. You can set it to do pretty much anything you want. If you want custom CSS, okay, if you want to set your own show and hide events, okay, you can change what the tooltip aligns to, the delay until it shows, you can do whatever you want. Tootipsy is the best one I ever used. (I had to make a little modification to it to get it to use HTML in the tooltips though, but it's a very simple change)
-33077123 0 Floating Action Button diasappears under SECOND SnackbarI'm using a CoordinatorLayout to keep my Floating Action Button above the Snackbar, which works great. ...But only for the first Snackbar. When a second one is created, while the first one is still there, the FAB slides under it.
I'm using this in a RecyclerView in which I can remove items. When an item is removed, a "Undo" Snackbar appears. So when you delete some items one after another, the visible Snackbar is replaced by a new one (which causes the FAB behaviour)
Do you know a solution to keep the FAB above new Snackbars?
<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:fab="http://schemas.android.com/tools" android:id="@+id/coordinator_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:backgroundTint="@color/background_grey" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <include android:id="@+id/toolbar" layout="@layout/toolbar" /> <android.support.v7.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="match_parent" android:scrollbars="vertical" /> </LinearLayout> <android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|end" android:layout_marginBottom="16dp" android:layout_marginEnd="16dp" android:layout_marginRight="16dp" android:elevation="6dp" android:src="@drawable/ic_add_white_36dp" app:borderWidth="0dp" app:fabSize="normal" app:pressedTranslationZ="10dp" app:rippleColor="@color/abc_primary_text_material_dark" /> </android.support.design.widget.CoordinatorLayout> This is how it looks after I delete on item
...and then after I delete another item
-29006359 0 NHibernate hql tuple resulthql = "select f, b from Foo f, Bar b" var resultList = session.CreateQuery(hql).List<object[]>(); result list item is an array where [0] is of type Foo and [1] id of Type Bar
Is there a way to use Tuple<Foo,Bar> (or other generic class ) as generic parameter insted of object[] so one can skip casting?
-28060954 0you could try something like
B.x.where(B.x.str.contains(A.x), B.index, axis=index) #this would give you the ones that don't match B.x.where(B.x.str.match(A.x, as_indexer=True), B.index, axis=index) #this would also give you the one's that don't match. You could see if you can use the "^" operator used for regex to get the ones that match. You could also maybe try
np.where(B.x.str.contains(A.x), B.index, np.nan) also you can try:
matchingmask = B[B.x.str.contains(A.x)] matchingframe = B.ix[matchingmask.index] #or matchingcolumn = B.ix[matchingmask.index].x #or matchingindex = B.ix[matchingmask.index].index All of these assume you have the same index on both frames (I think)
You want to look at the string methods: http://pandas.pydata.org/pandas-docs/stable/text.html#text-string-methods
you want to read up on regex and pandas where method: http://pandas.pydata.org/pandas-docs/dev/indexing.html#the-where-method-and-masking
-14029580 0You are using static method for custom sorting, so you can set some static properties in this class before usort
class Catalogs_model{ public static $usort_criteria = array(); public static function multi_compare($a,$b){ foreach(self::$usort_criteria as $what => $order){ if($a[$what] == $b[$what]){ continue; } return (($order == 'desc')?-1:1) * strcmp($a[$what], $b[$what]); } return 0; } } Catalogs_model::$usort_criteria = array( 'con' => 'asc', 'title' => 'asc' ); usort($arrCatalog, array('Catalogs_model', 'multi_compare')); of course it needs some tweaking , because now it only sorts strings.
-21299729 0Instead of a loop, just re-trigger the input from the done() code. You'd probably want to name this function so it can refer to itself.
-18462920 0exec 3>&1 1>>${LOG_FILE} 2>&1 would send stdout and stderr output into the log file, but would also leave you with fd 3 connected to the console, so you can do
echo "Some console message" 1>&3 to write a message just to the console, or
echo "Some console and log file message" | tee /dev/fd/3 to write a message to both the console and the log file - tee sends its output to both its own fd 1 (which here is the LOG_FILE) and the file you told it to write to (which here is fd 3, i.e. the console).
Example:
exec 3>&1 1>>${LOG_FILE} 2>&1 echo "This is stdout" echo "This is stderr" 1>&2 echo "This is the console (fd 3)" 1>&3 echo "This is both the log and the console" | tee /dev/fd/3 would print
This is the console (fd 3) This is both the log and the console on the console and put
This is stdout This is stderr This is both the log and the console into the log file.
-24202717 0 Optimize mysql multiple left joinsI have a query like this:
SELECT SUM(c.cantitate) AS num, p.id AS pid, p.titlu AS titlu, p.alias AS alias, p.gramaj AS gramaj, p.prettotal AS prettotal, p.pretunitar AS pretunitar, p.pretredus AS pretredus, p.stoc AS stoc, p.cant_variabila AS cant_variabila, p.nou AS nou, p.congelat AS congelat, p.cod AS cod, p.poza AS poza, cc.seo AS seo FROM produse p LEFT JOIN (SELECT produs, cantitate, COS FROM comenzi) c ON p.id = c.produs LEFT JOIN (SELECT STATUS, id FROM cosuri) cs ON c.cos = cs.id LEFT JOIN (SELECT id, seo FROM categorii) cc ON p.categorie = cc.id WHERE cs.status = 'closed' AND p.vizibil = '1' GROUP BY pid ORDER BY num DESC LIMIT 0, 14 The query is working, but Duration for 1 query: 2.922 sec. How can I improve the query ?
The keys are as following :
comenzi: cos, produs as unique key
cosuri: id as unique key
produse: titlu, categorie, alias as key
-32437268 0Let’s look at three common reasons for writing inner functions.
The value in the enclosing scope is remembered even when the variable goes out of scope or the function itself is removed from the current namespace.
def print_msg(msg): """This is the outer enclosing function""" def printer(): """This is the nested function""" print(msg) return printer # this got changed Now let's try calling this function.
>>> another = print_msg("Hello") >>> another() Hello That's unusual. The print_msg() function was called with the string "Hello" and the returned function was bound to the name another. On calling another(), the message was still remembered although we had already finished executing the print_msg() function. This technique by which some data ("Hello") gets attached to the code is called closure in Python.
So what are closures good for? Closures can avoid the use of global values and provides some form of data hiding. It can also provide an object oriented solution to the problem. When there are few methods (one method in most cases) to be implemented in a class, closures can provide an alternate and more elegant solutions. Reference
General concept of encapsulation is to hide and protect inner world from Outer one, Here inner functions can be accessed only inside the outer one and are protected from anything happening outside of the function.
Perhaps you have a giant function that performs the same chunk of code in numerous places. For example, you might write a function which processes a file, and you want to accept either an open file object or a file name:
def process(file_name): def do_stuff(file_process): for line in file_process: print(line) if isinstance(file_name, str): with open(file_name, 'r') as f: do_stuff(f) else: do_stuff(file_name) For more you can refer this blog.
-12695424 0 Window.location takes me to new page even when current form is not submitted completely.I am trying to redirect to different page after current form has been submitted but as it turns out, using window.location am diverted to new page very quickly and seems like my current form is not at all submitted.
Here the function that am using.
function updateImportJobTypeSettings() { var importJob = document.getElementById("jobtype").value; var parser = document.getElementById("selectparser"); var parserValue = parser.options[parser.selectedIndex].value; document.importJobManagmentForm.action="/admin/ImportJobManagment.jsp"; document.importJobManagmentForm.requestAction.value="updateImportJobSettings"; document.importJobManagmentForm.ImportJobParser.value=parserValue; document.importJobManagmentForm.ImportJobManagmentType.value=importJob; document.importJobManagmentForm.DivHidden.value="visible"; document.importJobManagmentForm.submit(); window.location = "/admin/ImportJobManagmentList.jsp" } My goal is that after ImportManagment.jsp page is submitted, I want to come back to ImportJobManagmentList.jsp page to see all data that were submitted to ImportJobManagment.jsp
Think to note here is that if I put debugger on then I do see that new job is created on JobList but if I go and try to update it, again new job is created rather than doing an update to the previous job.
-28995302 0I don't understand what exactly you need,
But it seems that you mixed types INT and DATE.
So if your in_date field has type DATE
select cust_no, cust_name, sum(bvtotal) as Amount from sales_history_header where cust_no is not null and number is not null and bvtotal > 1000 and in_date < DATE('2014-01-01') group by cust_no,cust_name order by sum(bvtotal) desc; If your in_date field has type TIMESTAMP
select cust_no, cust_name, sum(bvtotal) as Amount from sales_history_header where cust_no is not null and number is not null and bvtotal > 1000 and in_date < TIMESTAMP('2014-01-01 00:00:00') group by cust_no,cust_name order by sum(bvtotal) desc;
-1334529 0 What could cause "PROCEDURE schema.identity does not exist" using MySQL and Hibernate? Using Java, Hibernate, and MySQL I persist instances of a class like this using the Hibernate support from Spring.
@Entity public class MyEntity implements Serializable { private Long id; @Id @GeneratedValue(strategy = GenerationType.AUTO) public Long getId() { return id; } public void setId(Long id) { this.id = id; } } This generally works fine. But now and then when trying to persist such an entity, I get this:
java.sql.SQLException: PROCEDURE schema.identity does not exist The underlying MySQL error is:
SQL Error: 1305, SQLState: 42000 This is a regular MySQL error described in the MySQL manual.
My problem is that this system worked for months without any problem. Only recently I discovered the error described above. Do you have any ideas what could have caused this problem? What does Hibernate look for and doesn't find?
If this question should be on serverfault, feel free to migrate it :)
-21993202 0Have a try and add this header:
Disposition-Notification-To: "User" <user@user.com> The reader may need to confirm that you get a reply. Also adding html content served by your server can be an option to recognize that the mail is read.
You should be able to do this with any of these lines
msg['Disposition-Notification-To'] = '"User" <user@user.com>' msg['Disposition-Notification-To'] = 'user@user.com'
-35154988 0 Error: Recompile with -fPIC when trying to ./configure && make package nap I am trying to configure and make install package nap6.4 for tcl, but it fails in during "make" with the following error:
cc -shared -o libnap6.4.so cart_proj.o eval_tree.o function.o geometry.o land_flag.o land_flag_i.o linsys.o nap.o napChoice.o napDyad.o napDyadLib.o napImgNAO.o napInit.o napLib.o napMonad.o napParse.tab.o napParseLib.o napPolygon.o napSpatial.o nap_get.o nap_hdf.o nap_netcdf.o nap_ooc.o triangulate.o -L/usr/local/lib -lnetcdf -L/usr/local/lib -lmfhdf -ldf -ljpeg -lz -L/usr/local/lib -lproj -L. -ltclstub8.4 -ltkstub8.4 -lieee -lm -lX11 /usr/bin/ld: /usr/local/lib/libmfhdf.a(mfsd.o): relocation R_X86_64_32 against `.rodata.str1.1' can not be used when making a shared object; recompile with - fPIC /usr/local/lib/libmfhdf.a: error adding symbols: Bad value collect2: error: ld returned 1 exit status make: *** [libnap6.4.so] Error 1 So I was told to recompile with -fPIC, which I did in the following way from the terminal:
export CFLAGS=-fPIC ./configure --prefix/lib/ActiveTcl --enable-shared make but this does not work. I have also tried with --disable-shared, make clean, and
export CFLAGS="-fPIC -DHAVE_NETCDF"/ export CFLAGS="-fPIC" etc.. along with other not-working versions of CFLAGS.
So I am wondering how do I recompile with -fPIC? Is there some special syntax that I'm missing here?
-28080072 0Just find out all cookies start with "Cookie" and then do the same as that answer one by one.
document.cookie.split('; ') .map(function (x) { return x.split('=', 1)[0]; }) .filter(function (x) { return x.substring(0, 6) === 'Cookie'; }) .forEach(function (name){ // set the domain var domain = ".jsfiddle.net"; // get a date in the past var expireDate = new Date(-1).toUTCString(); // clear the cookie and force it to expire document.cookie = name + "=; domain=" + domain + "; path=/; expires=" + expireDate; });
-40519898 0 Counting specific lines in a log file I have a log file containing more than 100000 lines similar to the following
2016-11-08 17:04:01|x.x.x.x|xxxxxxxxxxxxx|x.x.x.x|1002|xxxx|xxxxxx|1|2|https://xxxxxxxxx/xxxxxxx/xxxxxxx/xxxxxx{"status":500,"body":""} 2016-11-08 17:04:02|x.x.x.x|xxxxxxxxxxxxx|x.x.x.x|1003|xxxx|xxxxxx|1|2|https://xxxxxxxxx/xxxxxxx/xxxxxxx/xxxxxx{"status":400,"body":""} Please help me to write a script that will return a count of lines only with "status":500.
While I've heared I need to use something called "job queue" I'm new to this and I've had hard time setting it all up. How do I execute function after returning a response in flask? Could you walk me through the process?
-18630753 0you should assume charset type.
-25337332 0public enum PairOddEnum { Evens, Odds, Both } public void BindControl(PairOddEnum type) { if (this.textBox1.Text != "") { List<string> numbersText = this.textBox1.Text.Split(',').ToList<string>(); var evens = numbersText.Where(t => int.Parse(t) % 2 == 0).Distinct(); var odds = numbersText.Where(t => int.Parse(t) % 2 == 1).Distinct(); if (type == PairOddEnum.Evens) { ListBoxEvenNumbers.DataSource = evens.ToList(); } else if (type == PairOddEnum.Odds) { ListBoxOddNumbers.DataSource = odds.ToList(); } else { ListBoxEvenNumbers.DataSource = evens.ToList(); ListBoxOddNumbers.DataSource = odds.ToList(); } } } protected void ButtonClassify_Click(object sender, EventArgs e) { if (RadioButtonList1.SelectedValue == "Both") { BindControl(PairOddEnum.Both); } if (RadioButtonList1.SelectedValue == "Even") { BindControl(PairOddEnum.Evens); } if (RadioButtonList1.SelectedValue == "Odd") { BindControl(PairOddEnum.Odds); } }
-9268047 0 Googleupdate.exe /c parameter is used for? I recently installed google chrome v. 17, and among programs loaded when the system start I found the file below:
C:\Users\Admin\AppData\Local\Google\Update\GoogleUpdate.exe" /c
This file would serve to check updates for google chrome, but /c parameter is used for?
On compilation it is generating:
[Warning] overflow in implicit constant conversion [-Woverflow] and that's why you are getting
-1,2,-3 as output.
Note: Always use debugger and debug your program.
private function setXY(ct:Object, yt:Object){ tt.txt_ct.embedFonts = false; tt.txt_yt.embedFonts = false; tt.txt_ct.text = ct.toString(); tt.txt_yt.text = yt.toString(); }
-29973534 1 Summing and dividing by different categories conversion from Python to R I have a set of vectors containing category values, lets call them, C1, C2,...and I have a frequency vector called Fr. All vectors are of the same length. I want to divide the frequency values in Fr by sums dependent on the categories. In Python using numpy this is fairly easy.
# Find unique categories unqC1 = np.unique(C1) unqC2 = np.unique(C2) # For each unique category in C1 and C2 sum frequencies and normalize for uC1 in unqC1: for uC2 in unqC2: mask = (uC1 == C1) & (uC2 == C2) nrmFactor = np.sum(Fr[mask]) Fr[mask] /= nrmFactor How can I do this in R? For simplicity lets say I have a table X, in R, with the columns X$Fr, X$C1 and X$C2.
-14966267 0Why not simply do one at a time?
#!/bin/bash echo "Importing URLs..." file=sizeurls.csv echo "Gathering page sizes..." while IFS= read -r url do phantomjs yslow.js --info basic --format plain $url | grep 'url\|size' done < "$file" > temp.txt echo "Formatting data..." sed -i -e 's/size://g' -e 's/url://g' temp.txt paste - - -d, < temp.txt > pagesize.csv echo "Done!"
-17875803 0 Zooming Distortation I am having a problem with my website, every time I adjust the zoom it distorts the page layout, I don't know what I've done wrong, please take a look at what I mean: Distorted Normal
-15815072 0 SQL Server "Deny View Any Database To" in stored procI have a script which generates a database for a given {databaseName}, and then creates a login for a given {loginName} for this database.
I then want restrict this user to only be able to view this database, and no others.
I have this working through the use of:
USE [{DatabaseName}] GO ALTER AUTHORIZATION ON DATABASE::[{DatabaseName}] to [{LoginName}] GO USE [master] GO DENY VIEW ANY DATABASE TO [{LoginName}] GO I have now put this into a stored procedure, but I cannot change to the [master] database to execute the last line:
DENY VIEW ANY DATABASE TO [{LoginName}] Is there a way to restrict the user from seeing other database from within a stored procedure?
The stored procedure is currently on another database, but I am able to move it.
-6933483 0this code looks correct, are you sure the crash isn't somewhere else?
EDIT: as noted in the comments, NSString being immutable won't cause the copy to allocate a new object. I've edited the answer for the mutable case, just in case someone stumbles into this later and doesn't read the whole thing. Now back with our regular programming.
Don't know if this might be the problem, but note that, if you were using a mutable object like NSMutableString, with copy you would not increment the retain count, you would effectively create a new object, so what would happen:
NSMutableString* newString = [[NSMutableString alloc] init..]; // allocate a new mutable string self.originalString=newString; // this will create yet another string object // so at this point you have 2 string objects. [newString relase]; //this will in fact dealloc the first object // so now you have a new object stored in originalString, but the object pointed // to by newString is no longer in memory. // if you try to use newString here instead of self.originalString, // it can indeed crash. // after you release something, it's a good idea to set it to nil to // avoid that kind of thing newString = nil;
-21743638 0 To disable only DTC you need to add this to your endpoint config:
Configure.Transactions.Advanced(settings => settings.DisableDistributedTransactions());
-19253397 0 DataBinding multiple instances of members of a class to specific labels 
I have a class that has a private member of another class, and which that class is an ObserveableCollection of another class.. and this is the class I need info from, that has private members that I want to databind.
private readonly NflGameCollection _games; .... class NflGameCollection : ObservableCollectionEx<NflGameStatus> {... class NflGameStatus : INotifyPropertyChanged { //***these are the members i want databound*** private readonly string _homeTri; private readonly string _awayTri; private string _homeScore; private string _awayScore; so multiple instances of this NflGameStatus will pop up everytime it detects a game... which the only way i know how to access it is by doing this:
_controller = new DtvGsisDataParser.AppController(); foreach (var item in _controller.Games) { string hometri = item.HomeTri; string awaytri = item.AwayTri; ... etc etc } how can i get it so that if a hometri and awaytri are equal to what i'm looking for... i can get the other instances of that class? for example
if item.HomeTri==what i want && item.AwayTri==what i want then bind item._homeScore to a certain label then bind item.awayAScore to a certain label. i know what i'm asking for is kinda complex.. but i'm kinda desperate here and would appreciate any help. this databinding is very new to me and i'm having trouble grasping it. is this even possible? the more i research the more i dont think so.. but i'm hoping i'm not. thanks for any help
-9791794 0You can use ini_set to set the value of a given configuration option.
continue on PHP duplicate staffID
code
$data[0] = 0001,Ali,N,OK
$data[1] = 0002,Abu,N,OK
$data[2] = 0003,Ahmad,N,OK
$data[3] = 0004,Siti,Y,Not OK. Only one manager allowed!
$data[4] = 0005,Raju,Y, Not OK. Only one manager allowed!
I write it as following:
for($i = 0; $i < 5; $i++) { $data[i] = $staffID[$i].','.$staffname[$i].','.$ismanager[$i].','.$remark[$i]; } Next I go to write csv file.
$file_format = "staffreport.csv"; $file = fopen($file_format,"w"); foreach($data as $line) { $replace = str_replace(",","|", $line); fputcsv($file, array($replace)); echo $replace.'<br />'; } fclose($file); output (echo $replace)
0001|Ali|N|OK
0002|Abu|N|OK
0003|Ahmad|N|OK
0004|Raju|Y|Only one manager allowed!
0005|Siti|Y|Only one manager allowed!
In CSV file (staffreport.csv)
0001|Ali|N|OK
0002|Abu|N|OK
0003|Ahmad|N|OK
"0004|Siti|Y|Only one manager allowed!"
"0005|Raju|Y|Only one manager allowed!"
Why my csv file have double quote("")? How do I solve it?
you can modify the sass variables that set the breakpoints that define the media queries, just set them to extreme values so that they do not trigger. This will provide very poor ux on devices with small displays. Another solution would be to match all of the grids, so if you have a .large-12 then add .small-12 .large-12 for each instance.
Here are the defaults pulled from the zurb foundation docs:
$small-range: (0em, 40em); $medium-range: (40.063em, 64em); $large-range: (64.063em, 90em); $xlarge-range: (90.063em, 120em); $xxlarge-range: (120.063em); $screen: "only screen" !default; $landscape: "#{$screen} and (orientation: landscape)" !default; $portrait: "#{$screen} and (orientation: portrait)" !default; $small-up: $screen !default; $small-only: "#{$screen} and (max-width: #{upper-bound($small-range)})" !default; $medium-up: "#{$screen} and (min-width:#{lower-bound($medium-range)})" !default; $medium-only: "#{$screen} and (min-width:#{lower-bound($medium-range)}) and (max-width:#{upper-bound($medium-range)})" !default; $large-up: "#{$screen} and (min-width:#{lower-bound($large-range)})" !default; $large-only: "#{$screen} and (min-width:#{lower-bound($large-range)}) and (max-width:#{upper-bound($large-range)})" !default; $xlarge-up: "#{$screen} and (min-width:#{lower-bound($xlarge-range)})" !default; $xlarge-only: "#{$screen} and (min-width:#{lower-bound($xlarge-range)}) and (max-width:#{upper-bound($xlarge-range)})" !default; $xxlarge-up: "#{$screen} and (min-width:#{lower-bound($xxlarge-range)})" !default; $xxlarge-only: "#{$screen} and (min-width:#{lower-bound($xxlarge-range)}) and (max-width:#{upper-bound($xxlarge-range)})" !default;
-112850 0 It seems that whenever you talk about anything J2EE related - there are always a whole bunch of assumptions behind the scenes - which people assume one way or the other - which then leads to confusion. (I probably could have made the question clearer too.)
Assuming (a) we want to use container managed transactions in a strict sense through the EJB specification then
Session facades are a good idea - because they abstract away the low-level database transactions to be able to provide higher level application transaction management.
Assuming (b) that you mean the general architectural concept of the session façade - then
Decoupling services and consumers and providing a friendly interface over the top of this is a good idea. Computer science has solved lots of problems by 'adding an additional layer of indirection'.
Rod Johnson writes "SLSBs with remote interfaces provide a very good solution for distributed applications built over RMI. However, this is a minority requirement. Experience has shown that we don't want to use distributed architecture unless forced to by requirements. We can still service remote clients if necessary by implementing a remoting façade on top of a good co-located object model." (Johnson, R "J2EE Development without EJB" p119.)
Assuming (c) that you consider the EJB specification (and in particular the session façade component) to be a blight on the landscape of good design then:
Rod Johnson writes "In general, there are not many reasons you would use a local SLSB at all in a Spring application, as Spring provides more capable declarative transaction management than EJB, and CMT is normally the main motivation for using local SLSBs. So you might not need th EJB layer at all. " http://forum.springframework.org/showthread.php?t=18155
In an environment where performance and scalability of the web server are the primary concerns - and cost is an issue - then the session facade architecture looks less attractive - it can be simpler to talk directly to the datbase (although this is more about tiering.)
-24761939 0 System.IO.Compression.FileSystem not found with VS 2010 Express 4.5.50938I have VS 2010 Express 4.5.50938, but when I go to add a reference there is no System.IO.Compression.FileSystem under .NET tab, but I found a 4.0 version under the Recent Tab. When program runs I receive:
Warning 1 Reference to type 'System.IO.Compression.CompressionLevel' claims it is defined in 'c:\Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\Profile\Client\System.dll', but it could not be found c:\Windows\Microsoft.NET\assembly\GAC_MSIL\System.IO.Compression.FileSystem\v4.0_4.0.0.0__b77a5c561934e089\System.IO.Compression.FileSystem.dll Zip_Copy_To_Public Do I copy the dll into this directory?
-2703227 0Reading your problem description "each box contain 10 piece of numbered paper (1 - 10) but there is a number the same in all 3 boxes" I take it that:
Like here, where the number '8' is the only one to appear in all three boxes.
int[] a = new int[] { 3, 2, 7, 5, 8, 2, 10, 6, 9, 7, 3 }; int[] b = new int[] { 1, 4, 8, 7, 5, 1, 3, 2, 2, 4, 1 }; int[] c = new int[] { 8, 4, 1, 6, 10, 9, 6, 4, 9, 6, 4 }; Is that your problem?
Then you wrote: "How to find that repeated number in java with an efficient/fastest way possible?"
Now how efficient/fast do you want to be? Are you talking about O(n) efficient (even though the boxes are unsorted), like here (slightly obfuscated to confuse you a bit):
int s = 0; int t = 0; int u = 0; for (int i = 0; i < 10; i++) { s |= 1 << a[i]; t |= 1 << b[i]; u |= 1 << c[i]; } System.out.println( Integer.numberOfTrailingZeros( s & t & u ) ); ; )
Somehow I'm not sure your teacher will think you came up with that answer : )
-23111646 0 get customer payment ids from CIMHow can I get customer payment method ids from AuthorizeNetCIM_Response object?
There's a method in AuthorizeNetCIM_Response which is supposed to return payment method ids
public function getCustomerPaymentProfileIds() { $ids = (array)$this->xml->customerPaymentProfileIdList; return $ids["numericString"]; } but calling this function results in error
Notice: Undefined index: numericString
The response object outputs as:
AuthorizeNet_AuthorizeNetCIMResponse Object ( [xml] => SimpleXMLElement Object ( [messages] => SimpleXMLElement Object ( [resultCode] => Ok [message] => SimpleXMLElement Object ( [code] => I00001 [text] => Successful. ) ) [profile] => SimpleXMLElement Object ( [merchantCustomerId] => 10 [email] => user@nine.com [customerProfileId] => 25441529 [paymentProfiles] => Array ( [0] => SimpleXMLElement Object ( [billTo] => SimpleXMLElement Object ( [firstName] => [lastName] => [address] => [city] => [zip] => [country] => [phoneNumber] => ) [customerPaymentProfileId] => 23298664 [payment] => SimpleXMLElement Object ( [creditCard] => SimpleXMLElement Object ( [cardNumber] => XXXX2224 [expirationDate] => XXXX ) ) ) [1] => SimpleXMLElement Object ( [customerType] => individual [billTo] => SimpleXMLElement Object ( [firstName] => Test [lastName] => Individual [company] => SimpleXMLElement Object ( ) [address] => [city] => [state] => [zip] => [country] => [phoneNumber] => SimpleXMLElement Object ( ) [faxNumber] => SimpleXMLElement Object ( ) ) [customerPaymentProfileId] => 23299421 [payment] => SimpleXMLElement Object ( [creditCard] => SimpleXMLElement Object ( [cardNumber] => XXXX0027 [expirationDate] => XXXX ) ) ) ) ) ) and I supposed to get the array of paymentProfiles as
$response->xml->profile->paymentProfiles;
but it only returning the first element of paymentProfiles not an array.
When I try to apply "not_analyzed" into my ES mapping it doesnt work.
I am using this package for ES in Laravel - Elasticquent
My mapping looks like:
'ad_title' => [ 'type' => 'string', 'analyzer' => 'standard' ], 'ad_type' => [ 'type' => 'integer', 'index' => 'not_analyzed' ], 'ad_type' => [ 'type' => 'integer', 'index' => 'not_analyzed' ], 'ad_state' => [ 'type' => 'integer', 'index' => 'not_analyzed' ], Afterwards I do an API get call to view the mapping and it will output:
"testindex": { "mappings": { "ad_ad": { "properties": { "ad_city": { "type": "integer" }, "ad_id": { "type": "long" }, "ad_state": { "type": "integer" }, "ad_title": { "type": "string", "analyzer": "standard" }, "ad_type": { "type": "integer" }, Note that not_analyzed is missing. I cant see any errors/warnings in my logs either.
-37303810 0Try this:
function Contact_OnAddTelephone() { var type = $("#rdoTelephoneType").val(), areaCode = $("#txtAreaCode").val(), radio = $('<input>').attr({ type: 'radio', id: 'rdoTelePrimary', name: 'rdoTelePrimary', onclick: 'myRadioButtonClickFunction' }); $('#tableTelephone tr:last').after("<tr><td>" + type + "</td><td>" + areaCode + "-" + number + "</td><td>" + radio[0].outerHTML + "</td></tr>"); } function myRadioButtonClickFunction(){ // do stuff } NB: Not tested.
By the way, you might want to use camelCase on function names.
-28361463 0Well, if you do not need all the members of your base class in your derived class, then yes, there will be a waste of memory.
One should probably code in such a manner as to reduce wastage of memory like this.
-7816994 0Why don't you use a framework for that job?
You can try json-framework (formerly SBJSon).
Project page : https://github.com/stig/json-framework
-28868383 0Use the Party Model.
A user is not a person, it's a user. Person and organization are parties. A party hasOne (or no) user.
A person hasMany (many2many) relationships with an organization:
Individual -< Relationship >- Organization
Organizations can have relationships with each other too.
-657912 0Resigning over that is a stupid move. You've raised your concerns and maybe they might be taken on board next time.
Doing something only supported in Internet Explorer is something I've done in the past. Try coding in a warning for other browsers or something to at least show you're aware.
-14809304 0You must have the mime_magic extension on. Check your php.ini and look in phpinfo(). By the way this function has been deprecated as the PECL extension Fileinfo provides the same functionality (and more) in a much cleaner way.
-3655344 0Windows users must include the bundled php_fileinfo.dll DLL file in php.ini to enable this extension.
The libmagic library is bundled with PHP, but includes PHP specific changes. A patch against libmagic named libmagic.patch is maintained and may be found within the PHP fileinfo extensions source.
It really depends on how much this format might change over time and what you want to rely on as constant. If you want to assume that your html will always start with <div class="plugin-block"> and the text you want will always be on a line after an h3, you can do something like this:
$pattern = '/plugin-block(?:\n|.)*?<\/h3>\s*(.+)/'; preg_match($pattern, $html, $matches); echo $matches[1]; //**Intergrate Sailthru API functionality into your WordPress blog.**
-11282594 0 What options do I have for storing information on Windows? How should I read this information? what options I have for storing information on Windows?
I was thinking of creating a file or working with the registry but the file could get rather annoying to handle if it gets too big and the registry is a bit too easily accessible by the user.
I don't expect there to be more than a max of 100 entries and they would look something like this.
John Banana
Marcus Apple
etc.
I realize this wouldn't produce a too big file but I dont want to parse it everytime I need the information. I was thinking of reading the information into the application on startup but wouldn't that create performance issues? Or perhaps it's so little it wouldn't matter except for older computers? Are there any other options? Perhaps I could encrypt the information and put it in the registry? Is the registry suitable for putting multiple entries such as this?
Note that when I program I sometimes go a bit too overboard when it comes to making things efficient. Excuse my ignorance.
-28628287 0 Send data from javascript to html and fetch with phpok, i don't know if this is the proper way of doing this. If not, please give me an example on how to do it. How do i fetch the data in the JS and send it to html?
JS
$(document).ready(function() { var choosenYear = $('#choose_year'); $("#choose_year").select2({ data: [{ id: 0, text: '2015' }, { id: 1, text: '2014' }], val: ["0"] }).select2('val', 0); // Start Change $(choosenYear).change(function() { var choosenYear = $(choosenYear).select2('data').id; $('#choosen_year').val(choosenYear); }); //Change }); HTML
<form class="form-inline well col-md-8" id="form-choose_usr" action="#" method="post" enctype="multipart/form-data"> //This is what i POST <div> <input type='hidden' class='col-md-4' id='choose_usr_email' name='choose_usr_email'> </div> <!-- Select2 choose_year --> <div> <input type='hidden' class='col-md-2' id='choose_year' name='choose_year'> </div> <!-- Select2 choose_month --> <div> <input type='hidden' id='choosen_year' name='choosen_year'> <input type="submit" class="btn btn-info pull-right" value="Hämta" /> PHP
//And this is how i fetch it $posted_choosen_year = $_POST['choosen_year']; echo $posted_choosen_year;
-36289060 0 In your no-arg constructor, the line
this(2.5, 1, 1000); explicitly means "call another constructor for the same class as the current constructor, but which takes these arguments".
So that's why adding the other constructor fixes the problem. The order in which you pass the arguments needs to match the order in which the parameters appear on that constructor, that constructor's parameter list defines the order you need to put the arguments in when calling it.
The relationship between these two constructors is that they are chained. The one with the 3 arguments is the primary constructor, the other calls the primary constructor with default values. Designing constructors in this way helps to initialize your objects consistently, because a single primary constructor always gets called. (For instance, the loanDate instance field gets set regardless of which constructor you call.)
-33181965 0 Change Netbeans preview from an external LookAndFeelI downloaded 4 LookAndFeel(LAF) libraries and one of them is SeaGlass LAF for java GUI, so far I managed to use them by writing this line:
UIManager.setLookAndFeel(new SeaGlassLookAndFeel()); but while I'm desinging I have to see what I'm building in the default Metal LAF in Netbeans, so the only way for me to see the real result is by running the application. I know there's a way to change JFrame Preview design, and I know how to do it, but I don't know how can I add my LAF libraries to this list Netbeans provides. So I will really appreciate an answer.. I've looked everywhere, I know there's another guy who talks about something like this in another post but I couldn't found the answer there.
-8604042 0You need no DataAnnotation Attribute to do that. In Codefirst you can do the following. The Entity Framework will generate the table you described for you.
Account { public int Id; } Job { public int Id; public virtual Account Account; } Practice { public int Id; public virtual Account Account; public string Name; } If you want also a ìnt column (AccountId) in your Job / Practice Entity you can do this using the ModelBuilder. The Entity Framwork creates only one foreign key column, like you want.
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Job>.HasRequired(x => x.Account).WithMany().HasForeignKey(x => x.Accountid); // } ScottGu - Using EF “Code First” with an Existing Database
You can use Entity Framework Power Tools CTP1 to generate the Models from your existing Database.
-18964073 0Change your jquery to this:
; (function ($) { $.fn.placehold = function (placeholderClassName) { var placeholderClassName = placeholderClassName || "placeholder", supported = $.fn.placehold.is_supported(); function toggle() { for (i = 0; i < arguments.length; i++) { arguments[i].toggle(); } } return supported ? this : this.each(function () { var $elem = $(this), placeholder_attr = $elem.attr("placeholder"); if (placeholder_attr) { if ($elem.val() === "" || $elem.val() == placeholder_attr) { $elem.addClass(placeholderClassName).val(placeholder_attr); } if ($elem.is(":password")) { var $pwd_shiv = $("<input />", { "class": $elem.attr("class") + " " + placeholderClassName, "value": placeholder_attr }); $pwd_shiv.bind("focus.placehold", function () { toggle($elem, $pwd_shiv); $elem.focus(); }); $elem.bind("blur.placehold", function () { if ($elem.val() === "") { toggle($elem, $pwd_shiv); } }); $elem.hide().after($pwd_shiv); } $elem.bind({ "focus.placehold": function () { if ($elem.val() == placeholder_attr) { $elem.removeClass(placeholderClassName).val(""); } }, "blur.placehold": function () { if ($elem.val() === "") { $elem.addClass(placeholderClassName).val(placeholder_attr); } } }); $elem.closest("form").bind("submit.placehold", function () { if ($elem.val() == placeholder_attr) { $elem.val(""); } return true; }); } }); }; $.fn.placehold.is_supported = function () { return "placeholder" in document.createElement("input"); }; })(jQuery); Then make the function work:
$("input, textarea").placehold("something-temporary");
-17249363 0 Knockout checkbox selection filter I am new at knockoutjc library, and can you help me? I have created a new model in javascript like this.

The code is here:
<h2>Category : Throusers</h2> <h3>Sizes</h3> <ul data-bind="foreach: products"> <li> <input type="checkbox" data-bind="value: size.id" /> <label data-bind="text: size.name"></label> </li> </ul> <h3>Colors</h3> <ul data-bind="foreach: products"> <li> <input type="checkbox" data-bind="value: color.id" /> <label data-bind=" text: color.name"></label> </li> </ul> <h3>Products</h3> <ul data-bind="foreach: products"> <li> <label data-bind="text: name"></label> - <label data-bind="text: size.name"></label>- <label data-bind="text: color.name"></label> </li> </ul> <script type="text/javascript"> function Color(id, name) { return { id: ko.observable(id), name: ko.observable(name) }; }; function Size(id, name) { return { id: ko.observable(id), name: ko.observable(name) }; } function Product(id,name, size, color) { return { id: ko.observable(), name: ko.observable(name), size: size, color: color }; }; var CategoryViewModel = { id: ko.observable(1), name: ko.observable("Throusers"), products: ko.observableArray([ new Product(1,"Levi's 501", new Size(1, "30-32"), new Color(1, "Red")), new Product(2,"Colins 308", new Size(2, "32-34"), new Color(2, "Black")), new Product(3,"Levi's 507", new Size(1, "30-32"), new Color(3, "Blue")) ]) }; ko.applyBindings(CategoryViewModel); </script> And now,
If model is wrong?
-40859760 0I have changed the global code and some modification in datatype. This code works:
from __future__ import print_function from __future__ import absolute_import from pycuda.compiler import SourceModule import pycuda.driver as drv import pycuda.autoinit # noqa import numpy as np import time import pandas as pd start_time = time.clock() mod = SourceModule(""" __global__ void similarityGPU(int inputmat[5][70], float similaritymat[5][5]) { int i = threadIdx.x; int j = 0, k=0; for(j=0 ; j<5 ; j++){ float max = 0.0 , min = 0.0; for (k=0 ; k<70 ; k++){ if(inputmat[i][k] > inputmat[j][k]){ max += inputmat[i][k]; min += inputmat[j][k]; } else{ max += inputmat[j][k]; min += inputmat[i][k]; } } similaritymat[i][j] = max/min; } } """) #creating matrix mat = np.zeros(shape=(5,70)) mat[0][0]=6 mat[0][1]=4 mat[0][2]=9 mat[1][0]=35 mat[1][1]=22 mat[1][3]=65 mat[2][1]=9 mat[2][2]=30 mat[0][3]=45 mat[0][6]=85 mat[2][0]=10 mat[4][0]=37 mat[4][2]=2 mat[4][6]=67 mat[4][3]=77 mat[2][3]=12 mat[3][3]=5 mat[3][2]=56 similarity = np.zeros(shape=(5,5)) mat1 = mat.astype(np.int32) similarity1 = similarity.astype(np.float32) print(mat1) similarityGPU = mod.get_function("similarityGPU") similarityGPU( drv.In(mat1), drv.Out(similarity1), block=(5,70,1), grid=(1,1)) print (similarity1) print ("Total GPU Code execution took :",time.clock() - start_time, "seconds.") But, this code does not work for large dataset. I have inputmat[200][15000] and I need to get similaritymat[200][200], I tried blocksize=(200,15000,1) , but the code fails.
Can anyone tell me how to make it work for large matrix? I'm using NVIDIA geForce GTX 960M.
-39010298 0The proper format should be:
composer require "dirkgroenen/Pinterest-API-PHP:0.2.11" Or alternatively, you can add it to your composer.json:
"dirkgroenen/Pinterest-API-PHP" : "0.2.11", Then do a composer install
Have you tried to add a ToList() statement to the where statement?
query = query.Where(x => x.GetType() == typeof(T)).ToList(); As I recall the result of the Where statement is a too generic collection and therefore it needs to be cast first.
Since I see that you're using an AddRange, it could also need to be converted to an array, use the ToArray() statement instead of the ToList() statement if the first doesn't work. I'm not sure if you can provide a List to an AddRange() statement.
-18633311 0I think this would depend on the method you used to do the URL rewriting.
Using IIS - Refer to this previous post on how to extract the full URL: get current url of the page (used URL Rewrite)
Using 404 - This is how I've done it in the past and the only way to access the raw URL is to check the querystring. The 404 URL will look something like this:
https://website.com/rewrite.asp?404;http://website.com/images/gal/boxes-pic004.asp To get the URL, I use something like this:
Function getURL() Dim sTemp sTemp = Request.Querystring ' the next line removes the HTTP status code that IIS sends, in the form "404;" or "403;" or whatever, depending on the captured error sTemp = Right(sTemp, len(sTemp) - 4) ' the next two lines remove both types of server names that IIS includes in the querystring sTemp = replace(sTemp, "http://" & Request.ServerVariables("HTTP_HOST") & ":80/", "") sTemp = replace(sTemp, "http://" & Request.ServerVariables("HTTP_HOST") & "/", "") sTemp = replace(sTemp, "https://" & Request.ServerVariables("HTTP_HOST") & "/", "") sTemp = replace(sTemp, "https://" & Request.ServerVariables("HTTP_HOST") & ":443/", "") ' the next bit of code will force our array to have at least 1 element getURL = sTemp End Function This will get you the full raw URL, you can then extract the part you need by using simple split like:
tmpArr = Split(getURL(),"/") strScriptName = tmpArr(UBound(tmpArr)) The strScriptName variable will then return "boxes-pic004.asp".
Hope this helps.
-7369375 0Highlight your text in visual mode, as in press v and select your text (like viw to select the word your cursor is inside, and type, for example s' to surround it with single quotes. Just don't drop out of visual mode.
-19494215 0 Imageview with frame and imageI am working on android app and I want to create imageview that background is frame and src is image, but always there is space between them Also I want to do that the image will cut in case that his edge bigger then the frame. thanks!
<TableLayout android:id="@+id/layoutItems" android:layout_width="fill_parent" android:layout_height="fill_parent" android:stretchColumns="*" > <TableRow android:id="@+id/row1" android:layout_width="match_parent" android:layout_height="fill_parent" android:orientation="horizontal"> <ImageView android:id="@+id/frame_1_1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="2sp" android:layout_marginTop="2sp" android:layout_marginLeft="13sp" android:layout_marginRight="10sp" android:contentDescription="@string/line" android:background="@drawable/picture_gallery_frame"/> <ImageView android:id="@+id/frame_1_2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="2sp" android:layout_marginTop="2sp" android:layout_marginLeft="10sp" android:layout_marginRight="13sp" android:contentDescription="@string/line" android:background="@drawable/picture_gallery_frame"/> </TableRow> I have more rows like that one and I add src with that code progamatically:
File f = new File(media.get(media.size() - 1).getmMediaPath()); if (f.exists() && f != null) { try { Uri u = Uri.parse(f.getPath()); if (ProfileActivity.tryJpegRead(iv, f)) { //Bitmap bitmap = BitmapUtils.getSafeDecodeBitmap(getPath(u), 512); //iv.setImageBitmap(BitmapUtils.makeRegularScaledBitmap(bitmap, 1.0f, 1.3f)); iv.setImageURI(u); } } catch (Exception e) { iv.setImageResource(R.drawable.sample); } } else { iv.setImageResource(R.drawable.sample); }
-17308163 0 try
percentageDecimals: 0 in your tooltip
-3189001 0Well... Former internet explorer versions had a mistake in their box model: the w3c box model takes width without padding and border, and the IE model took it including them. I have examined the page in a a new IE8 in windows 7, and I've only noticed that the border of the tabs were not rounded and they were not connected to the box. The corner can be done with images.
Sorry.
-37474024 0 Ruby win32ole Gem with OLE error 800A004C (Path Not Found) for size methodI have a colossal directory on my hard-drive and I wanted to gather some stats so I began writing a script. To speed things up massively I used Windows OLE but I've come across an interesting issue where the the ar2 OLE object has a method called size but calling it gives me error 800A004C or "Path Not Found". I have also tested on other directories and the below code works perfectly fine.
I have used the method ole_methods and double checked the casing on size. The OLE method in Ruby definitely exists but no dice on getting it to succeed.
Why is Windows OLE throwing this error when it should know the folder exists and compute the overall size of the folder structure recursively?
require 'win32ole' def getFileCount(dir) size = dir.Files.count sub_folders = dir.SubFolders unless sub_folders == 0 sub_folders.each do |sub| size += getFileCount(sub) end end size end AR2_NAME = ARGV[0] FSO = WIN32OLE.new("Scripting.FileSystemObject") ar2 = FSO.GetFolder(AR2_NAME) ar2_file_count = getFileCount(ar2) puts "Stats for #{ar2.path}.\n\n" puts "Total file count: #{ar2_file_count}." puts "Total size: #{ar2.size}." Run the file using
Ruby C:\sample.rb "C:\my_folder" Here's the error in question:
The folder's size is 1,492,503,618,641 bytes (1.35 TB) according to Windows. It is over 100k files.
I have included my recursive file counting method as this works and illustrates that my folder does indeed exist.
-6674665 0What do you mean by images in hard drive.Are you saying that you have kept your images in your bundle in iphone app.If so then you can make array of those images like this....
NSMutableArray *imageArray; imageArray=[[NSMutableArray alloc]initWithObjects:@"001.jpg",@"002.jpg",@"003.jpg",@"004.jpg",nil]; And then can access your images by this array;
Or if you simply want to show a single image from the bundle you can do this way
UIImageView *creditCardImageView=[[UIImageView alloc]initWithFrame:CGRectMake(10, 16, 302, 77)]; creditCardImageView.image=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"CreditCard_2RowTable" ofType:@"png"]]; [self.view addSubview:creditCardImageView]; This will help you.
-33562625 0Tight loop with high priority thread is not a good idea...when the print hello is just looping without doing anything, Introduce switchtothread/yield after certain loops and sleep zero after a higher loop count. This will give other threads on the system oppurtinity to execute Eventually wait on a event handle when there is no work.
@kiran0x1B
-12389454 0 NSString Somehow turn in to an "__NSArrayI" objecti am receiving response from my server, it looks like this :
2012-09-12 16:29:11.690 WhatIsIt[1763:707] ( { qid = ebb81a9c0c2125c9f12fee33c281dfe2ef5c1596; "qid_data" = { labels = Wristwatch; }; } ) when i am parsing the "qid" value like this :
- (void)updateCompleteWithResults:(NSArray*)results{ NSLog(@"%@",results); NSString *qid = [results valueForKey:@"qid"]; the NSString object is getting a Parentheses around the string (i dont know how) looks like this :
2012-09-12 16:34:17.979 WhatIsIt[1785:707] ( 2e1da5854f3b4f02cd967293cd1364e6d3e0b76a ) so i tried to use :
NSString *string = @" spaces in front and at the end "; NSString *trimmedString = [string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]; and the app crashes, any idea?
-24794987 0In your code, the Unit is registered into angular's module as bdUnit:
angular.module('Modelbuildr').factory('bdUnit', Unit.$factory); Therefore, you should use it like this:
app.controller("MainCtrl", function($scope, bdUnit) { .. }); or explicitly tell angular to alias the bdUnit as Unit:
app.controller("MainCtrl", ['$scope', 'bdUnit', function($scope, Unit) { .. }]);
-12476189 0 How to use colorstatelist in android I want to change button text color on diffrent states like btn_presses,btn_focus,etc.
For that i use colorstatelist.xml and I refrenced it in button text in titlebarlayout.xml. But still I cant able to change text color of button.
Any one know how to do it.Is I am going wrong anywhere in code.
MainActivity.java
public class MainActivity extends Activity implements OnClickListener { EditText emailEdit, passwordEdit; Button loginButton; String email, password; TitleBarLayout titlebarLayout; String r; String rr; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login_activity); emailEdit = (EditText) findViewById(R.id.etEmail); passwordEdit = (EditText) findViewById(R.id.etPassword); loginButton = (Button) findViewById(R.id.loginButton); loginButton.setOnClickListener(this); // titlebarLayout=(TitleBarLayout) findViewById(R.id.titlebar); titlebarLayout = new TitleBarLayout(MainActivity.this); titlebarLayout.setLeftButtonText(""); titlebarLayout.setRightButtonText("Logout"); titlebarLayout.setTitle("iProtect"); //titlebarLayout.setLeftButtonSize(50,50); //titlebarLayout.setRightButtonSize(100,50); titlebarLayout.setLeftButtonBackgroundColor(Color.rgb(34,49,64)); titlebarLayout.setRightButtonBackgroundColor(Color.rgb(34,49,64)); titlebarLayout.setLeftButtonTextColor(Color.rgb(255,255,255)); titlebarLayout.setRightButtonTextColor(Color.rgb(255,255,255)); XmlResourceParser parser =getResources().getXml(R.color.colorstatelist); ColorStateList colorStateList; try { colorStateList = ColorStateList.createFromXml(getResources(), parser); titlebarLayout.setLeftButtonTextColor(colorStateList); } catch (XmlPullParserException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // ColorStateList colorlist=new ColorStateList( new int[][] { new int[] { android.R.attr.state_focused }, new int[0], }, new int[] { Color.rgb(0, 0, 255), Color.BLACK, } ); // titlebarLayout.setLeftButtonTextColor(colorlist); OnClickListener listener = new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (v.getId() == R.id.left_button) { } else if (v.getId() == R.id.right_button) { } } }; titlebarLayout.setLeftButtonOnClickListener(listener); titlebarLayout.setRightButtonOnClickListener(listener); } TitleBarLayout.java
public class TitleBarLayout { private Activity activityRef; private View contentView; private Button leftButton, rightButton; TextView titletext; public TitleBarLayout(Activity a) { Log.i("TitleBar Layout", "Inside constructor"); activityRef = a; inflateViewsFromXml(); setListenersOnViews(); setValuesOnViews(); } private void setValuesOnViews() { leftButton.setText(""); rightButton.setText(""); } private void setListenersOnViews() { leftButton.setOnClickListener(listener); rightButton.setOnClickListener(listener); } private final OnClickListener listener = (new OnClickListener() { @Override public void onClick(View v) { activityRef.finish(); } }); private void inflateViewsFromXml() { contentView = activityRef.findViewById(R.id.titlebar); rightButton = (Button) contentView.findViewById(R.id.right_button); leftButton = (Button) contentView.findViewById(R.id.left_button); titletext = (TextView) contentView.findViewById(R.id.title_textview); } public void setLeftButtonText(int resID) { leftButton.setText(resID); } public void setLeftButtonText(String text) { leftButton.setText(text); } public void setLeftButtonOnClickListener(View.OnClickListener listener) { leftButton.setOnClickListener(listener); } public void setRightButtonText(int resID) { rightButton.setText(resID); } public void setRightButtonText(String text) { rightButton.setText(text); } public void setRightButtonOnClickListener(View.OnClickListener listener) { rightButton.setOnClickListener(listener); } public void setTitle(int resID) { titletext.setText("" + resID); } public void setTitle(String text) { titletext.setText(text); } public void setLeftButtonSize(int width, int height) { Log.i("Button" ,"Width"+width); leftButton.setWidth(width); leftButton.setHeight(height); } public void setRightButtonSize(int width, int height) { Log.i("Button" ,"Width"+width); rightButton.setWidth(width); rightButton.setHeight(height); } public void setLeftButtonBackgroundResource(int backgroundResource) { } public void setRightButtonBackgroundResource(int backgroundResource) { } public void setLeftButtonBackgroundColor(int backgroundColor) { Log.i("Button" ,"COLOR"+backgroundColor); leftButton.setBackgroundColor(backgroundColor); } public void setRightButtonBackgroundColor(int backgroundColor) { Log.i("Button" ,"COLOR"+backgroundColor); rightButton.setBackgroundColor(backgroundColor); } public void setLeftButtonTextColor(int textcolor) { Log.i("Button" ,"COLOR"+textcolor); leftButton.setTextColor(textcolor); } public void setRightButtonTextColor(int textcolor) { Log.i("Button" ,"COLOR"+textcolor); rightButton.setTextColor(textcolor); } public void setLeftButtonTextColor(ColorStateList colorStateList) { leftButton.setTextColor(colorStateList); } public void setRightButtonTextColor(ColorStateList colorStateList) { } } color.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="title_bg_color">#2e4256</color> <color name="layout_bg_color">#dcdcdc</color> <color name="state_pressed">#ffffff</color> <color name="state_selected">#00ff00</color> <color name="state_focused">#0000ff</color> </resources> titlebarlayout.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="@dimen/titlebar_height" android:background="@color/title_bg_color" android:gravity="center_vertical" android:orientation="horizontal" > <Button android:id="@+id/left_button" android:layout_width="@dimen/titlebar_button_width" android:layout_height="@dimen/titlebar_button_height" android:text="" android:clickable="true" android:textColor="@color/colorstatelist" android:background="@drawable/button_shape_drawable" android:layout_marginLeft="10dp"/> <TextView android:id="@+id/title_textview" android:layout_width="0dip" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:text="" android:textColor="@android:color/white" android:textStyle="bold" /> <Button android:id="@+id/right_button" android:layout_width="@dimen/titlebar_button_width" android:layout_height="@dimen/titlebar_button_height" android:text="" android:clickable="true" android:layout_marginRight="10dp" android:background="@drawable/button_shape_drawable" android:textColor="@color/colorstatelist" /> </LinearLayout> colorstatelist.xml
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:color="@color/state_pressed"/> <item android:state_selected="true" android:color="@color/state_selected"/> <item android:state_focused="true" android:color="@color/state_focused"/> <item android:color="#808080"/> </selector>
-19206721 0 xml parse from mysqldump in php I'm trying to parse this xml file to php.
http://www.san-isidro.net/appmovil/partenieve.xml
The problem are that i don't know to parse with this xml format obtained with mysqldump.
Can you help me to parsing <field name="observaciones"> in php?
If you want to take a heap dump programmatically, you'll not find suitable APIs in the java.* or javax.* namespace. However, the Sun runtime comes with the HotSpotDiagnosticMXBean which will enable you to take a heap dump by writing the contents of the heap on to a specified file in disk.
-124598 0If you did want to whitelist for performance reasons, consider using an annotation to indicate which fields to compare. Also, this implementation won't work if your fields don't have good implementations for equals().
P.S. If you go this route for equals(), don't forget to do something similar for hashCode().
P.P.S. I trust you already considered HashCodeBuilder and EqualsBuilder.
-12338370 0 Passing php file in ajaxThis is my code
<script> $(document).ready(function() { // delete the entry once we have confirmed that it should be deleted $('.delete').click(function() { var parent = $(this).closest('tr'); $.ajax({ type: 'POST', url: 'delete.php', data: 'ajax=1&delete=' + $(this).attr('id'), success: function() { parent.fadeOut(300,function() { parent.remove(); }); } }); }); $('.delete').confirm({ }); }); </script> My question is why delete.php is not executing? It's in the same folder, do I need type absolure url to this file? But the best of it is that row in table is deleting, but php file is not executing. And second question is why this code is not working without this line:
$('.delete').confirm({ }); In php file i got this to know is it executed:
<script> alert('aaaa'); </script> Or even I had change it on echo 'something'; but still not working
You're expressing a real-world constraint in code. Your examples here don't actually show that buying you anything here, so going on the evidence I'd wonder whether it's redundant to express it, or irrelevant to any situation that will actually arise. But if you're ever going to have different kinds of shaders for different kinds of vertex datasets, I'd say you've hit on exactly the right way to express this here.
-10606438 0This problem is actually caused by HTML behaving differently then JQuery. In HTML, spaces and extra lines don't matter.
In HTML, these 2 examples are visually the same when rendered to the page:
<div id="vendor">Barracuda</div> and
<div id="vendor"> Barracuda </div> However when you use JQuery's .Text() method, they yield different results.
<div id="vendor">Barracuda</div> $('#vendor').text() // equals "Barracuda" But this is very different:
<div id="vendor"> Barracuda </div> $('#vendor').text() // equals " Barracuda " Thus the need to .trim() the results if you can't tailor the HTML, or just want to play it safe.
var thisText = $.trim($(this).text());
-9732633 0 Language Translation API for iPhone I want to implement language translation feature in my iPhone app, is there any API which is free that I can use, or any other way to do this.
-30847396 0 RawSourceWaveStream volume control and playback time estimation with NaudioI'm using Naudio to play audio samples from memory.
private RawSourceWaveStream waveStream; private MemoryStream ms; private int sampleRate = 48000; private IWavePlayer wavePlayer; //generate sine wave signal short[] buffer = new short[(int)Math.Round(sampleRate * 10.00)]; double amplitude = 0.25 * short.MaxValue; double frequency = 1000; for (int n = 0; n < buffer.Length; n++) { buffer[n] = (short)(amplitude * Math.Sin((2 * Math.PI * n * frequency) / sampleRate)); } byte[] byteBuffer = new byte[buffer.Length * sizeof(short)]; Buffer.BlockCopy(buffer, 0, byteBuffer, 0, byteBuffer.Length); //create audio player to play samples from memory ms = new MemoryStream(byteBuffer); waveStream = new RawSourceWaveStream(ms, new WaveFormat(sampleRate, 16, 1)); //wavePlayer = new WaveOutEvent(); wavePlayer = new DirectSoundOut(); wavePlayer.Init(waveStream); wavePlayer.PlaybackStopped += wavePlayer_PlaybackStopped; I want to control the Volume of RawSourceWaveStream for each stream separately. (I will play multiple streams).
1) It's enough to use wavePlayer.Volume = volumeSlider1.Volume;? It is deprecated.
2) I see that AudioFileReader make use of SampleChannel for Volume control. If i rewrite Read method for RawSourceWaveStream and add Volume Property should this be a good solution?
3) I want playback time estimation as best as possible (at millisecond level). I saw that the time resolution of WaveOutEvent is about hundred of milliseconds. The time resolution of DirectSoundOut is better, but still not enough.
Thank you in advance!
-25394209 0You can't do assignment in an if statement. It looks as though you are trying to do comparison, however, which uses == rather than =.
I want to send some information through JSON object using http protocol.i am getting this error.
UNEXPECTED TOP-LEVEL ERROR: java.lang.OutOfMemoryError: Java heap space at java.util.Arrays.copyOf(Arrays.java:2271) at java.io.ByteArrayOutputStream.toByteArray(ByteArrayOutputStream.java:178) at com.android.dx.cf.direct.ClassPathOpener.processArchive(ClassPathOpener.java:279) at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:166) at com.android.dx.cf.direct.ClassPathOpener.process(ClassPathOpener.java:144) at com.android.dx.command.dexer.Main.processOne(Main.java:672) at com.android.dx.command.dexer.Main.processAllFiles(Main.java:569) at com.android.dx.command.dexer.Main.runMultiDex(Main.java:366) at com.android.dx.command.dexer.Main.run(Main.java:275) at com.android.dx.command.dexer.Main.main(Main.java:245) at com.android.dx.command.Main.main(Main.java:106) FAILED FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:dexDebug'. > com.android.ide.common.internal.LoggedErrorException: Failed to run command: C:\Users\Koli\AppData\Local\Android\sdk\build-tools\23.0.0\dx.bat --dex --no-optimize --multi-dex --main-dex-list D:\Android\MedApp\app\build\intermediates\multi-dex\debug\maindexlist.txt --output D:\Android\MedApp\app\build\intermediates\dex\debug --input-list=D:\Android\MedApp\app\build\intermediates\tmp\dex\debug\inputList.txt Error Code: 3 Output: UNEXPECTED TOP-LEVEL ERROR: java.lang.OutOfMemoryError: Java heap space at java.util.Arrays.copyOf(Arrays.java:2271) at java.io.ByteArrayOutputStream.toByteArray(ByteArrayOutputStream.java:178) at com.android.dx.cf.direct.ClassPathOpener.processArchive(ClassPathOpener.java:279) at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:166) at com.android.dx.cf.direct.ClassPathOpener.process(ClassPathOpener.java:144) at com.android.dx.command.dexer.Main.processOne(Main.java:672) at com.android.dx.command.dexer.Main.processAllFiles(Main.java:569) at com.android.dx.command.dexer.Main.runMultiDex(Main.java:366) at com.android.dx.command.dexer.Main.run(Main.java:275) at com.android.dx.command.dexer.Main.main(Main.java:245) at com.android.dx.command.Main.main(Main.java:106) * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. this is my gradle.app
apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.0" defaultConfig { applicationId "com.knitechs.www.medapp" minSdkVersion 15 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } productFlavors { } packagingOptions { exclude 'META-INF/DEPENDENCIES' exclude 'META-INF/LICENSE' exclude 'META-INF/LICENSE.txt' exclude 'META-INF/license.txt' exclude 'META-INF/NOTICE' exclude 'META-INF/NOTICE.txt' exclude 'META-INF/notice.txt' exclude 'META-INF/ASL2.0' } defaultConfig { multiDexEnabled = true } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:23.1.0' compile 'com.google.android.gms:play-services:+' } This is My Activity
package com.knitechs.www.medapp; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.Spinner; import com.knitechs.www.medapp.Transactors.PatientDetailsSender; import com.knitechs.www.medapp.actors.Patient; import java.util.Calendar; public class PatientDetails extends ActionBarActivity { Button cmdSave; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_patient_details); cmdSave = (Button)findViewById(R.id.cmdSave); cmdSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Patient pt = new Patient(); pt.setRecordCode(((EditText) findViewById(R.id.txtPatientRecordCode)).getText().toString()); pt.setName(((EditText) findViewById(R.id.txtFullName)).getText().toString()); pt.setAddress(((EditText) findViewById(R.id.txtAddress)).getText().toString()); pt.setTelephone(((EditText) findViewById(R.id.txtTelepphoneNumber)).getText().toString()); pt.setGardianName(((EditText) findViewById(R.id.txtGardianName)).getText().toString()); pt.setGardianTelephone(((EditText) findViewById(R.id.txtGardianContactNumber)).getText().toString()); final Spinner sp = (Spinner)findViewById(R.id.spnGender); pt.setGender(sp.getSelectedItem().toString()); final DatePicker dob = (DatePicker) findViewById(R.id.dateDob); Calendar cal = Calendar.getInstance(); cal.set(dob.getYear(),dob.getMonth(),dob.getDayOfMonth()); pt.setBirthdate(cal.getTime()); PatientDetailsSender patientDetailsSender = new PatientDetailsSender(pt,"php/service_classes/PatientDetails.php",getApplicationContext(),"Processing","Details Saved"); patientDetailsSender.execute(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_patient_details, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } this is my PatientDetailsSender class
package com.knitechs.www.medapp.Transactors; import android.content.Context; import com.knitechs.www.medapp.actors.Patient; import com.knitechs.www.medapp.core.JSONSender; import com.knitechs.www.medapp.core.PDialog; import java.util.HashMap; /** * Created by Koli on */ public class PatientDetailsSender extends JSONSender { Patient patient; String url; HashMap<String,String> params; String message; public PatientDetailsSender(Patient patient,String url,Context context,String message,String successmessge){ this.patient=patient; super.setSender_url(url); // set the send URL super.setCurrentActivityContext(context); // set current context this.message = message; // set message for in process super.setpDialog(new PDialog(super.getCurrentActivityContext(),message)); // ser process dialog super.setSuccess_message(successmessge); // set success messge setPatientDataToHashMap(); // set the hash map } public void execute(){ executeQueryCreator(); } private void setPatientDataToHashMap(){ params = new HashMap<>(); params.put("REC_CODE",patient.getRecordCode()); params.put("NAME",patient.getName()); params.put("ADDRESS",patient.getAddress()); params.put("GENDER",patient.getGender()); params.put("GUARDIAN_NAME",patient.getGardianName()); params.put("GUARDIAN_TP",patient.getGardianTelephone()); params.put("B_DATE",patient.getBirthdateString()); params.put("AGE",patient.getAgeString()); params.put("TELEPHONE",patient.getTelephone()); } } This is My JOSNSender class
public class JSONSender { private static String sender_url ; // sender URL private ProgressDialog pDialog; // process dialog for when executing private Context currentActivityContext; // current activity private String success_message; // success message when the dat inserted private HashMap<String,String> parameters; // map for data for json object JSONParser jsonParser = new JSONParser(); // json parser private static final String TAG_SUCCESS = "success"; public static void setSender_url(String sender_url) { JSONSender.sender_url = sender_url; } public void setpDialog(ProgressDialog pDialog) { this.pDialog = pDialog; } public void setParameters(HashMap<String, String> parameters) { this.parameters = parameters; } public void setSuccess_message(String success_message) { this.success_message = success_message; } public void setCurrentActivityContext(Context currentActivityContext) { this.currentActivityContext = currentActivityContext; } public Context getCurrentActivityContext() { return currentActivityContext; } protected void executeQueryCreator(){ new QueryCreator().execute(); } class QueryCreator extends AsyncTask<String, String, String> { /** * Before starting background thread Show Progress Dialog if it is having * */ @Override protected void onPreExecute() { super.onPreExecute(); if(!pDialog.equals(null)){ pDialog.show(); } } /** * Do work in the save to datbse * */ protected String doInBackground(String... args) { JSONObject json = jsonParser.makeHttpRequest(sender_url, "POST", parameters); // create the JSON object in parameters and send data Log.d("Create Response", json.toString()); /** * check for success tag incomming */ try { int success = json.getInt(TAG_SUCCESS); if (success == 1) { Log.d("Data Saved"," OK"); // data saved indatabase if(!success_message.isEmpty()){ Toast.makeText(getCurrentActivityContext(), success_message, Toast.LENGTH_SHORT).show(); } } else { Log.d("Data Failed", " NO"); // Data failed Toast.makeText(getCurrentActivityContext(),"Error",Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { // dismiss the dialog once done if(!pDialog.equals(null)){ pDialog.dismiss(); } } } } This is My JSONParser class
package com.knitechs.www.medapp.core; import android.util.Log; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; /** * Created by Koli on */ public class JSONParser { String charset = "UTF-8"; // character type HttpURLConnection conn; // HTTP connection DataOutputStream wr; // Data output stream for get out data from database StringBuilder result; // reciving data string URL urlObj; // URL object for the connection JSONObject jObj = null; // Json object for create Json parsers StringBuilder sbParams; // string for create parameter url String paramsString; // sending parameter url string private String ipaddress ="http://192.168.8.100/"; //IP address of theserver /** * @param url_path url for the servenr php service class without the ip (folder/pages) * @param method port or get method * @param params json object parmeters * @return JSON object returns with include HTTP URL */ public JSONObject makeHttpRequest(String url_path, String method, HashMap<String, String> params) { sbParams = new StringBuilder(); // create new string for theparameters int i = 0; /** * create the URL parameter string from key set and values * key=value & key=value like that */ for (String key : params.keySet()) { try { if (i != 0) { sbParams.append("&"); } sbParams.append(key).append("=") .append(URLEncoder.encode(params.get(key), charset)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } i++; } /** * create the connection URL */ String url = ipaddress + url_path ; /** * create the connection object byVal method */ if (method.equals("POST")) { /** * request port method */ try { urlObj = new URL(url); // create a URL object conn = (HttpURLConnection) urlObj.openConnection(); // create a HTTP connection object from theURL object conn.setDoOutput(true); // set the method type as Output conn.setRequestMethod("POST"); // Request method as POST conn.setRequestProperty("Accept-Charset", charset); // chrctor acceptance conn.setReadTimeout(10000); // readable timeout for reading conn.setConnectTimeout(15000); // connection time out for connect to server conn.connect(); paramsString = sbParams.toString(); // parameter string wr = new DataOutputStream(conn.getOutputStream()); // write the output stream to the Dtoutput stream wr.writeBytes(paramsString); wr.flush(); wr.close(); } catch (IOException e) { e.printStackTrace(); } } else if (method.equals("GET")) { /** * request get method */ if (sbParams.length() != 0) { url += "?" + sbParams.toString(); // url ? key = val1 & key = val2 } try { urlObj = new URL(url); // create a URL object conn = (HttpURLConnection) urlObj.openConnection(); // create a HTTP connection object from theURL object conn.setDoOutput(false); // set the method type as Output conn.setRequestMethod("GET"); // Request method as GET conn.setRequestProperty("Accept-Charset", charset); // chrctor acceptance conn.setConnectTimeout(15000); // connection time out for connect to server conn.connect(); } catch (IOException e) { e.printStackTrace(); } } /** * response comes from server for request message this is also as a data input stream,same connection c */ try { InputStream in = new BufferedInputStream(conn.getInputStream()); // input strem BufferedReader reader = new BufferedReader(new InputStreamReader(in)); // Buffer reader for the reader od connection statements,inpu string result = new StringBuilder(); // respond message String line; /** * append the lines in to single result string */ while ((line = reader.readLine()) != null) { result.append(line); } Log.d("JSON Parser", "result: " + result.toString()); } catch (IOException e) { e.printStackTrace(); } conn.disconnect(); // disconnect the connection /** * parse the string to a json object */ try { jObj = new JSONObject(result.toString()); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } return jObj; // return json object } } This is My PDialog class
package com.knitechs.www.medapp.core; import android.app.ProgressDialog; import android.content.Context; /** * Created by Koli on */ public class PDialog extends ProgressDialog { public PDialog(Context context) { super(context); } public PDialog(Context context,String message){ super(context); super.setMessage(message); super.setIndeterminate(false); } } I am confused why i get this Error. please Help me.
-39503004 0Apply the min-width property.
In Your CSS Style Sheet
.Textbox { min-width:100%; } In Your *.aspx
<asp:TextBox CssClass="TextboxStyle" placeholder="Enter the Title" runat="server" ID="TextBox1"></asp:TextBox> This will update your text box
-33469525 0I think I found the answer. The bcp format spec doesn't work properly! It seems that even for numeric or datetime import fields, you have to specify "SQLCHAR" as the datatype in the .fmt file. Any attempt to use the actual .fmt file generated by "bcp format" is hopeless -- if it gives you SQLINT or SQLDATE lines back, you have to replace those with SQLCHAR for the thing to work, even if the db columns are in fact numeric or date/datetime types.
What a crock!
-37220168 0My Bots are running well against ReCaptcha.
Here my Solution.
Let your Bot do this Steps:
First write a Human Mouse Move Function to move your Mouse like a B-Spline (Ask me for Source Code). This is the most important Point.
Also use for better results a VPN like https://www.purevpn.com
For every Recpatcha do these Steps:
If you use VPN switch IP first
Clear all Browser Cookies
Clear all Browser Cache
Set one of these Useragents by Random:
a. Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
b. Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0
5 Move your Mouse with the Human Mouse Move Funktion from a RandomPoint into the I am not a Robot Image every time with different 10x10 Randomrange
Then Click ever with random delay between
WM_LBUTTONDOWN
and
WM_LBUTTONUP
Take Screenshot from Image Captcha
Send Screenshot to
or
and let they solve.
After receiving click cooridinates from captcha solver use your Human Mouse move Funktion to move and Click Recaptcha Images
Use your Human Mouse Move Funktion to move and Click to the Recaptcha Verify Button
In 75% all trys Recaptcha will solved
Chears Google
Tom
-5672544 0 How to receive Error code from SOAPClient : JBOSS ESBI am using org.jboss.soa.esb.actions.soap.SOAPClient in my ESB. And i am trying to get the HTTP status code or any exception if SOAPClient fails to send request. Here , there may be plenty of reasons for unsuccesful delivary ex :--404,500 etc.... My requirment is to catch any error or exception (can be soap fault exception) or http status code in ESB so that i do some bussiness logic based on Exception . I tried to use below code but unable to receive any exception.
<action class="com.xxx.esb.yyy.A228ProducerInquiry.ProducerInquiryTransactionHandler" name="RequestMapper" process="mapRequestPath"> <property name="OGNLPath" value="AgentValidation.strXMLIN"/> </action> <action class="org.jboss.soa.esb.actions.soap.SOAPClient" name="FasatPost"> <property name="responseAsOgnlMap" value="true" /> <property name="wsdl" value="http://example.org?wsdl"/> <property name="SOAPAction" value="mySoapAction"/> </action> <action name="response-mapper" class="com.foresters.esb.acord.A228ProducerInquiry.MyResponseAction"> </action> I can see exception in console and SOAP UI but unable to receive in ESB
Thanks, Madhu CM
-22190456 0 "accessorize" method - Ruby, Rack or Sinatra?I've seen the following idiom, and wonder what does accessorize mean and where does it come from - Ruby, Rack or Sinatra?
use Rack::Flash, accessorize: [:error, :success]
-9277156 0 You can do that! Just create some non-queried parameters for the report and set the value of each textbox to:
=Parameters!ParameterName.Value ...where ParameterName is the actual name of the parameter, as you defined for the report.
-34586214 0 Load Earlier Messages in listview like whats appWhen i Click load earlier messages the earlier messages get loaded from database but list view scrolls to the top which is not be done , the message should only loaded at the top of list view without its scroll.
Here is my code for main Activity
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.private_group_chat); Intent i = getIntent(); btnLoadMore = new Button(this); btnLoadMore.setText("Load Earlier Messages"); lsvChat = (ListView) findViewById(R.id.lv_messsages); lsvChat.addHeaderView(btnLoadMore); chatModel = new ArrayList<ChatModel>(); db = new Database3(getApplicationContext()); chatModel = db.getSelectedIncidentDetails(getApplicationContext(), groupId, count); chatAdapter = new ChatAdapterGroup(getApplicationContext(), chatModel); lsvChat.setAdapter(chatAdapter); discoverModel = new ArrayList<DiscoverModel>(); dm = new DiscoverModel(); } here is my base adapter......
public class ChatAdapterGroup extends BaseAdapter { private Context context; private LayoutInflater inflater; int count = 0; private ArrayList<ChatModel> list; public ChatAdapterGroup(Context context, ArrayList<ChatModel> list) { this.context = context; this.list = list; inflater = (LayoutInflater) context .getSystemService(context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } private class ViewHolder { TextView txt_left; TextView txt_right; TextView tv_fromName; RelativeLayout rl_left; RelativeLayout rl_right; } @Override public View getView(final int position, View v, ViewGroup arg2) { final ViewHolder holder; if (v == null) { holder = new ViewHolder(); v = inflater.inflate(R.layout.chat_adapter, null); holder.txt_left = (TextView) v.findViewById(R.id.txt_left); holder.txt_right = (TextView) v.findViewById(R.id.txt_right); holder.tv_fromName = (TextView) v.findViewById(R.id.tv_fromName); holder.rl_left = (RelativeLayout) v.findViewById(R.id.rl_left); holder.rl_right = (RelativeLayout) v.findViewById(R.id.rl_right); v.setTag(holder); } else { holder = (ViewHolder) v.getTag(); } if (list.get(position) != null) { if (list.get(position).getGroup_cordinate() .equalsIgnoreCase("left")) { holder.txt_left.setText("" + list.get(position).getGroup_messages_recive()); holder.tv_fromName.setText("" + list.get(position).getFrom_name_recive()); holder.txt_left.setTextColor(Color.parseColor("#000000")); holder.rl_right.setVisibility(View.GONE); holder.rl_left.setVisibility(View.VISIBLE); } else { holder.txt_right.setText("" + list.get(position).getGroup_messages_recive()); holder.rl_left.setVisibility(View.GONE); holder.rl_right.setVisibility(View.VISIBLE); } } v.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub // notifyDataSetChanged(); } }); return v; } } and the xml coding for List view .............
<ListView android:id="@+id/lv_messsages" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_above="@+id/ll_send" android:layout_below="@+id/rl_header" android:divider="@null" android:stackFromBottom="true" android:transcriptMode="alwaysScroll" />
-16356100 0 Go check these styles:
.nivo-controlNav a h1 { color: #E4007B; font: bold 15px/20px Arial; text-transform: none; } and add these after:
.nivo-controlNav a.active h1 { color: #000; } This should work.
-27447359 0looks like unicode
http://www.charbase.com/0304-unicode-combining-macron
U+0304: COMBINING MACRON
-26511016 0 relative width and height in storyboard?I've been developing an ios app and the layout is driving me absolutely mad. So i have a CollectionViewCell, in this collectionviewcell i have 2 UIViews. What i want to know is how can i set width and height of my views relative to their parent container.
I've already attempted this
NSLayoutConstraint *c = [NSLayoutConstraint constraintWithItem:bottomView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:topView multiplier:1.5 constant:0]; from the other stack post but it does nothing.
Ive tried to set the height of one of the containers programaticaly but that also doesnt work. Here is the code that sets the layout of the collectionviewCell which is the super view and works.
CGFloat screenWidth = screenRect.size.width; CGFloat screenHeight = screenRect.size.height; CGFloat marginWidth = 10.f; CGFloat itemWidth = (screenWidth / 2.0f) - (1.5f * marginWidth); [self layout].itemSize = CGSizeMake(itemWidth, itemWidth * 1.3f); Ive tried to set the height of the view relative to the collectionviewcell with the code below
CGFloat height = (((itemWidth * 1.3f)/3)*2); CGRect imageFrame = self.imagePanel.frame; imageFrame.size.width = (screenWidth / 2.0f); imageFrame.size.height = height; [self.imagePanel setFrame:imageFrame]; But again this doesnt work :( How can i achieve this? Is there any way to do this through the storyboard?
-22709424 0Try to use:
jQuery(document).ready(function(){ var target = jQuery('.product-image'); target.mouseenter(function(){ jQuery(this).find('.popUpPrice button').show(); }); }); Also target is already a jQuery object. You can just use target.mouseenter instead of jQuery(target).mouseenter
My working build.graddle:
apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "19.1.0" defaultConfig { applicationId "com.squiri.squiri" minSdkVersion 15 targetSdkVersion 23 versionCode 1 versionName "1.0" //multiDexEnabled = true } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } packagingOptions { exclude 'META-INF/DEPENDENCIES.txt' exclude 'META-INF/LICENSE.txt' exclude 'META-INF/NOTICE.txt' exclude 'META-INF/NOTICE' exclude 'META-INF/LICENSE' exclude 'META-INF/DEPENDENCIES' exclude 'META-INF/notice.txt' exclude 'META-INF/license.txt' exclude 'META-INF/dependencies.txt' exclude 'META-INF/LGPL2.1' } } dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') compile 'com.google.android.gms:play-services:7.8.0' compile 'com.android.support:support-v4:23.0.0' compile 'com.android.support:appcompat-v7:23.0.0' compile 'com.vk:androidsdk:+' compile 'com.facebook.android:facebook-android-sdk:4.0.0' } If I add to this file next lines:
repositories { mavenCentral() maven { url 'http://maven.stickerpipe.com/artifactory/stickerfactory' } } ... dependenies{ ... compile('vc908.stickers:stickerfactory:+') { transitive = true; } } I getting next error:
Information:Gradle tasks [:app:assembleDebug] :app:preBuild UP-TO-DATE :app:preDebugBuild UP-TO-DATE :app:checkDebugManifest :app:preReleaseBuild UP-TO-DATE :app:prepareComAndroidSupportAppcompatV72300Library UP-TO-DATE :app:prepareComAndroidSupportDesign2221Library UP-TO-DATE :app:prepareComAndroidSupportMediarouterV72220Library UP-TO-DATE :app:prepareComAndroidSupportRecyclerviewV72221Library UP-TO-DATE :app:prepareComAndroidSupportSupportV42300Library UP-TO-DATE :app:prepareComAnjlabAndroidIabV3Library1026Library UP-TO-DATE :app:prepareComFacebookAndroidFacebookAndroidSdk400Library UP-TO-DATE :app:prepareComGithubCastorflexSmoothprogressbarLibrary110Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServices780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesAds780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesAnalytics780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesAppindexing780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesAppinvite780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesAppstate780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesBase780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesCast780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesDrive780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesFitness780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesGames780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesGcm780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesIdentity780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesLocation780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesMaps780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesNearby780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesPanorama780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesPlus780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesSafetynet780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesVision780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesWallet780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesWearable780Library UP-TO-DATE :app:prepareComVkAndroidsdk1510Library UP-TO-DATE :app:prepareVc908StickersStickerfactory053Library UP-TO-DATE :app:prepareDebugDependencies :app:compileDebugAidl UP-TO-DATE :app:compileDebugRenderscript UP-TO-DATE :app:generateDebugBuildConfig UP-TO-DATE :app:generateDebugAssets UP-TO-DATE :app:mergeDebugAssets UP-TO-DATE :app:generateDebugResValues UP-TO-DATE :app:generateDebugResources UP-TO-DATE :app:mergeDebugResources UP-TO-DATE :app:processDebugManifest UP-TO-DATE :app:processDebugResources UP-TO-DATE :app:generateDebugSources UP-TO-DATE :app:processDebugJavaRes UP-TO-DATE :app:compileDebugJavaWithJavac UP-TO-DATE :app:compileDebugNdk UP-TO-DATE :app:compileDebugSources UP-TO-DATE :app:preDexDebug UP-TO-DATE :app:dexDebug UNEXPECTED TOP-LEVEL EXCEPTION: java.lang.IllegalArgumentException: method ID not in [0, 0xffff]: 65536 at com.android.dx.merge.DexMerger$6.updateIndex(DexMerger.java:501) at com.android.dx.merge.DexMerger$IdMerger.mergeSorted(DexMerger.java:276) at com.android.dx.merge.DexMerger.mergeMethodIds(DexMerger.java:490) at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:167) at com.android.dx.merge.DexMerger.merge(DexMerger.java:188) at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:439) at com.android.dx.command.dexer.Main.runMonoDex(Main.java:287) at com.android.dx.command.dexer.Main.run(Main.java:230) at com.android.dx.command.dexer.Main.main(Main.java:199) at com.android.dx.command.Main.main(Main.java:103) Error:Execution failed for task ':app:dexDebug'. > com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0\bin\java.exe'' finished with non-zero exit value 2 Information:BUILD FAILED Information:Total time: 33.864 secs Information:1 error Information:0 warnings Information:See complete output in console Why??? Notation: in other project (quickblox sample chat) on my PC working all OK!
My not working build.gradle:
apply plugin: 'com.android.application' repositories { mavenCentral() maven { url 'http://maven.stickerpipe.com/artifactory/stickerfactory' } } android { compileSdkVersion 23 buildToolsVersion "19.1.0" defaultConfig { applicationId "com.squiri.squiri" minSdkVersion 15 targetSdkVersion 23 versionCode 1 versionName "1.0" //multiDexEnabled = true } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } packagingOptions { exclude 'META-INF/DEPENDENCIES.txt' exclude 'META-INF/LICENSE.txt' exclude 'META-INF/NOTICE.txt' exclude 'META-INF/NOTICE' exclude 'META-INF/LICENSE' exclude 'META-INF/DEPENDENCIES' exclude 'META-INF/notice.txt' exclude 'META-INF/license.txt' exclude 'META-INF/dependencies.txt' exclude 'META-INF/LGPL2.1' } } dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') compile 'com.google.android.gms:play-services:7.8.0' compile 'com.android.support:support-v4:23.0.0' compile 'com.android.support:appcompat-v7:23.0.0' compile 'com.vk:androidsdk:+' compile 'com.facebook.android:facebook-android-sdk:4.0.0' compile('vc908.stickers:stickerfactory:+') { transitive = true; } } Working build.gradle in quickblox sample chat:
apply plugin: 'com.android.application' repositories { mavenCentral() maven { url 'http://maven.stickerpipe.com/artifactory/stickerfactory' } } android { compileSdkVersion rootProject.compileSdkVersion buildToolsVersion rootProject.buildToolsVersion sourceSets { main { manifest.srcFile 'AndroidManifest.xml' java.srcDirs = ['src'] res.srcDirs = ['res'] } } } dependencies { compile files(rootProject.core_jar_path, rootProject.chat_jar_path, rootProject.messages_jar_path) compile 'com.google.android.gms:play-services-gcm:7.5.0' compile 'com.android.support:support-v4:19.0.+' compile 'com.android.support:appcompat-v7:19.0.0' compile project(':pull-to-refresh') compile('vc908.stickers:stickerfactory:0.2.2@aar') { transitive = true; } } What I have tried:
clear, rebuild, recreate project
change compile version of java to 1.7
enable multiDexEnabled with big memory size allocation for multidex configuration
delete appcompat and support dependencies
changed version of stickerfactory to latest (":+")
Nothing works.
The analogic problem is with quickblox jar libraries also! (all jar libs are taken from quickblox chat sample (jars directory))
-40665833 0 Siddhi logical pattern AND only works for a pair of eventsI have been doing some tests using WSO2 Siddhi language and I came across something that I did no fully understand. It seems like a bug/limitation but I would like to hear your opinion/recommendations.
Creating a chain of events using logical pattern. I tried to create a chain of 3 events connected by AND operator. Below is a very simple query I created:
from ea=event_a[ea.status == 1] and eb=event_b[eb.status == 2] and ec=event_c[ec.status == 3] select 'And_Test' as ID insert into outputStream; When I try to test it using Siddhi Try it, it shows the following error message:
You have an error in your SiddhiQL at line 10:1, extraneous input 'and' expecting {'[', '->', '#', SELECT, INSERT, DELETE, UPDATE, RETURN, OUTPUT, WITHIN}
However, if I remove the third event from my query, it works fine. Below is the query that works fine:
from ea=event_a[ea.status == 1] and eb=event_b[eb.status == 2] select 'And_Test' as ID insert into outputStream; It seems that I can only use AND for a pair of events. As I mentioned before, it seems like a bug/limitation. I tested it on both WSO2 CEP 4.1.0 and WSO2 CEP 4.2.0.
-2949221 0 How to find unmapped properties in a NHibernate mapped class?I just had a NHibernate related problem where I forgot to map one property of a class.
A very simplified example:
public class MyClass { public virtual int ID { get; set; } public virtual string SomeText { get; set; } public virtual int SomeNumber { get; set; } } ...and the mapping file:
<?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="MyAssembly" namespace="MyAssembly.MyNamespace"> <class name="MyClass" table="SomeTable"> <property name="ID" /> <property name="SomeText" /> </class> </hibernate-mapping> In this simple example, you can see the problem at once:
there is a property named "SomeNumber" in the class, but not in the mapping file.
So NHibernate will not map it and it will always be zero.
The real class had a lot more properties, so the problem was not as easy to see and it took me quite some time to figure out why SomeNumber always returned zero even though I was 100% sure that the value in the database was != zero.
So, here is my question:
Is there some simple way to find this out via NHibernate?
Like a compiler warning when a class is mapped, but some of its properties are not.
Or some query that I can run that shows me unmapped properties in mapped classes...you get the idea.
(Plus, it would be nice if I could exclude some legacy columns that I really don't want mapped.)
EDIT:
Okay, I looked at everything you proposed and decided to go with the meta-data API...that looks the easiest to understand for me.
Now that I know what to search for, I found some examples which helped me to get started.
So far, I have this:
Type type = typeof(MyClass); IClassMetadata meta = MySessionFactory.GetClassMetadata(type); PropertyInfo[] infos = type.GetProperties(); foreach (PropertyInfo info in infos) { if (meta.PropertyNames.Contains(info.Name)) { Console.WriteLine("{0} is mapped!", info.Name); } else { Console.WriteLine("{0} is not mapped!", info.Name); } } It nearly works, except one thing: IClassMetadata.PropertyNames returns the names of all the properties except the ID.
To get the ID, I have to use IClassMetadata.IdentifierPropertyName.
Yes, I could save .PropertyNames in a new array, add .IdentifierPropertyName to it and search that array.
But this looks strange to me.
Is there no better way to get all mapped properties including the ID?
I'm trying to create reusable subclass of UINavigationController. So here's my code :
@interface MainNavigationController : UINavigationController ... - (void)viewDidLoad { [super viewDidLoad]; self.navigationBar.barTintColor = primaryOrange; self.navigationBar.tintColor = white; self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"search"] style:UIBarButtonItemStylePlain target:self action:nil]; self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"menu"] style:UIBarButtonItemStylePlain target:self action:nil]; } So the problem that the color of navigation bar is changing but the buttons they doesn't appears.
What's I've missed here ?
Update I want to have the same NavigationController (button and color ...) for the NavigationController in my image :
Update So I've subclasse my navugationController unn this way :
-(void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{ viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"search"] style:UIBarButtonItemStylePlain target:self action:nil]; viewController.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"menu"] style:UIBarButtonItemStylePlain target:self action:@selector(showMainMenu)]; } - (id)initWithRootViewController:(UIViewController *)rootViewController { self = [super initWithRootViewController:rootViewController]; if (self) { rootViewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"search"] style:UIBarButtonItemStylePlain target:self action:nil]; rootViewController.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"menu"] style:UIBarButtonItemStylePlain target:self action:@selector(showMainMenu)]; } return self; } This work's but the only problem is that when I push a view instead of having back button on left I get Always the search icon, how to fix it (I want to have search button for parent on left , and back button for child view ) ?
-16481613 0 BootBox JS for Twitter Bootstrap - how to pass data into the callback function?JS/JQuery newbie here. I'm using BootBox for Twitter Bootstrap, and I'm trying to pass the value of the id attribute of an a element into the callback function:
<a class="confirmdel" id="<?= $folioid ?>" href="#"> Delete</a> <script> $(document).on("click", ".confirmdel", function(e) { var folioid = ($(this).attr('id')); bootbox.dialog("Do you really want to delete this folio entry?", [{ "label" : "Yes", "class" : "btn-danger", "icon" : "icon-trash", "callback": function() { window.location.replace("deletefolio.php?folioid="+$folioid); } }, { "label" : "No", "class" : "btn", }]); }); </script> It seems i can't use $(this) inside the callback function because in there it doesn't refer to the a element but to the window instead, and I have no idea how to pass the variable into the callback from outside.
Maybe I'm thinking about it the wrong way entirely.
Any suggestions greatly appreciated!
-40883207 0Use super() as the first line inside your constructor for the reason as shared in an SO-answer here - why-does-this-and-super-have-to-be-the-first-statement-in-a-constructor and you can change your existing code as -
public Car(String name, int modelNo, int seatCap) { super(name, modelNo); this.seatCap = seatCap; }
-33021221 0 How can I use SVG titles as tooltips? Could you help me with my question. My .svg file is a map with countries. All of the countries have a title. How can I display title as tooltip when I hover it? Look here please: http://bit.ly/1N1RVTn
-7404685 0 Packaging JVM with Application While Maintaining an Automated and Repeatable Build ProcessI'm currently working on a project that requires us to package a JRE with our application. I'm normally against this as it makes keeping the JRE patched quite difficult, but in this case it is necessary.
What are the best practices for packaging a JRE with an application as part of an automated build process?
Where do you normally store the JRE files so that they can be picked up by your build process? Shared file server? What about making it an artifact in your maven repo?
Just trying to get a feel for what people do in this situation.
-9960919 0 flowplayer 200 stream not found on firefoxHello I'd like to use flowplayer on a website but I experienced that it is not relieable with my configurations yet.
Using firefox I sometimes got the error 200 stream not found. It seemed as if the url of the clip has not been passed to the player.
using seamonkey the video was played with the configuration in the example bellow all the time propperly.
using epiphany i only get a black screen which might depend on my css.
but now the real problem and question: why do I get the 200 stream not found problem on firefox and how to get rid of it 100% do you have it too?
here is a demo page: http://lehrer-beraten-eltern.de/debug
-134137 0Personally I would always run some form of sanitation on the data first as you can never trust user input, however when using placeholders / parameter binding the inputted data is sent to the server separately to the sql statement and then binded together. The key here is that this binds the provided data to a specific type and a specific use and eliminates any opportunity to change the logic of the SQL statement.
-18793992 0This is valid Python syntax when it is located in a module, but in the interactive interpreter you need to separate blocks of code with a blank line.
The handy rule of thumb here is that you can't start a new block with if, def, class, for, while, with, or try unless you have the >>> prompt.
i have 2 Date (start_date, end_date) with yyyy-MM-dd format and i want to check that if the month between in december 01 - march 31 then do something. For example my start_date is 2015-12-01 or 2016-02-01 and end_date 2016-02-12 then write something. I have this
public void meethod(){ DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Date startDate = null; Date endDate = null; try { startDate = df.parse(tf_start_date.getText()); endDate = df.parse(tf_end_date.getText()); } catch (ParseException e) { e.printStackTrace(); } if( /* what goes here? */ ) { System.out.println("its between december-march"); } else { } } tf_start_date and tf_end_date is a TextField and the value of TextFields like 2015-02-03
Cookies are managed by the browser. You have no direct access to the underlying file. It may not even saved in a file.
-23842990 0 APEX: How to link application log-in credentials to a table in back-end databaseI have made a database and now I am trying to make a front-end application using oracle apex 4(default with oracle-xe 11g). I have included the following table for user credentials in my database.
Manager(managerid{PK},name,username,password) I know I can create many end-user accounts from the apex for an application. But, users of application will be managers only and I have a table for them in database so it would be illogical to create separate accounts and information when I have them already in database.
My question is, how can I link the authorization of front-end application with the above table?
Regards
-30589535 0This may help you
[akshay@localhost tmp]$ cat test.php <?php $array= array( (object)array("exercise_name" => "Hang Clean","category_name" => "Heavy,Pull,Core"), (object)array("exercise_name" => "Ice Skaters","category_name" => "Ground,Lower,Plyometrics"), (object)array("exercise_name" => "Ice Skaters","category_name" => "Basketball,Sport Specific") ); function simple_merge($array) { foreach($array as $k) { if(isset($output[$k->exercise_name])) { array_push($output[$k->exercise_name]->multiple_category_name,$k->category_name); }else { $k->multiple_category_name = array($k->category_name); unset($k->category_name); $output[$k->exercise_name] = $k; } } return array_values($output); } // Input print_r($array); // Output print_r(simple_merge($array)); ?> Output
[akshay@localhost tmp]$ php test.php Array ( [0] => stdClass Object ( [exercise_name] => Hang Clean [category_name] => Heavy,Pull,Core ) [1] => stdClass Object ( [exercise_name] => Ice Skaters [category_name] => Ground,Lower,Plyometrics ) [2] => stdClass Object ( [exercise_name] => Ice Skaters [category_name] => Basketball,Sport Specific ) ) Array ( [0] => stdClass Object ( [exercise_name] => Hang Clean [multiple_category_name] => Array ( [0] => Heavy,Pull,Core ) ) [1] => stdClass Object ( [exercise_name] => Ice Skaters [multiple_category_name] => Array ( [0] => Ground,Lower,Plyometrics [1] => Basketball,Sport Specific ) ) )
-3902816 0 I think it's unlikely that this is possible using only client-side Flash. In theory maybe it would be possible to simulate playback speed of video by doing manual seeking, but that wouldn't provide for audio. Using Flash 10+, it is now possible to manipulate audio data manually, though that doesn't mean it's possible to manipulate in context of a audio/video stream . (Example: http://www.kelvinluck.com/2008/11/first-steps-with-flash-10-audio-programming/)
If the Google Video player you provided a screen shot of was Flash based, then I think it's very likely they were using a media server to handle playback speed changes. (Just FYI, google at one time had multiple video players available, and not all were Flash based.) Recent versions of Flash Media Server supposedly also support playback speed adjustment. (I couldn't find anything authoritative though, and I don't know if handling of audio is included.)
One other thought, just FWIW, HTML5 video includes support for speed adjustment the playbackRate property. Perhaps that will eventually be an option for you.
-30561343 0I had this same issue. Turns out I needed to traverse the subview tree like so:
var subView = alertController.view.subviews.first as! UIView var contentView = subView.subviews.first as! UIView contentView.backgroundColor = UIColor(red: 233.0/255.0, green: 133.0/255.0, blue: 49.0/255.0, alpha: 1.0)
-20900256 0 Can give currency pattern in yaxis tickLabel in jqplot? Here is my script
<script type="text/javascript"> function my_ext() { this.cfg.axes.yaxis.tickOptions = { formatString : '' }; } </script> I want to format the numbers on my axis like this: 100,000,000.00. How do I do this in jqplot?
I have an Android project composed of a Java layer for the UI, and a C++ layer for the core of the application that contains most of the code.
These two layers are two separate Visual Studio 2015 projects/solutions, the "UI" project being a "Basic Application (Android, Gradle)" project, and the "Core" project being a "Dynamic Shared Library (Android)" generating a .so which is loaded by the Java on startup.
I would like my "UI" project to reference the "Core" project without making the C++ code accessible when openning the "UI" project.
What I have thought so far :
Adding a reference to the "Core" project in the "UI" project, which seems to be the clean way to do this, but which also makes the C++ code accessible, which I don't want to be possible.
Not creating a reference to the "Core" project in the "UI" project but simply "referencing" the .so generated by the "Core" project into the "UI" project. However I don't know how to do that. And because there will not be an actual reference to the "Core" project, compiling the "UI" project will not automatically recompile the "Core" project if a modification was made to it, forcing me to do it manually.
Is there a clean way to do what I want to do ? Thank you.
-8600145 0Trying to do something similar to allow WS calls to an embedded Jetty REST API...here's my echo test code (Jetty 7), HTH
public class myApiSocketServlet extends WebSocketServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException ,IOException { OutputStream responseBody = response.getOutputStream(); responseBody.write("Socket API".getBytes()); responseBody.close(); } public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) { return new APIWebSocket(); } class APIWebSocket implements WebSocket, WebSocket.OnTextMessage { Connection connection; @Override public void onClose(int arg0, String arg1) { } @Override public void onOpen(Connection c) { connection = c; } @Override public void onMessage(String msg) { try { this.connection.sendMessage("I received: " + msg); } catch (Exception e) { e.printStackTrace(); } } } }
-40727166 0 Thank you so much! You guys are life saver! This is the code that I eventually come up with it. I think it is the combination of all answers!
import json table = [] with open('simple.json', 'r') as f: for line in f: try: j = line.split('|')[-1] table.append(json.loads(j)) except ValueError: # You probably have bad JSON continue for row in table: print(row)
-32829727 0 String supports only + and +=. All other arithmetic and compound statements are invalid at compile time itself.
From String docs
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings.
That doesn't mean it support all other operations.
To substract or to make parts of string, there are other methods like substring, split etc.
Here are some examples to substring, from docs
String c = "abc".substring(2,3);
-34915524 0 Thread 1:EXC_BAD_INSTRUCTION error when calling "addObjectsFromArray"method for NSMutableArray I have created a program where it calculates the borders of certain countries based on a Custom Object being inputed into a function. This function returns an array of custom objects. I keep getting this error when trying to add this array to a NSMutableArray. The error is called "Thread 1: EXC_BAD_INSTRUCTION(code=EXC_1386_INVOP, subcode=0x0)".
Here is my adding code:
@IBOutlet var Label: UILabel! @IBOutlet var imageView: UIImageView! override func viewDidLoad() { //Afganistan Afghanistan.name = "Afghanistan" Afghanistan.borders.addObjectsFromArray(relate(Afghanistan)) Label.text = String((Afghanistan.borders[0] as! develop).name) } Here is the relate method along with the group dictionary:
func relate(X : develop) -> Array<develop>{ var A : [develop] = [] for (_, value) in groups { for y in value { if y.name == X.name { for i in value { if i.name != X.name { A.append(i) } } } } } return A } //Groups var groups = [ "one": [Afghanistan] ] Here is the class of develop:
class develop : NSObject, NSCoding { //Shared var power : Int! var name : String! var image : UIImage! var flag : UIImage! var militaryName : String! //Military var experience : Int! var OATC : Int! var navy : Int! var airforce : Int! var artillery : Int! //Geography var borders : NSMutableArray! var cities : NSMutableArray! //Biomes var biom : NSMutableArray! var continent : String! var NSEW : String! //Encoding Section required convenience init(coder decoder: NSCoder) { self.init() //shared self.power = decoder.decodeObjectForKey("power") as! Int self.name = decoder.decodeObjectForKey("name") as! String self.image = decoder.decodeObjectForKey("image") as! UIImage self.flag = decoder.decodeObjectForKey("flag") as! UIImage self.militaryName = decoder.decodeObjectForKey("militaryName") as! String //Military self.experience = decoder.decodeObjectForKey("experience") as! Int self.OATC = decoder.decodeObjectForKey("OATC") as! Int self.navy = decoder.decodeObjectForKey("navy") as! Int self.airforce = decoder.decodeObjectForKey("airforce") as! Int self.artillery = decoder.decodeObjectForKey("artillery") as! Int //Geography self.borders = decoder.decodeObjectForKey("borders") as! NSMutableArray self.cities = decoder.decodeObjectForKey("cities") as! NSMutableArray self.continent = decoder.decodeObjectForKey("continent") as! String self.NSEW = decoder.decodeObjectForKey("NSEW") as! String } convenience init( power: Int, name: String, image: UIImage, flag: UIImage, relations: NSMutableArray, mName: String, experience: Int, OATC: Int, navy: Int, airforce: Int, artillery: Int, borders: NSMutableArray, cities: NSMutableArray, biom: NSMutableArray, continent: String, NSEW: String ) { self.init() //shared self.power = power self.name = name self.image = image self.flag = flag self.militaryName = mName //military self.experience = experience self.OATC = OATC self.navy = navy self.airforce = airforce self.artillery = artillery //geography self.borders = borders self.cities = cities self.biom = biom self.continent = continent self.NSEW = NSEW } func encodeWithCoder(coder: NSCoder) { //Shared if let power = power { coder.encodeObject(power, forKey: "power") } if let name = name { coder.encodeObject(name, forKey: "name") } if let image = image { coder.encodeObject(image, forKey: "image") } if let flag = flag { coder.encodeObject(flag, forKey: "flag") } if let militaryName = militaryName { coder.encodeObject(militaryName, forKey: "militaryName") } //Military if let experience = experience { coder.encodeObject(experience, forKey: "experience") } if let OATC = OATC { coder.encodeObject(OATC, forKey: "OATC") } if let navy = navy { coder.encodeObject(navy, forKey: "navy") } if let airforce = airforce { coder.encodeObject(airforce, forKey: "airforce") } if let artillery = artillery { coder.encodeObject(artillery, forKey: "artillery") } //geography if let borders = borders { coder.encodeObject(borders, forKey: "borders") } if let cities = cities { coder.encodeObject(cities, forKey: "cities") } if let biom = biom { coder.encodeObject(biom, forKey: "biom") } if let continent = continent { coder.encodeObject(continent, forKey: "continent") } if let NSEW = NSEW { coder.encodeObject(NSEW, forKey: "NSEW") } } } "Afghanistan" is a subclass of develop
-28674171 0 Having problems splitting a long string with preg_match_allI have a variable (text) and it is updated with sentences every time there is an update. When i display this array it turns into 1 long sentence, and i want to break this up in single sentences for readability.
<?php $pattern = '~\\d+-\\d+-\\d{4} // \\w+: ~ '; $subject = '01-02-2015 // john: info text goes here 10-12-2015 // peter: some more info '; $matches = array(); $result = preg_match_all ($pattern, $subject, $matches); ?> Which gives this output:
$matches: array ( 0 => array ( 0 => '01-02-2015 // john: ', 1 => '10-12-2015 // peter: ', ), ) I'd like the output to be:
$matches: array ( 0 => array ( 0 => '01-02-2015 // john: info text goes here', 1 => '10-12-2015 // peter: some more info', ), ) I need the output to be like this so i can use a foreach loop to print each sentence.
ps. I'd like to try to get it to work this way first, because otherwise i'd need to change a lot of entries in the database.
pps. I'm also not a hero with regex as you can see, so i hope someone can help me out!
-701355 0Here's how
int i = Math.Abs(386792); while(i >= 10) i /= 10; and i will contain what you need
While this will work, it's probably best (from a readability and performance standpoint) to use a dedicated event library. If you don't want to do that, this is a neater way to do it.
jQuery allows creation of documentFragments, which just live in memory as an object. It isn't added to your page, and events can only be triggered on it by using the returned value (here stored in window.events).
window.events = $('<div>'); events.on('changeSettings',function(e,param1){ // do something }); events.trigger('changeSettings', ['value']); Here's an example using radio.js, which does events and nothing else.
radio('changeSettings').subscribe(function(data1, data2) { //do something with data1 and data2 }); radio('changeSettings').broadcast(data1, data2); You could also do something like this, which allows refactoring and minification.
var events = {changeSettings: radio('changeSettings')}; events.changeSettings.subscribe(function(data1, data2) { //do something with data1 and data2 }); events.changeSettings.broadcast(data1, data2);
-21810145 0 Paypal checkout opens on a separate tab - how to change this? I have found that the Paypal generated buttons is a very good solution for my wife's website. However, whenever someone presses on the "add to cart" button, he/she is taken to a separate Internet Explorer tab. That's fine. However, if they chose to "continue shopping", IE tries to close the Paypal tab and asks the user's permission to do so. This is not really ideal from the user experience point of view.
Can I force the Paypal Checkout to open in the same IE tab as the main website?
Thank you.
-10937478 0As you .inline append to DOM dynamically, so ordinary binding will not work here. You need delegate event handler to perform like following:
$('#selectResult').on('hover', '.inline', function(e) { if(e.type == "mouseenter") { alert('In'); } else { alert('Out'); } }); .on() method for delegate event handler need to use as following:
$(container).on(eventName, target, handlerFunction); Here, container points to the element that is Static-element i.e. belongs to DOM at page load, not append dynamically. Try to avoid document or body as container reference.
You can try to use indexes, its very optimize queries time.
try this link:
-21452934 0 What is the easiest way to push a very messy local git repo to a remote git repo, chunk by chunk?I have forked and then cloned a git repo that my research group is working on a while ago. I was (and still am) new to git, but I happily created a few branches, occasionally merging them with the changes from the remote source. I have also pushed my changes every now and again to my remote forked version of the repo, but I never pushed much to the original repo, because my work was undone and nobody demanded it.
Here is the situation: I have a whole load of changes committed and pushed to my remote repo. Almost none of it made it to the original remote repo that the rest of the group is working on. Just doing one big diff is out of the question, because there is still way too much scruffy unfinished work that nobody besides me might need. How do I start pushing selected changes (as in, selected manually, by hand) to the remote repo, chunk by chunk?
I am not fluent in git, and I wonder if I have to make a clean clone and start from there. Is there a smarter way of approaching my situation?
Thank you.
-8970478 0Mediawiki which is used for Wikipedia, does support private wikis provided you configure it properly. Please check the following links to get an idea about it- http://www.mediawiki.org/wiki/Manual:Preventing_access http://mythopoeic.org/mediawiki-private/ N.B: I haven't tried it, but it should work.
-760353 0A swift google came up with this example which may be of use. I offer no guarantees, except that it compiles and runs :-)
#include <streambuf> #include <ostream> template <class cT, class traits = std::char_traits<cT> > class basic_nullbuf: public std::basic_streambuf<cT, traits> { typename traits::int_type overflow(typename traits::int_type c) { return traits::not_eof(c); // indicate success } }; template <class cT, class traits = std::char_traits<cT> > class basic_onullstream: public std::basic_ostream<cT, traits> { public: basic_onullstream(): std::basic_ios<cT, traits>(&m_sbuf), std::basic_ostream<cT, traits>(&m_sbuf) { init(&m_sbuf); } private: basic_nullbuf<cT, traits> m_sbuf; }; typedef basic_onullstream<char> onullstream; typedef basic_onullstream<wchar_t> wonullstream; int main() { onullstream os; os << 666; }
-19996069 0 Unbounded knapsack pseducode I need to modify wiki's knapsack pseudocode for my homework so it checks whether you can achieve exact weight W in the knapsack or not. Number of items is unlimited and you the value not important. I am thinking to add a while loop under j>-W[j] to check how many same items would it fit. Will that work?
Thanks
// Input: // Values (stored in array v) // Weights (stored in array w) // Number of distinct items (n) // Knapsack capacity (W) for w from 0 to W do m[0, w] := 0 end for for i from 1 to n do for j from 0 to W do if j >= w[i] then m[i, j] := max(m[i-1, j], m[i-1, j-w[i]] + v[i]) else m[i, j] := m[i-1, j] end if end for end for
-8614416 0 MVP can be explained the following way:
Model -- the domain model of your application. All business logic is here.
Presenter -- All view logic is here. Retrieves data from model and updates the view.
View -- UI presentation. Contains no updating logic. Fires events to the presenter on user interaction something and listens to the events from the presenter.
-17701847 0 Database implementation of formattingI have database like this:
text_id | sentence_id | word_id | word | meaning 4 2 124 I Ja 4 2 124 like lubię 4 2 124 trains. pociągi Where "Ja", "lubię" , "pociągi" are unique translation in particular context.
The thing is that I need sometimes, format this text, this is for example bold the word "trains" in on my website. Or surround one of the sentences with:
<h1> </h1> tag.
I have no idea how to save information about formatting in a not obtrusive way.
Thanks for help.
PS: I need no fancy formatting, I just need save information about new paragraphs "p" headers "h1" "h2" and so on.
Maybe I would like to save information about image that is between particular sentences.
PS2: I use MySql.
-37749979 0You don't instantiate ConfigParser when you assign it to the self.scfgs or self.cfg attributes; so when you then call read on it, you're calling an unbound method via the class, rather than a method on the instance.
It should be:
self.cfg = ConfigParser() etc
-31138279 0 Standard output strange behaviorI have an issue using Eclipse cdt and I am facing a strange behavior:
cout << "Hello world" << endl; aFunction(); // The output here is Hello world // END When I take off the endl the output is nothing
cout << "Hello world"; aFunction(); // No output // END and when I put the endl later it works fine :
cout << "Hello world"; aFunction(); cout << endl; // output is Hello world // END Now, I can't provide the function code, because it will take me a thousand of lines.
However, I tried this with a function that does nothing void toto(){} and there was not this strange thing .
cout << "Hello world"; toto(); // Gives me Hello world // END What I want to know is what can cause this ??
EDIT : The tests with foo are tested alone (no other instructions), In the other tests, I initialize a structure that I give as a parameter to aFunction. The function uses some metaprogramming and there is a lot of code i need to show so you understand it.
One possible Approch:
SELECT FROMID, FROMOWNERID, APPROVERID, NULL APPROVERID, NULL APPROVERID, NULL APPROVERID FROM yourtable WHERE FROMID = 100 AND APPROVERID = 102 UNION ALL SELECT FROMID, FROMOWNERID, NULL APPROVERID, APPROVERID APPROVERID, NULL APPROVERID, NULL APPROVERID FROM yourtable WHERE FROMID = 100 AND APPROVERID = 103 UNION ALL SELECT FROMID, FROMOWNERID, NULL APPROVERID, NULL APPROVERID, APPROVERID APPROVERID, NULL APPROVERID FROM yourtable WHERE FROMID = 100 AND APPROVERID = 104 ---- ------- And So On
-23456472 0 Converting an if-else statement into a switch statement I'm having trouble turning this program from an if-else statement into a switch statement. Any help would be appreciated.
#!/bin/bash for x in $@ do array[$i]=$x i=$((i+1)) done # initial state state=S0 for((i=0;i<${#array[@]};i++)) do if [ $state == S0 ] then if [ ${array[$i]} == I0 ] then state=S1 output[$i]=O1 elif [ ${array[$i]} == I1 ] then state=S0 output[$i]=O0 fi elif [ $state == S1 ] then if [ ${array[$i]} == I0 ] then state=S1 output[$i]=O1 elif [ ${array[$i]} == I1 ] then state=S0 output[$i]=O0 fi fi done echo "final state="$state echo "output="${output[@]} for those who are wondering about script.. this script about finite state machine .. this script has two states I want to convert to case statement so it can be readable and faster especially for big projects not like this one.
-41024710 0You could use the property accessor, like the assignment.
var f = function() { console.log("Hello! " + f.x); } f.x = "Whoohoo"; console.log(f.x); f(); For stable access, you could use a named function
var f = function foo() { console.log("Hello! " + foo.x); } // ^^^ >>>>>>>>>>>>>>>>>>>>>>>>>>> ^^^ f.x = "Whoohoo"; console.log(f.x); f(); I have been trying to install Django correctly for a while to no avail.
C:\Python34\Scripts\pip.exe install C:\Python34\Lib\site-packages\Django-1.7.2\Django-1.7.2\setup.py raises an exception and stores the following in a log file:
C:\Python34\Scripts\pip run on 01/12/15 17:47:02 Exception: Traceback (most recent call last): File "C:\Python34\lib\site-packages\pip\basecommand.py", line 122, in main status = self.run(options, args) File "C:\Python34\lib\site-packages\pip\commands\install.py", line 257, in run InstallRequirement.from_line(name, None)) File "C:\Python34\lib\site-packages\pip\req.py", line 172, in from_line return cls(req, comes_from, url=url, prereleases=prereleases) File "C:\Python34\lib\site-packages\pip\req.py", line 70, in __init__ req = pkg_resources.Requirement.parse(req) File "C:\Python34\lib\site-packages\pip\_vendor\pkg_resources.py", line 2606, in parse reqs = list(parse_requirements(s)) File "C:\Python34\lib\site-packages\pip\_vendor\pkg_resources.py", line 2544, in parse_requirements line, p, specs = scan_list(VERSION,LINE_END,line,p,(1,2),"version spec") File "C:\Python34\lib\site-packages\pip\_vendor\pkg_resources.py", line 2512, in scan_list raise ValueError("Expected "+item_name+" in",line,"at",line[p:]) ValueError: ('Expected version spec in', 'C:\\Python34\\Lib\\site-packages\\Django-1.7.2\\Django-1.7.2\\setup.py', 'at', ':\\Python34\\Lib\\site-packages\\Django-1.7.2\\Django-1.7.2\\setup.py') any help would be greatly appreciated! THANK YOU
-11404401 0I am not sure if I understand you right, but does a tranpose of your matrix do the job?
Here is an example:
require(gplots) data(mtcars) x <- as.matrix(mtcars) heatmap.2(x) 
# transpose the matrix heatmap.2(t(x)) 
I'm trying to figure out if there is an easy way implementing a retry to the service when it sends a fault. lets say for eg:
Private Function SaveEmployee(emp as Empoyee) Try ... returnval = service.SaveEmployee(emp) Catch ex as exception 'if exception requires retry eg:end point not found or database is not responding then 'call retry func/class RetryOperation(...) End Try End Function in the above sample how can I make a generic RetryOperation class which can take any function and call it 3 or 4 times with an interval before informing the user that the operation cannot be completed.
I'm hoping it's possible to make a generic method rather than have duplicate code in all the service call functions
any samples in C# or vb.net will be really appreciated.
Thanks
-24475236 0If you want to use the symbolic toolbox, define functions of type symfun:
syms t x1(t)=A1*cos(w1*t); now you can easily integrate:
Ix1=int(x1) xc(t)=cos(wc*t + Ix1(t)-Ix1(0))
-14332615 0 How about this:
[TestFixture] public class Tests { [Test] public void Test() { var obj = new MyClass(); obj.First = "some value"; obj.Second = "some value"; obj.Third = "some value"; AssertPropertyValues(obj, "some value", x => x.First, x => x.Second, x => x.Third); } private void AssertPropertyValues<T, TProp>(T obj, TProp expectedValue, params Func<T, TProp>[] properties) { foreach (var property in properties) { TProp actualValue = property(obj); Assert.AreEqual(expectedValue, actualValue); } } }
-2712107 0 This article is a guide to building a .net component ,using it in a Vb6 project at runtime using late binding, attaching it's events and get a callback.
http://www.codeproject.com/KB/cs/csapivb6callback2.aspx
-5102093 0Yes, for instance singleton implementations can be static but they have to implement mechanisms such as double checked locking to prevent multithreading issues.
-27281621 0First, don't use action bar tabs because they are deprecated (find an alternative Action bar navigation modes are deprecated in Android L).
Second, optimize fragments that are contained in ViewPager.
Third, optimize everything else (like navigation drawer listview)
-13680508 0 Image is not in one line with other componentsI know that alignment is sometimes complicated in html. But here is something puzzled for me. I have div with text,button and image with no other options.
<div class="div-filter"> <input type="text" value="Hladaj"/> <input type="submit" value="Hladaj"/> <img alt="image" id = "ShowOrHideImage" />

Why is image is cca 5px higher? Without image there is no padding over text and button. When I put there image.....
To be clear:
<style> .div-filter { background-color:rgb(235, 235, 98); width:100%; border-bottom-width: 1px; border-top-width: 1px; border-left-width: 1px; border-right-width: 1px; border-bottom-color: black; border-top-color: black; border-left-color: black; border-right-color: black; border-bottom-style: solid; border-top-style: solid; border-left-style: solid; border-right-style: solid; } I can resolve it with table and tableRow but it is not good for me.
-13057842 0You question isn't clear. Frequency has nothing to do with getting signal strength. Signal strength is calculated by the WiFi client upon receiving of frame. If you want to get every channel signal strength, you need to do WiFi scanning. Scanning is defined in 802.11 (WiFi) protocol and is done every n time units without user intervention.
-18733408 0 Cannot find symbol : constructorWhen I compile I am getting the error: cannot find symbol symbol : constructor Team()
public class Team { public String name; public String location; public double offense; public double defense; public Team(String name, String location) { } public static void main(String[] args) { System.out.println("Enter name and location for home team"); Scanner tn = new Scanner(System.in); Team team = new Team(); team.name = tn.nextLine(); Scanner tl = new Scanner(System.in); team.location = tl.nextLine(); } } Any ideas how to fix? many thanks Miles
-27397145 0alternative is to change the order of timestamp column
OR
set first column DEFAULT value like this
ALTER TABLE `tblname` CHANGE `first_timestamp_column` `first_timestamp_column` TIMESTAMP NOT NULL DEFAULT 0;
-34708148 0 The answer by @miro is very good but can be improved as in the following middleware in a separate file (as @ebohlman suggests).
module.exports = { configure: function(app, i18n, config) { app.locals.i18n = config; i18n.configure(config); }, init: function(req, res, next) { var rxLocale = /^\/(\w\w)/i; if (rxLocale.test(req.url)){ var locale = rxLocale.exec(req.url)[1]; if (req.app.locals.i18n.locales.indexOf(locale) >= 0) req.setLocale(locale); } //else // no need to set the already default next(); }, url: function(app, url) { var locales = app.locals.i18n.locales; var urls = []; for (var i = 0; i < locales.length; i++) urls[i] = '/' + locales[i] + url; urls[i] = url; return urls; } }; Also in sample project in github.
The middleware has three functions. The first is a small helper that configures i18n-node and also saves the settings in app.locals (haven't figured out how to access the settings from i18n-node itself).
The main one is the second, which takes the locale from the url and sets it in the request object.
The last one is a helper which, for a given url, returns an array with all possible locales. Eg calling it with '/about' we would get ['/en/about', ..., '/about'].
In app.js:
// include var i18n = require('i18n'); var services = require('./services'); // configure services.i18nUrls.configure(app, i18n, { locales: ['el', 'en'], defaultLocale: 'el' }); // add middleware after static app.use(services.i18nUrls.init); // router app.use(services.i18nUrls.url(app, '/'), routes); The locale can be accessed from eg any controller with i18n-node's req.getLocale().
What @josh3736 recommends is surely compliant with RFC etc. Nevertheless, this is a quite common requirement for many i18n web sites and apps, and even Google respects same resources localised and served under different urls (can verify this in webmaster tools). What I would recommended though is to have the same alias after the lang code, eg /en/home, /de/home etc.
basicly what i want to do is written in code. so , is there a way with templates or with something else get outer class name in global function ? is there a way to get this code work?
#include <iostream> class A { public: enum class B { val1, val2 }; typedef B InnerEnum; static void f(InnerEnum val) { std::cout << static_cast<int>(val); } }; template <typename T1> void f(typename T1::InnerEnum val) { T1::f(val); } int main() { A::InnerEnum v = A::InnerEnum::val1; f(v); return 0; }
-28848983 0 Yes, it was a bug in the control, it could not start document processing/calculating while it is invisible (or is placed in an invisible container). This bug is fixed in the context of this ticket: https://www.devexpress.com/Support/Center/Question/Details/T198005.
The hotfix is already requested and I believe it will be available in the nearest days.
-28754534 0The abstract operation that converts to a boolean is called ToBoolean:
falsefalsefalse if the argument is +0, −0, or NaN; otherwise the result is true.false if the argument is the empty String (its length is zero); otherwise the result is true.true.However, this operation is internal and not available.
But there are some workaround to use it:
!!variable; variable ? true : false; Boolean(variable) You need to use something like Rollup, Webpack, or Browserify. This statement import FormComponent from './FormComponent.js'; doesn't mean anything on the client. No browser natively supports it so you need something like the tools mentioned above to turn it into something the browser can actually use.
Without them you just have to load the files in your index.html.
-7406247 0Too much recursion means that something is looping over and over again, possibly infinitely. The reason that's happening with your current code is because <a> is a parent of <img>, so any click event on <img> bubble up to the parent <a> (search for "event bubbling" in Google). So your code is basically saying "when someone clicks on <a>, trigger a click on <img> and then <a> (because of event bubbling)" -- which of course causes the code to run again.
If the JavaScript plugin already has binded events to clicks on the image, I don't see why you need to bind a click event to the parent <a> that simply clicks on the image. What do you need to happen that isn't already happening when the user clicks on the <img> -- without including your jQuery code?
i want to be able to fetch all the quotas status related to the google analytics API consumption. One part of it seems to be available via IAM:
First, accessing to these data through an API would be nice..is it possible with the IAM API ?? If so, can i get a sample ?
Next, i need one more data: the google analytics quota consumption PER VIEW (which is limited to 10.000 queries per view per day)..is it also possible to fetch this data, one way or another ?
Cheers,
Clément.
-36033771 0 Adaptive size classes weired issueMy app is universal. I have different constraints for iphone and ipad. Using adaptive size classes, Particularly i am assigning label leading margin to superview = 390, for ipad only. As you can see in attached image. 
It is working fine, when text to label is static, but my text to label is getting changed dynamically and continuously. Because of this, my lablel's position is getting shifted horizontally.
-10634536 0Here is the code I'm using. Change BUFFER_SIZE for your needs.
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class ZipUtils { private static final int BUFFER_SIZE = 4096; private static void extractFile(ZipInputStream in, File outdir, String name) throws IOException { byte[] buffer = new byte[BUFFER_SIZE]; BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(outdir,name))); int count = -1; while ((count = in.read(buffer)) != -1) out.write(buffer, 0, count); out.close(); } private static void mkdirs(File outdir,String path) { File d = new File(outdir, path); if( !d.exists() ) d.mkdirs(); } private static String dirpart(String name) { int s = name.lastIndexOf( File.separatorChar ); return s == -1 ? null : name.substring( 0, s ); } /*** * Extract zipfile to outdir with complete directory structure * @param zipfile Input .zip file * @param outdir Output directory */ public static void extract(File zipfile, File outdir) { try { ZipInputStream zin = new ZipInputStream(new FileInputStream(zipfile)); ZipEntry entry; String name, dir; while ((entry = zin.getNextEntry()) != null) { name = entry.getName(); if( entry.isDirectory() ) { mkdirs(outdir,name); continue; } /* this part is necessary because file entry can come before * directory entry where is file located * i.e.: * /foo/foo.txt * /foo/ */ dir = dirpart(name); if( dir != null ) mkdirs(outdir,dir); extractFile(zin, outdir, name); } zin.close(); } catch (IOException e) { e.printStackTrace(); } } }
-6394860 0 @Maz - thank you for that. I'm learning at the moment and need to look at service_set.
@arustgi - that worked perfectly. For the benefit of fellow novices stumbling over this, I pass in 'queryset': Service.objects.all() and use:
{% regroup object_list by area as area_list %} {% for area in area_list %} <h2 class="separate">{{ area.grouper }}</h2> {% for service in area.list %} <div class="column"> <h3>{{ service.title }}</h3> {{ service.body }} </div> {% endfor %} {% endfor %} Concise, descriptive code. Many thanks, both of you
-8835956 0 Make CVDisplayLink + Automatic Reference Counting play well togetherI recently switched from using NSTimer to CVDisplayLink to redraw my OpenGL animation, but i've got a little problem making it work with ARC switched on:
/* * This is the renderer output callback function. */ static CVReturn displayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeStamp* now, const CVTimeStamp* outputTime, CVOptionFlags flagsIn, CVOptionFlags* flagsOut, void* displayLinkContext) { // now is the time to render the scene [((__bridge BDOpenGLView*)displayLinkContext) setNeedsDisplay:YES]; // always succeeds, because we don't actually do anything here anyway return kCVReturnSuccess; } The display link callback function has to be written in C, to be used as a parameter for
// set the renderer output callback function CVDisplayLinkSetOutputCallback(displayLink, &displayLinkCallback, (__bridge void*)self); So i can't use self within in the callback, but using ((__bridge BDOpenGLView*) displayLinkContext) produces a memory leak:
objc[29390]: Object 0x1001b01f0 of class NSConcreteMapTable autoreleased with no pool in place - just leaking - break on objc_autoreleaseNoPool() to debug I read, that i have to set up an NSAutoreleasePool myself, but i can't with ARC switched on.
Am i missing something?
-38972851 0If you are using a version of .net less than 4.5, manual collection may be inevitable (especially if you are dealing with many 'large objects').
this link describes why:
https://blogs.msdn.microsoft.com/dotnet/2011/10/03/large-object-heap-improvements-in-net-4-5/
-13953601 0There are several techiniques for removing outliers or refining matches:
Cross check
Ratio test
RANSAC+Homography for planar shapes
I usually apply the last two ones.
RATIO TEST:
BFMatchermatcher(CV_L2); vector<vector<DMatch>>nearest_neighbors; matcher.radiusMatch( right_points_to_find_flat, right_features_flat, nearest_neighbors, 2.0f); // Check that the found neighbors are unique (throw away neighbors // that are too close together, as they may be confusing) std::set<int>found_in_right_points; // for duplicate prevention for(inti=0;i<nearest_neighbors.size();i++) { DMatch _m; if(nearest_neighbors[i].size()==1) { _m = nearest_neighbors[i][0]; // only one neighbor } else if(nearest_neighbors[i].size()>1) { // 2 neighbors – check how close they are double ratio = nearest_neighbors[i][0].distance / nearest_neighbors[i][1].distance; if(ratio < 0.7) { // not too close // take the closest (first) one _m = nearest_neighbors[i][0]; } else { // too close – we cannot tell which is better continue; // did not pass ratio test – throw away } } else { continue; // no neighbors... :( } RANSAC+Homography:
std::vector<Point2f> object; std::vector<Point2f> scene; for( int i = 0; i < good_matches.size(); i++ ) { //-- Get the keypoints from the good matches object.push_back( keypoints_object[ good_matches[i].queryIdx ].pt ); scene.push_back( keypoints_scene[ good_matches[i].trainIdx ].pt ); } Mat H = findHomography( object, scene, CV_RANSAC, status ); //draw only the matches considered inliers by RANSAC => status=1 for(i=0;i=object.size();i++){ if(status[i]) { } }
-20594029 1 How do you order what websites reply in Skype4Py? I use Skype4Py for my Skype Bot I've been working on.
I was wondering how I could order what the APIs respond.
For example, if I wanted to get the weather, I'd type !weather
and it would respond with:
Gathering weather information. Please wait...
Weather: { "data": { "current_condition": [ {"cloudcover": "0", "humidity": "39", "observation_time": "11:33 AM", "precipMM": "0.0", "pressure": "1023", "temp_C": "11", "temp_F": "51", "visibility": "16", "weatherCode": "113", "weatherDesc": [ {"value": "Clear" } ], "weatherIconUrl": [ {"value": "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0008_clear_sky_night.png" } ], "winddir16Point": "N", "winddirDegree": "0", "windspeedKmph": "0", "windspeedMiles": "0" } ], "request": [ {"query": "90210", "type": "Zipcode" } ] }}
and I would like to have it be more like:
Weather:
Current Temp: 51 F | 22 C
Humidity: 39%
Wind Speed: 0 MPH
or something cleanly ordered out like that.
That way it looks less ugly in Skype, and looks more professional.
I should've added the code:
def weather(zip): try: return urllib2.urlopen('http://api.worldweatheronline.com/free/v1/weather.ashx?q='+zip+'&format=json&num_of_days=1&fx=no&cc=yes&key=r8nkqkdsrgskdqa9spp8s4hx' ).read() except: return False That is my functions.py
This is my commands.py:
elif msg.startswith('!weather '): debug.action('!weather command executed.') send(self.nick + 'Gathering weather information. Please wait...') zip = msg.replace('!weather ', '', 1); current = functions.weather(zip) if 4 > 2: send('Weather: ' + current) else: send('Weather: ' + current) Like I stated, I'm using Skype4Py, and yeah.
-27324005 0The jar may be in your deployed folder, but is the jar (or your deployed folder with a wildcard) in the CLASSPATH?
-30805163 0 Tools to minify CDD and JS filesI deployed my application, I find that the loading time is much .. there isa way to compress css and js files ? , knowing that I use in each page that the necessary and sometimes js version minified .. thank you
-3355092 0Please copy the libeay32.dll and sselay.dll in to the C:\windows and C:\windows\system32 and restart on your webserver and see the correct php.ini file is loaded
-14386487 0 Bootstrap progress bar using $.getI realize there are a good number of progress bar related questions already present on SO. I browsed through many of them and was unable to get things working.
Simply put, I am developing a page in JSP and I want to use an animated progress bar within bootstrap to display while the calls are being made for the data.
HTML:
<div class="row-fluid"> <div class="span12 progress progress-striped active"> <div id="searchAnimation" class="bar" hidden="true"></div> </div> </div> Servlet (Not sure if this part is relevant, but better safe than sorry):
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //String that gets returned as HTML StringBuilder returnAsHTML = new StringBuilder(); //See if the class is closed, has a lab, or is just a regular class for(ClassInfo classes : springClassListings) { //Class is full, style accordingly if(classes.getSectionMeetingInfo().contentEquals("LEC") && classes.getSectionEnrolled().contentEquals("0")) { returnAsHTML.append(closedClass(classes)); } else if(classes.getSectionMeetingInfo().contentEquals("LAB")) //These are labs, style accordingly { returnAsHTML.append(labClass(classes)); } else //These are normal classes without lab components { returnAsHTML.append(openClass(classes)); } } response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(returnAsHTML.toString()); } And my scripting:
//Serves up the data $('#btnData').click(function() { //THIS IS THE PROGRESS BAR $("#searchAnimation").show(); $.get('daoServlet', function(responseText) { $('#dataDisp').html(responseText); }); }); I get the idea, % the width of the progress bar by a where the $.get call is at in terms of getting the data. I just don't understand how to do it.
PS - I know my for/if in the doGet is a nasty anti pattern, I just haven't figured out a way around it yet.
-30522654 0First download the .ttf file of the font you need (arial.ttf). Place it in the assets folder(Inside assest folder create new folder named "fonts" and place it inside it). If "txtyour" is the textvies you want to apply the font , use the following piece of code,
Typeface type = Typeface.createFromAsset(getAssets(),"fonts/arial.ttf"); txtview.setTypeface(type);
-11809126 1 Cannot determine vowels from consonants With the code below, no matter what the first letter of the input is, it is always determined as a vowel:
original = raw_input("Please type in a word: ") firstLetter = original[0] print firstLetter if firstLetter == "a" or "e" or "i" or "o" or "u": print "vowel" else: print "consonant" In fact, it doesn't matter what the boolean is in the if statement... if it is == or != , it is still return "vowel". Why?
Qt does not include a compiler. On Windows you're probably either compiling with mingw or Visual C++. Either way, the issue is that you're calling a function that expects a wide character string but you're trying to hand it an 8-bit character string.
For compatibility reasons, Win32 uses a different set of API functions if you have _UNICODE defined. In your case, you do have _UNICODE defined. You can continue using the 8-bit std::string but simply change the method from LoadImage() to LoadImageA(). Or if you don't mind changing your Bitmap class, you could switch from std::string to std::wstring to take advantage of Windows' Unicode features.
But perhaps the larger question is why use Win32 to load bitmaps and std::string if you're using Qt? Qt's QImage class and QString class provide a full-featured, cross-platform strings and image loaders. Like any comprehensive framework, Qt works best if you only use external features on an as-needed basis.
-39814785 0 Acknowledgements in socket.io when using mongooseI use socket.io to communicate between server and client.
On the server, I have
socket.on('new object', (id, object) => { Model.findByIdAndUpdate(id, { $addToSet: { objects: object } }, { new: true }).then(model => { io.sockets.emit('new object', object); }).catch(err => { console.log(err); }); }); So when a new object is created, I broadcast it to all sockets (including the sender).
What I want is to tell the client who started this process from the client if everything was successful.
I have found http://socket.io/docs/#sending-and-getting-data-(acknowledgements), but I don't know exactly how to do it.
I guess I should do something like
socket.on('new object', (id, object, callbackFunction) => { Model.findByIdAndUpdate(id, { $addToSet: { objects: object } }, { new: true }).then(model => { callbackFunction('success'); io.sockets.emit('new object', object); }).catch(err => { callbackFunction('error'); }); }); and on the client have
socket.emit('new object', id, object, function (msg) { alert(msg); }); but is this correct? I guess there will be a problem of calling callbackFunction inside then and catch.
I have an issue with SQL Server transactional replication performance. The published articles are on a database which is being used quite heavily however i am not convinced the replication is should be going this slow and I could use some advice on interpreting the information from replication monitor.


I have noticed that the distributor agent has a delivery rate of 0 which concerns me. Can someone explain what the following information means in real terms and how i can go about improving the performance of replication?
-20097995 0 Referencing Databases In SQL 2008 Mirrored ReportingI have 2 databases.
1 is a mirror of the other, EXCEPT, 1 has a table called DOG and the other has the same table but it is called DOG2.
I have an ssrs report that references DOG..DOGID.
Now when DOG goes down I want to use the connection string to DOG2, the only issue is my reference to DOG..ID will no longer be valid if I am connecting to DOG2.
Is there a way in SQL code to make it so if DOG..DOGID is invalid use DOG2..DOGID?
-14001367 0What you might be seeing is that until the alert box is dismissed, the code afterwards is not executed. The alert command is a blocking one.
Perhaps you can use console.log() for debugging purposes of this feature. This will not block your code and it will be executed on the keydown event.
The only version of OneNote that is available for Mac OSX is available through the app store.
There is no version of OneNote 2010 that works on Mac.
-5063262 0Sounds like your rendering thread is just sat there waiting for the update thread to finish what its doing which causes the "jitter". Perhaps put in some code that logs how long a thread has to wait for before being allowed access to the other thread to find out if this really is the issue.
-20621434 0Try the jQuery function val() instead of the non-existant property .value:
$('#postcode_entry').val()
-35583765 0 You could possibly INNER JOIN the two result sets
select from test1 AS T1 INNER JOIN (select * from test1 where head_Id_Head = 5 and detail_Id_Detail = 4) AS T2 ON T2.company_Id_Company = T1.company_Id_Company where T1.head_Id_Head = 1 and T1.detail_Id_Detail = 7 Or even simpler
select * from test1 where head_Id_Head = 1 and detail_Id_Detail = 7 AND company_Id_Company IN (select company_Id_Company from test1 where head_Id_Head = 5 and detail_Id_Detail = 4)
-25698830 0 Programatically reading iOS app .crash file? As per my understanding, when an iOS app crashes, the system creates a .crash file that can be accessed through XCode. Is it possible to read this file programatically from within the app itself?
My intention is to send this crash log (if exists) to a server so that we can analyse the log without user intervention. There are several crash reporting services (e.g. bugsense, crashlytics) that are able to do this, so I assume a custom implementation should be possible?
Cheers!
-7301549 0The browser sends the value of radio buttons only when they are checked.
Also, each radio button must have the same name (if you want to user to be able to check only one of them). Only the value changes:
print '<input type=checkbox checked value="'.htmlspecialchars($element).'" name=checked_items />'; POST this and check the value of $_POST['checked_items']
You've reached the end of the file. You should be able to do this to go back to the beginning:
searchFile.seek(0)
-33312748 0 why dont IDE's offer built in code timing like break points? I find timing my code for performance to be a bit of a headache and I have to assume this is a common problem for folks.
Adding in a bunch of code to time my loops is great but often there is more overhead in adding the timing checks than adding a parallel task. making a loop parallel can take seconds whereas adding in timing chunks requires several lines of code and be dangerous if forgotten.
So... My question is why dont IDE's include this ability to time chunks of code like a break point? Something like i mark a section of code and tell it to dump the timing output to a console with some options to make it more readable. averages and such.
I know break points can seriously hamper performance but there must be an easier way to time specific chunks of code then to write all my own timing routines for each chunk of code i want to check.
-15686849 0Everyting can be achieved via the built-in functions of PHP, so you can do all that you can with String objects.
-30375660 0If you use the AJAX Control toolkit, you could put a panel around the table and add the DragPanel and ResizableControl extenders to the panel.
-16310139 0CREATE LOGIN [IIS APPPOOL\MyAppPool] FROM WINDOWS; CREATE USER MyAppPoolUser FOR LOGIN [IIS APPPOOL\MyAppPool];
-730847 0 You can drag the provision profile and the app package into itunes and sync. This is how you can distribute your beta.
Note that the phones will have to be registered(UDID) in the developer program portal.
-16740797 0In case (a), What do you expect to happen if the pattern occurs within the 10 lines?
Anyway, here are some awk scripts which should work (untested, though; I don't have Solaris):
# pattern plus 10 lines awk 'n{--n;print}/PATTERN/{if(n==0)print;n=10}' # between two patterns awk '/PATTERN1/,/PATTERN2/{print}' The second one can also be done similarly with sed
After you initialize the PDO object try setting the error mode higher.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
The default is PDO::ERRMODE_SILENT which will output no warnings/errors. With this default setting, you have to poll errorInfo() to see error details.
I have 2 linq 2 SQL statements I'd like to be in a transaction (the SQL server is remote, outside firewalls etc) all other communication works but when I wrap these 2 statements in a TransactionScope() I begin having to configure MSDTC which we did, but then there are firewall issues (I think) is there a simpler way?
the basics of what I want to do boil down to this: (both are stored procs under the hood)
using (var transactionScope = new TransactionScope()) { Repository.DataContext.SubmitChanges(); Repository.DataContext.spDoFinalStuff(tempID, ref finalId); transactionScope.Complete(); } What is the simplest way to achieve this?
EDIT:
first I got this: The transaction manager has disabled its support for remote/network transactions. (Exception from HRESULT: 0x8004D024) On our servers I followed the instructions here to correct this. However the instructions don't seem to apply to windows 7 (my dev box) see my comment on above answer.
after correcting the issue (on the non win7 boxes) I get this: The transaction has already been implicitly or explicitly committed or aborted (Exception from HRESULT: 0x8004D00E) which some googling suggested may be firewall issue.
EDIT
I just discovered the remote DB is SQL 2000
Using the Poco libraries, if I'm doing something like this:
MailMessage mailMessage; mailMessage.addPart("", new FilePartSource("/path/icon.png", "image/png"), Poco::Net::MailMessage::CONTENT_ATTACHMENT, Poco::Net::MailMessage::ENCODING_BASE64); Do I need to worry about deleting the "newed" FilePartSource
that's sent to the addPart method/function in MailMessage?
Upload a file using POCO - SSL Connection Unexpectedly Closed Exception
I've noticed in some examples where "new" is tossed-in places that I wouldn't call typical.
Line 65-66: new StringPartSource https://github.com/pocoproject/poco/blob/develop/Net/samples/Mail/src/Mail.cpp
Line 88: new Context https://github.com/pocoproject/poco/blob/develop/NetSSL_OpenSSL/samples/Mail/src/Mail.cpp
-28869430 0Here's my solution:
var items = [ { id: 1, name: 'bill' }, { id: 2, name: 'sam' }, { id: 3, name: 'mary' }, { id: 4, name: 'jane' } ]; var order = [ { id: 1, sortindex: 4 }, { id: 2, sortindex: 2 }, { id: 3, sortindex: 1 }, { id: 4, sortindex: 3 } ]; _(items) .indexBy('id') .at(_.pluck(_.sortBy(order, 'sortindex'), 'id')) .pluck('name') .value(); // → [ 'mary', 'sam', 'jane', 'bill' ] Here's what's going on:
items into an object, where the id values are the keys.order by the sortindex key.id array.If you're gathering facts, you can access hostvars via the normal jinja2 + variable lookup:
e.g.
- hosts: serverA.example.org gather_facts: True ... tasks: - set_fact: taco_tuesday: False and then, if this has run, on another host:
- hosts: serverB.example.org ... tasks: - debug: var="{{ hostvars['serverA.example.org']['ansible_memtotal_mb'] }}" - debug: var="{{ hostvars['serverA.example.org']['taco_tuesday'] }}" Keep in mind that if you have multiple Ansible control machines (where you call ansible and ansible-playbook from), you should take advantage of the fact that Ansible can store its facts/variables in a cache (currently Redis and json), that way the control machines are less likely to have different hostvars. With this, you could set your control machines to use a file in a shared folder (which has its risks -- what if two control machines are running on the same host at the same time?), or set/get facts from a Redis server.
For my uses of Amazon data, I prefer to just fetch the resource each time using a tag/metadata lookup. I wrote an Ansible plugin that allows me to do this a little more easily as I prefer this to thinking about hostvars and run ordering (but your mileage may vary).
-34935044 0Your solution will almost definitely end up involving ssh in some capacity.
You may want something to help manage the execution of commands on multiple servers; ansible is a great choice for something like this.
For example, if I want to install libvirt on a bunch of servers and make sure libvirtd is running, I might pass a configuration like this to ansible-playbook:
- hosts: all tasks: - yum: name: libvirt state: installed - service: name: libvirtd state: running enabled: true This would ssh to all of the servers in my "inventory" (a file -- or command -- that provides ansible with a list of servers), install the libvirt package, start libvirtd, and then arrange for the service to start automatically at boot.
Alternatively, if I want to run puppet apply on a bunch of servers, I could just use the ansible command to run an ad-hoc command without requiring a configuration file:
ansible all -m command -a 'puppet apply'
-11157108 1 OpenCL delete data from RAM I'm coping data in python using OpenCL onto my graphic card. There I've a kernel processing the data with n threads. After this step I copy the result back to python and in a new kernel. (The data is very big 900MB and the result is 100MB) With the result I need to calculate triangles which are about 200MB. All data exceed the memory on my graphic card.
I do not need the the first 900MB anymore after the first kernel finished it's work.
My question is, how can I delete the first dataset (stored in one array) from the graphic card?
Here some code:
#Write self.gridBuf = cl.Buffer(self.context, cl.mem_flags.READ_ONLY | cl.mem_flags.COPY_HOST_PTR, hostbuf=self.grid) #DO PART 1 ... #Read result cl.enqueue_read_buffer(self.queue, self.indexBuf,index).wait()
-22008665 0 IsHitTestVisible helped but it was disabling the control. so through infragistic got few styles to be applied to disable the drag feature but still keep control enabled.
The sample is here :http://www.infragistics.com/community/forums/p/86863/433458.aspx#433458
-11900001 0 Default parameter template vs variadic template : what is the last template parameter?I'm a little confused because both a default parameter template and a variadic template parameter have to be the last parameter of a template. So what is the good official syntax for my function ?
template<typename T, class T2 = double, unsigned int... TDIM> myFunction(/* SOMETHING */) or
template<typename T, unsigned int... TDIM, class T2 = double> myFunction(/* SOMETHING */)
-1467968 0 Classes in different sub-namespaces all appear at top level in WSDL I'm creating a web service with a variety of classes, many of which can contain references to other classes. Sometimes these "sub classes" have the same name (e.g. Customer and Customer), but are actually different, so I've placed these in different namespaces (e.g. MyRoot.Sub1, MyRoot.Sub2, etc.)
When I build the service, the generated WSDL places all of these classes at the top level, without specifying any delineation by sub-namespace. Therefore, it will define two versions of "Customer". Curiously, it doesn't complain during the build process.
When I host the service and try to reference it with a browser, I get the following error:
The top XML element 'Customer' from namespace 'RE: http://...' references distinct types MyRoot.Sub1.Customer and MyRoot.Sub2.Customer. Use XML attributes to specify another XML name or namespace for the element or types.
I looks like I could use XmlTypeAttribute TypeName to provide an unique class name, but this makes documentation quite a hassle, as everything's going to have two names. Considering the differentiation is already specified by the namespaces, is there any way to utilize that information? I haven't tried using TypeName="Sub1.Customer", etc., but none of the examples that I've seen use this notation, so I'm skeptical.
Is there something else obvious that I'm missing?
-783253 0This is why we have the REST (and SOAP) protocols.
The desktop makes RESTful requests to your web application. Your web application receives the REST requests and does the real work.
Your code exists in exactly one place -- the web.
-33480864 0 How to make the parent view to handle all the OnClick events?I have a Layout that has a button that shows another view, but only for 1 time, I mean, you click the button, it dissapear and the other view is shown, the second time you should click the parent view of that button and the other view (the one that was shown) should dissapear and the button should appear again. I am trying with clickable:false and focusable:false but it is not working. How can I achieve that?
Relevant Code
XML
<LinearLayout android:id="@+id/item_tournament_header" android:background="@drawable/bg_card_tournament" android:layout_width="match_parent" android:layout_height="wrap_content" android:weightSum="15"> <RelativeLayout android:clickable="false" android:focusable="false" android:layout_weight="3" android:layout_width="0dp" android:layout_height="match_parent"> <com.github.siyamed.shapeimageview.CircularImageView android:id="@+id/item_friend_img_profile_pic" android:layout_height="48dp" android:layout_width="48dp" android:layout_centerInParent="true" android:scaleType="centerCrop" android:src="@drawable/ic_profile" app:siBorderColor="@color/white"/> </RelativeLayout> <LinearLayout android:clickable="false" android:focusable="false" android:layout_weight="10" android:layout_width="0dp" android:orientation="vertical" android:layout_height="match_parent"> <TextView android:id="@+id/tournament_name" android:textSize="@dimen/text_h3" android:textStyle="bold" android:textColor="@color/white" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/tournament_client" android:textSize="@dimen/text_p" android:textColor="@color/white" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> <RelativeLayout android:clickable="false" android:focusable="false" android:layout_weight="2" android:layout_width="0dp" android:orientation="vertical" android:layout_height="match_parent"> <ImageView android:id="@+id/btn_plus" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:src="@drawable/ic_plus_tournaments"/> </RelativeLayout> </LinearLayout> Java
btn_plus = (ImageView) findViewById(R.id.btn_plus); TournamentContent =(LinearLayout)findViewById(R.id.item_tournament_content); TournamentHeadaer =(LinearLayout)findViewById(R.id.item_tournament_header); btn_plus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { TournamentContent.setVisibility(View.VISIBLE); btn_plus.setVisibility(View.GONE); } }); TournamentHeadaer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(btn_plus.getVisibility()==View.VISIBLE) { // It's not entering here!!! TournamentContent.setVisibility(View.GONE); btn_plus.setVisibility(View.VISIBLE); } } });
-21251886 0 There are several syntax errors in your code try the following code,
$(function() { $("#toggleSelect").on("change", function() { idToggler = $(this).attr("rel"); if ($("#" + idToggler).is(":disabled")) { $("#" + idToggler).prop("disabled", false); } else { $("#" + idToggler).prop("disabled", true); } }); });
-2295552 0 select TPNB, sum(AllocatedQty) as 'QTY' from ( SELECT TPND, TPNB FROM ProductLookup GROUP BY TPND, TPNB ) as PL inner join dbo.AllocatedStock as AStock on PL.TPND = AStock.TPND group by TPNB
-18700563 0 My ajax call is not working in Chrome and Firefox Hi My ajax call is not working in chrome and firefox but it is in Safari. I am not able to figure it out as it is working on all browsers locally. My site is recently had SSl certificate.Is that something causing problem? I am not sure. For reference below is my Ajax function
<script type="text/javascript"> //<![CDATA[ $(function () { $("#selectReport").hide(); $("select#countryId").change(function () { var manu = $("#manufacturerId option:selected").text(); $("#Manufacturer").val(manu); $("#selectReport").show(); }); $("select#reportId").change(function (e) { e.preventDefault(); var country = $("#countryId option:selected").text(); $("#CountryName").val(country); }); $("select#reportId").change(function (event) { event.preventDefault(); var reportName = $("#reportId option:selected").text(); var manufacturer = $("#Manufacturer").val(); var countryName = $("#CountryName").val(); var theUrl = "/Reports/GetReport/" + reportName + "/" + manufacturer + "/" + countryName; $.ajax({ url: theUrl, type: 'get', success: function (data) { alert("I am success"); $('#ajaxOptionalFields').html(data); }, error: function () { alert("an error occured here"); } }); }); }); //]]> </script>
-3094575 0 Since your function is going to return a vector, you will have to make a new vector (i.e. copy elements) in any case. In which case, std::remove_copy_if is fine, but you should use it correctly:
#include <iostream> #include <vector> #include <set> #include <iterator> #include <algorithm> #include <functional> std::vector<int> filter(const std::vector<int>& all, const std::set<int>& bad) { std::vector<int> result; remove_copy_if(all.begin(), all.end(), back_inserter(result), [&bad](int i){return bad.count(i)==1;}); return result; } int main() { std::vector<int> all_items = {4,5,2,3,4,8,7,56,4,2,2,2,3}; std::set<int> bad_items = {2,8,4}; std::vector<int> filtered_items = filter(all_items, bad_items); copy(filtered_items.begin(), filtered_items.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; } To do this in C++98, I guess you could use mem_fun_ref and bind1st to turn set::count into a functor in-line, but there are issues with that (which resulted in deprecation of bind1st in C++0x) which means depending on your compiler, you might end up using std::tr1::bind anyway:
remove_copy_if(all.begin(), all.end(), back_inserter(result), bind(&std::set<int>::count, bad, std::tr1::placeholders::_1)); // or std::placeholders in C++0x and in any case, an explicit function object would be more readable, I think:
struct IsMemberOf { const std::set<int>& bad; IsMemberOf(const std::set<int>& b) : bad(b) {} bool operator()(int i) const { return bad.count(i)==1;} }; std::vector<int> filter(const std::vector<int>& all, const std::set<int>& bad) { std::vector<int> result; remove_copy_if(all.begin(), all.end(), back_inserter(result), IsMemberOf(bad)); return result; }
-40851473 0 I get a big Error when i want to run this program in eclipse I can't run this program in Eclipse. Eclipse doesn't say anything's wrong, I just can't open it.
Screenshot of the error and my program
-3847514 0 Google Checkout for peer-to-peer paymentsI'm trying to figure out if I can use Google Checkout for peer-to-peer payments. It seems fairly straightforward to set it up between a vendor and customers, but I'm not sure if it works well (or at all) for p2p.
Can I use Google Checkout to do peer to peer payments?
-10269674 0If you slice a string with a negative number, Python counts backward from the end.
complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'} s = "AAAAAAAAAACCCCCCCCCCTTTTTTTTTTGGGGGGGGGG" "".join(complement[c] for c in s[-20:-10]) EDIT:
Your edit looks about right to me, yes. I am very bad at checking for fencepost errors, but you're better placed to see those than I am anyway!
I've rewritten your code to be more Pythonic, but not changed anything substantial.
bc = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'N':'N'} f = open('chr22.fa') l = ''.join(line.strip() for line in f) f.seek(0) for line in f: fields = line.split('\t') gene_ID, chr, strand = fields[:2] start = int(fields[3]) end = int(fields[4]) if strand == '-': start, end = -(start + 1), -(end + 1) geneseq = ''.join(bc[base.upper()] for base in l[start:end])
-28456989 0 Alternatively, you could also use Apache Ruta, either with the workbench (recommended to get started) or with java code.
For the latter, I created an example project at https://github.com/renaud/annotate_ruta_example. The main parts are:
a list of names in src/main/resources/ruta/resources/names.txt (a plain text file)
Mark John Rabbit Owl Curry ATH-MX50 CC234 a Ruta script in src/main/resources/ruta/scripts/Example.ruta
PACKAGE example.annotate; // optional package def WORDLIST MyNames = 'names.txt'; // declare dictionary location DECLARE Name; // declare an annotation Document{-> MARKFAST(Name, MyNames)}; // annotate document and some java boilerplate code to launch the annotator:
JCas jCas = JCasFactory.createJCas(); // the sample text to annotate jCas.setDocumentText("Mark wants to buy CC234."); // configure the engine with scripts and resources AnalysisEngine rutaEngine = AnalysisEngineFactory.createEngine( RutaEngine.class, // RutaEngine.PARAM_RESOURCE_PATHS, "src/main/resources/ruta/resources",// RutaEngine.PARAM_SCRIPT_PATHS, "src/main/resources/ruta/scripts", RutaEngine.PARAM_MAIN_SCRIPT, "Example"); // run the script. instead of a jCas, you could also provide a UIMA collection reader to process many documents SimplePipeline.runPipeline(jCas, rutaEngine); // a simple select to print the matched Names for (Name name : JCasUtil.select(jCas, Name.class)) { System.out.println(name.getCoveredText()); } there is also some UIMA type (annotation) definitions, check src/main/resources/desc/type/ExampleTypes.xml, src/main/resources/META-INF/org.apache.uima.fit/types.txt and src/main/java/example/annotate.
git clone https://github.com/renaud/annotate_ruta_example.git cd annotate_ruta_example mvn clean install mvn exec:java -Dexec.mainClass="example.Annotate"
-4175981 0 How to specify liquid layout with swfobject? swfobject.embedSWF("flash/main.swf", "myContent", "100%", "100%"... It turns out the above doesn't work,how can I instruct to swfobject that I want the swf to be as wide/high as possible?
-17320883 0 right click save as pdf is not coming in embed tagIn my web page there is an Iframe and in this Iframe pdf is being generated by birt UI tool and working fine. But Problem is when I right click on the pdf and do save as its saving it as a html not as pdf.
The structure of the dome element is like this
<iframe> #document <html> <embed ..... ></embed> </html> </iframe> Actually this link is being fired and which gives a form and after filling the form and submitting it the pdf file is coming
The link is http://localhost:9090/ui_dashboard/frameset?__report=reports/RPT5008.rptdesign&__format=pdf&
this gives a form and the then after submitting it pdf is generated runtime.
So in this embed the pdf is being generated and coming to browser.But when I right click it is considering it as a html element not as a pdf.
Please help
-21519618 0The behavior you so beautifully demonstrated is by design (or lack of, if you will). You are right in part, the crazy_linker does resolve some of such issues (but not all of them). There is an easy but ugly workaround. Build a dummy libfcn_defined.so which only has T someMethod in its nm. Use it to link libfnc_undefined.so, using LD_LIBS. NDK will show a warning, but that's OK. LAoad the real libfcn_defined.so in your Java.
I have a server on our company intranet that runs JBoss. I want to send API calls to this server from my machine, also on the intranet, and get the resulting XML responses using JQuery.
I read the entry on Wikipedia but am confused how that applies to my situation, since our machines only have IP addresses, not domain names.
I have
My questions are:
Thanks!
-35676933 0 Laravel 4.2 / Mysql Json(Text) Column Elements Eager LoadI have 3 table matches, players , player_details
Matches row is =
1 | computer
Players row is =
1 | 1 | [{id:100},{id:102},{103}]
Players_Details row is =
100 | leonardo
102 | mark
103 | david
i want to eager loading with three table for example
Matches::with('players')->get();
how can i get matches with players and players_details eager loading.
i try too
Matches row is =
1 | computer | [{id:100},{id:102},{103}]
Matches::with('players.id')->get();
but not working anywhere i need help.
Sorry for my english i'm not english person, thanks for patience.
-37726390 0 Manually writing bmp image works for one resolution and is broken for otherI try to create bmp output image. According to bmp header structure this code looks correct. Bmp header structure was taking according to http://www.fastgraph.com/help/bmp_header_format.html But it produced valid bmp image only for resolution 500x500px. Whats wrong with code?
#include <cstdint> #include <fstream> struct BmpHeader { uint32_t mFileSize; // Size of file in bytes uint32_t mReserved01; // 2x 2 reserved bytes uint32_t mDataOffset; // Offset in bytes where data can be found (54) uint32_t mHeaderSize; // 40B int mWidth; // Width in pixels int mHeight; // Height in pixels short m_colorPlates; // Must be 1 short mBitsPerPixel; // We use 24bpp uint32_t mCompression; // We use BI_RGB ~ 0, uncompressed uint32_t mImageSize; // mWidth x mHeight x 3B uint32_t mHorizRes; // Pixels per meter (75dpi ~ 2953ppm) uint32_t mVertRes; // Pixels per meter (75dpi ~ 2953ppm) uint32_t mPaletteColors; // Not using palette - 0 uint32_t mImportantColors; // 0 - all are important }; int main() { uint32_t width = 2; uint32_t height = 2; std::ofstream bmp("1.bmp", std::ios::binary); BmpHeader header; bmp.write("BM", 2); header.mFileSize = uint32_t(sizeof(BmpHeader) + 2) + width * height * 3; header.mReserved01 = 0; header.mDataOffset = uint32_t(sizeof(BmpHeader) + 2); header.mHeaderSize = 40; header.mWidth = width; header.mHeight = height; header.m_colorPlates = 1; header.mBitsPerPixel = 24; header.mCompression = 0; header.mImageSize = 0; header.mHorizRes = 2953; header.mVertRes = 2953; header.mPaletteColors = 0; header.mImportantColors = 0; bmp.write((char*)&header, sizeof(header)); for (unsigned int y = 0; y<height; y++) { for (unsigned int x = 0; x<width; x++) { typedef unsigned char byte; byte bgrB[3]; bgrB[0] = 120; bgrB[1] = 120; bgrB[2] = 120; bmp.write((char*)&bgrB, sizeof(bgrB)); } } }
-36227877 0 A typical way of doing this uses the ANSI standard window functionrow_number():
select t.* from (select t.*, row_number() over (partition by idUser order by idUser) as seqnum from t ) t where seqnum = 1;
-17819464 1 Compiled binaries VS interpreted code in python I'm planning to use python to build a couple of programs to be used as services, run from PHP code later on. In terms of performance, which is faster, to compile the python code into a binary file using cx_freeze or to run the python interpreter each time I run the program?
Deployment environment:
OS: Arch Linux ARM
Hardware: Raspberry Pi [700MHz ARMv6 CPU, 256MB RAM, SD Card filesystem]
Python Interpreter: Python2.7
App calls frequency: High
I let my users to change any attribute(location, color, and ...) of every element in a page before printing.
I'm looking for a way which user can store the new style sheet and restore it anytime later?
I've tried to parse element.style, but it doesn't return an array! Also $(element).css() doesn't work without any argument!
Here is the pseudo code:
for i=1 to n for j=1 to n for k=1 to j x = x+1 and I have to calculate these two thing (i) count it precisely (ii) find it big-O
in (i), my final answer is n^4+2n^3+5n^2+4n+2. in (ii), because there are three loop, so it's O(n^3);
It seem that there must be an error either (i) or (ii) since (i) raise to the power 4, and the big-O is just 3.
Here is my step when counting the iteration:
for(i=1; i <=n; i++) count as 1+(n+1)+n which is (2n+2).
So, (2n+2)+n(2n+2)+n(4+6+8+...+2n+2)+n^2(1+2+3+...+n)(2) which finally come out with n^4(see the last term, sum of AS * n).
-29295593 0Here i Used Content Dialog Box.
Button_Click Code
ContentDialog msg = new ContentDialog(); msg.Content = "Data Saved Successfully"; msg.ContentTemplate = Application.Current.Resources["ContentDialogContentTemplate"] as DataTemplate; msg.PrimaryButtonText = CommonDisplayMessages.DisplayMessage_Yes; await msg.ShowAsync();
-35548217 0 packaging options based on product flavor in gradleI m using packaging options to exclude some libs. Is it possible to have packaging options based on product flavor. For example -
android { productFlavors { flavorDimensions 'models' S2 { flavorDimension 'models' minSdkVersion 22 .... } S6 { flavorDimension 'models' minsdkversion 22 .... } } packagingOptions { exclude 'lib/armeabi/libs2.so' exclude 'lib/arm64-v8a/libs6.so } } Now in above code, I want to exclude only 'lib/armeabi/libs2.so' in apk generated for s6 flavor and want to exclude only 'lib/arm64-v8a/libs6.so' in apk generated for s2 flavor
How can we achieve this.
-39588437 0I think the pins 12 and 24 (BOARD numberingscheme) are hardware PWM capable, hence more accurate.
-19154549 0-
$stmt=$this->$dbh->beginTransaction(); Should probably be something like
$this->dbh->beginTransaction(); $sql = ... $stmt = $this->dbh->prepare($sql); Replace ... with your insert query.
Yes, you can basically do the same thing using package name com.facebook.katana with the same action (ACTION_VIEW) and using extra Intent.EXTRA_TEXT to set the text.
Sure, just add view-source: in front of the URL.
view-source:http://stackoverflow.com/posts/edit/145419 Will show the source of this page for instance - try it in the address bar.
-20284963 0I come from Oracle background; but I like this beautiful solution.
Order the records in CONTACTS by COMPANY_ID, assign each record a unique number, find the minimum and maximum number given to each company, and then, select their two corresponding records:
WITH T AS ( SELECT ROWNUM RN, C.* FROM (SELECT CONTACTS.COMPANY_ID, COMPANY.COMPANY_NAME, CONTACTS.NAME, CONTACTS.TEL FROM CONTACTS, COMPANY WHERE CONTACTS.COMPANY_ID = COMPANY.COMPANY_ID ORDER BY CONTACTS.COMPANY_ID ) C ), R AS ( SELECT COMPANY_NAME, MIN(RN) MINR, MAX(RN) MAXR FROM T GROUP BY COMPANY_NAME ) SELECT R.COMPANY_NAME, T1.NAME NAME1, T1.TEL TEL1, T2.NAME NAME2, T2.TEL TEL2 FROM R, T T1, T T2 WHERE R.MINR = T1.RN and R.MAXR = T2.RN
-3144418 0 Signal for Entire Row Selection in QTableWidget Is there a signal for when an entire row in the QTableWidget has been selected by pressing the buttons that are stacked on the left? I would like that to enable some functionality, but am not sure how?
Thank you in advance!
-10019832 0You could have Previous/Next buttons quite easily. I would place them outside the TabControl (so you're not duplicating them) and then have their handlers simply increment or decrement the SelectedIndex property of the TabControl.
EDIT: Are you aware that you can make tabs not look like tabs? You can set the Appearance property to TabAppearance.Buttons, for instance, and the "tabs" will instead be rendered as buttons, which would make the tab row look more like a breadcrumb control.
You can also use Panels overlapped on the Form, and call the BringToFront() method of the Panel representing the Page you want.
-24300429 0You can use .closest() to find parent then check its length
Code
$(document).on("click", ".Topping-details", function () { var ordersdiv = $(this).closest('#ordersdiv').length; var activateUiHTML = $(this).closest('div.activateUiHTML').length; if (ordersdiv) { alert('Under ordersdiv'); } if (activateUiHTML) { alert('Under activateUiHTML'); } });
-37218769 0 Get string between parts I am having a string:
c(\\", \" \", \" \", \"\", \"\", \"Object:\", \"\", \"\", NA, \"vlg. numb 2\", \"\", NA, NA, NA, NA, \"This: \", NA, \"Date\r\n(21.03.1961)\", \"K..\r\nRom (28.04.2012)\", NA, NA, \"test.test@yahoo.de\", NA, \"Italy, Rome\", NA, \"UP, Ö\", \"BP, \", NA, NA, NA, NA, NA)" I would like to get the string numb 2, which is between vlg.numb 2\"
I tried:
=MID(A18;FIND("vlg.";A18;1)+7;FIND("/object";A18;1)-FIND("\";A18;1)-8) However, I only get #VALUE back.
Any suggestions what I am doing wrong?
-29265555 0 managed_file form element doesn't render correctlyI have a simple managed file form element that is the only element in my form. It looks like this:
$form['upload'] = array( '#type' => 'managed_file', '#title' => t('Select a YML file'), '#progress_message' => t('Please wait...'), '#progress_indicator' => 'bar', '#description' => t('Click "Browse..." to select a file to upload.'), '#required' => TRUE, '#upload_validators' => array('file_validate_extensions' => array('yml txt docx')), '#upload_location' => $upload_dest, ); When I render the form using the drupal_get_form callback in hook_menu I get a perfectly formed managed_file upload field with the browse and upload buttons. Things change when I decide I want to add a table of information underneath the form. This requires building a table using theme functions then adding that to the form by rendering the form and appending the table. I create my table and add it to the form:
$rows = array(); foreach($yml_files as $yml_file){ $rows[] = array($yml_file->uri, $yml_file->filename); } $output = drupal_render($form['upload']); $output .= theme('table', array('header'=>$header, 'rows'=>$rows)); return $output; When I generate the form using drupal_render, I get the nice help text, but no upload form. The table renders fine in both scenarios and I'm not seeing any errors.
If Drupal uses drupal_render to render its forms why would the form look different in the second scnenario? Is there a way to get the entire form? I've tried a variety of ways of passing the form and using dpm to print the form at various stages and I'm not sure where to go from here.
Standard file upload fields render correctly as do other form elements. It seems to be limited to the managed_file element.
-26447424 0 How to re-create jQuery data-table on ajax response?I am creating a jQuery data-table based on some search criteria using ajax call & response. I am able to create the table. But when I try to search again, I am getting the below error.
DataTables warning: table id=sendBulkEmailTable - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3
I guess I cannot re-create the data table again. Can somebody provide a solution to my problem, how can I refresh the data of my table on next search.
jQuery ajax call I wrote is:
$("#tableId").dataTable({ "data": res.ajaxResult.data, "columns": [ { "data": "data1" }, { "data": "data2" }, { "data": "data3" }, { "data": "data4" }, { "data": "data5" } ] });
-2827777 0 stop user changing tabs till app loads fully im my app i have had to thread the loading of xml so the app loads and does not get kicked out by the os , but that also means that when the app loads and , the user selects one of the tabs that is still loading, it crashes.
is there any way i can stop them changing tabs till the app is fully loaded?
Thanks
-26894976 0 Taking Sample in SQL QueryI'm working on a problem which is something like this :
I have a table with many columns but major are DepartmentId and EmployeeIds
Employee Ids Department Ids ------------------------------ A 1 B 1 C 1 D 1 AA 2 BB 2 CC 2 A1 3 B1 3 C1 3 D1 3 I want to write a SQL query such that I take out 2 sample EmployeeIds for each DepartmentID.
like
Employee Id Dept Ids B 1 C 1 AA 2 CC 2 D1 3 A1 3 Currently I am writing the query,
select EmployeeId, DeptIds, count(*) from table_name group by 1,2 sample 2 but it gives me total two rows.
Any help?
-17888925 0To unit test a code, that piece of code needs to be testable.
To unit test a method, what we do is pass in some known input and check it is returning expected result or if we are having correct side effect.
Now if you directly take your input inside your method, it is not very testable. It has two parts, reading the input and processing it. If the assert in your test fails, you don't know which step failed. Unit test should be aimed towards testing a unit or single responsibilty of a code.
To make it testable, read the input in main method and pass it to another method for processing (also common notion of object oriented programming), and test the second method with known parameters.
-15848901 0The whole point of using this plugin is to eliminate the need to generate images.
Instead, you can use MathJax, a free and open source JavaScript display engine to convert this formula back to an image.
-8984537 0Yes, it does. The javadoc says:
Closes this input stream and releases any system resources associated with the stream.
And the wrapped stream is definitely such a system resource.
Moreover, GZIPInputStream is a FilterInputStream, and the FilterInputStream javadoc says:
-12549601 0 Clickatell alternative SMS-Gateway?Closes this input stream and releases any system resources associated with the stream. This method simply performs in.close().
We're just about to go live but Clickatell seems to be problematic. Billing AND Server issues!!
A quick google search shows a long record of problems.
They did however made good impression at first but now we're simply not sure - they don't seem to be stable!
So, which reliable SMS gateway would allow me to send simple English SMS to Israel (programmatically through an HTTP API)?
Saw so far:
-14332143 0 Spring MVC - How to display blank textbox when integer value is zeroIm using spring, hibernate, java, and jsp. My problem is that when the integer value is zero it displays 0 in my textbox. I want to display only empty string but Idk how to do it. Please help.
In my jsp:
<form:form method="POST" commandName="division"> ... ... <form:input path="number"/> </form:form> In my domain:
/** * Get the number of the division. * @return The number. */ @Column(name = "NUMBER") public int getNumber() { return number; } /** * Set the number of the division. * @param number The division number. */ public void setNumber(int number) { this.number = number; }
-22987586 0 Not able to select an option from the dropdown leading to ElementNotVisibleException import java.util.List; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.Select; public class DellDropdown { public static void main(String[] args) { WebDriver driver=new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); driver.get("http://www.dell.com/"); WebElement dropdown=driver.findElement(By.xpath("//select[@class='para_small']")); Select select=new Select(dropdown); select.selectByIndex(5); List<WebElement> options=select.getOptions(); for(int i=0;i<options.size();i++) { options.get(i).getText(); } } } I am getting the ElementNotVisibleException on at line select.selectByIndex(5), can someone help me in this regard?
-17516908 0You have to create provisioning profiles for adhoc and distribution. See http://developer.apple.com/library/ios/ipad/#documentation/ToolsLanguages/Conceptual/YourFirstAppStoreSubmission/TestYourApponManyDevicesandiOSVersions/TestYourApponManyDevicesandiOSVersions.html Under 'create an AdHoc provisioning profile'
-4924945 0The key point is to loop thru the inputs and add their values.
var totalInput = 0; $("input").keyup(function () { //zero out the global var totalInput totalInput = 0; $("input").each(function(){ //for each input, add value to global totalInput totalInput += $(this).val() }); //setup price var item_price = parseFloat("50.25"); //display price times totalInput $("h3").text(totalInput * item_price); });
-22764343 0 Javascript not drawing on canvas Over here, I am trying to paint image on a canvas (the image is a tile sheet). However, I have checked, the loop works just fine, the code is being executed, the cases are correct (I tested it by logging text to console) however, nothing is being painted on the console. The image is being loaded just fine.
I really don't know what exactly causing this problem, there is no syntax error on the console. The following is my code, It might take a little time for anyone to analyse it, but any help is greatly appreciated.
Here is the image "monsterTileSheet.png" as defined in the script below:

var canvas = document.querySelector("canvas"); var drawingSurface = canvas.getContext("2d"); var image = new Image(); image.src = "monsterTileSheet.png"; image.addEventListener("load", loadHandler, false); var spaceInc = 0; // increment counter var inc = 5; // increment between the tiles var imgSize = 80; var map = [ [0, 0, 1, 0], [0, 0, 0, 0], [0, 0, 0, 0] ]; function adjustCanvas() { canvas.height = (map.length * imgSize) + (map.length * inc); canvas.width = (map[0].length * imgSize) + (map[0].length * inc); } var monster = { SIZE: 80, frames: 5, hiding: 0, jumping: 1, state: this.hiding, sourceX: 0, sourceY: 0, currentFrame: 0, COLUMNS: 3, start: function () { if (this.currentFrame < this.frames) { this.sourceX = Math.floor(this.currentFrame % this.COLUMNS) * this.SIZE; this.sourceY = Math.floor(this.currentFrame / this.COLUMNS) * this.SIZE; this.currentFrame++; renderImage(); } else { window.clearInterval(interval); this.sourceX = 0; this.sourceY = 0; this.currentFrame = 0; } } }; var x = 0; var y = 0; function renderMap() { for (var i = 0; i < map.length; i++) { for (var j = 0; j < map[0].length; j++) { switch (map[i][j]) { case 0: drawingSurface.drawImage(image, 0, 0, monster.SIZE, monster.SIZE, (j * imgSize) + spaceInc, i * imgSize, imgSize, imgSize); if (spaceInc >= (map[0].length - 1) * inc) { // reset increment spaceInc = 0; } else { spaceInc += inc; } console.log("Case 0"); break; case 1: x = map[i][j] * monster.SIZE y = map[j] * monster.SIZE; stGame(); console.log("Case 1"); break; default: console.log(j); break; } } } } function stGame() { interval = window.setInterval(function () { monster.start(); }, 300); } function loadHandler() { adjustCanvas(); renderMap(); } function renderImage() { drawingSurface.drawImage(image, monster.sourceX, monster.sourceY, monster.SIZE, monster.SIZE, x, y, monster.SIZE, monster.SIZE); }
-37473122 0 I think your approach is fine, it gets the job done.
I'm not too sure what you're asking by saying how should you loop the two output statements, followed by if it should be in the main method. From what I understand, and by looking at your code, running this input loop is perfectly fine from the main class. The do-while is fine although I'd move the first 'introductory' output outside the loop so you don't see it every time the loop reiterates. Also, I notice you're not actually calling/instantiating the Store class in your main method, there's no data being added to the Store class for when it iterates through the accounts ArrayList.
As far as the answer that stated a more "modern" approach, I think the for loop you used is fine. I think the person was referring to the for-each loop. It doesn't really matter how you loop through it with the little amount of data you have.
There's some error in the logic for that loop. The getHighestCustomerTotal() is referencing an empty accounts ArrayList. You declared an ArrayList within the Store class and tried to loop through it but it's empty unless you called the addAccount() method from your main method at some point, so you'd need some error checking on that.
There are multiple syntax errors in your query:
let clauses have to be part of a FLWOR expression, which always ends with a return clause.if cannot be used without then and else and does not use curly braces.<res> needs a matching closing tag </res> at the end of the query.The corrected query looks like this:
declare variable $datesList := ( "2013-01-01-00.30.00", "2013-01-01-01.00.00", "2013-01-01-01.30.00", "2013-01-01-02.00.00", "2013-01-01-02.30.00", "2013-01-01-03.00.00", "2013-01-01-03.30.00", "2013-01-01-04.00.00" ); <res>{ let $mcId1 := count(//ZZQAD2UsageTransactionSVC/usagePeriods/usagePeriodsList/SQs/SQsList[1]/mL) let $mcId2 := count(//ZZQAD2UsageTransactionSVC/usagePeriods/usagePeriodsList/SQs/SQsList[2]/mL) return if($mcId1 = 8) then ( for $mlList in //ZZQAD2UsageTransactionSVC/usagePeriods/usagePeriodsList/SQs/SQsList[1]/intervals/mL return if($mcId1 > $mcId2) then <text>true</text> else <text>false</text> ) else () }</res>
-29946806 0 How can I use powershell to retrieve AD distinguishedName from the employeeID only? What I'm trying to do is run a script which compares employee IDs from a CSV file to AD, and if they're NOT in the CSV but ARE in AD they should: - be disabled - have a termination date comment added to the description - move to a different OU
The script I'm using below disables the account and adds the comment, but I get an error when it tries to move to different OU. The error is: Move-ADObject : Cannot find an object with identity: 'name1test' ...
I've tried a lot of things to adjust the script to get the samAccountName or distinguishedName using only the employeeID, but I've had no luck. Any ideas?
Import-Module ActiveDirectory $TargetOU = "ou=Term,ou=Logins,dc=domain,dc=com" $Date = Get-Date -Format MM-dd-yyyy $Users = Import-Csv c:\ADTerm.csv | Select-object -ExpandProperty EmployeeID $Terms = Get-ADUser -filter * -SearchBase "ou=Test,ou=Logins,dc=domain,dc=com" -Properties EmployeeID | Where-Object{$_.EmployeeID -and ($Users -notcontains $_.EmployeeID)} ForEach ($Term in $Terms) { # Retrieve user sAMAccountName. $Name = $Term.sAMAccountName # Disable the user. Set-ADUser -Identity $Name -Enabled $False -Description "Terminated - $Date" # Move the user. Move-ADObject -Identity $Name -TargetPath $TargetOU }
-2649447 0 Using MembershipCreateStatus in MVC How can I use the MembershipCreateStatus in my controller below to identify errors?
My controller below creates a new user but I would like to catch any errors from CreateStatus and add the error to my modelstate.
I keep getting errors for status below.
[HttpPost] public ActionResult CreateUser(user UserToCreate) { if (ModelState.IsValid) { // TODO: If the UserToCreate object is Valid we'll //Eventually want to save it in a database MembershipCreateStatus status; MembershipService newMembershipService = new MembershipService(); MembershipCreateStatus newUser = newMembershipService.CreateUser(UserToCreate.Username, UserToCreate.Password, UserToCreate.Email,out MembershipCreateStatus **status**); if (newUser == MembershipCreateStatus.Success) { return RedirectToAction("Index", "Home"); } else { ModelState.AddModelError(createStatus); return Redirect("/"); } } //Invalid - redisplay form with errors return View(UserToCreate); }
-28707049 0 what are some techniques for DRY-ing up macros in Sweet.js? let's say i have these two macros which are identical except for the macro name:
macro h1 { case {$name ($x (,) ...)} => { letstx $nameVal = [makeValue(unwrapSyntax(#{$name}), null)] return #{React.createElement($nameVal, $x (,) ...)} } } macro h2 { case {$name ($x (,) ...)} => { letstx $nameVal = [makeValue(unwrapSyntax(#{$name}), null)] return #{React.createElement($nameVal, $x (,) ...)} } } what are my options for code reuse here? can i have a macro generate a macro?
or could i minimally place the body portion (beginning with letstx...) in it's own 'internal' macro?:
I am a total novice on android programming and is relying on threads/solutions by veteran android programmers to enhance my application. For now I have 2 problems regarding our android app:
How and where could our users send their current location? What ways can we store the location of our users and use it on our application?
-36844757 0 Rails Streamio FFMPEG taking a screenshot of the movie and upload with carrierwaveI have got a Form where I can upload a movie. Its uploaded with carrierwave.
In this process I want to Make a screenshot of the movie while uploading.
How can I do this with Streamio FFMPEG.
My code Looks like this at the moment.
#Laedt ein Video hoch def uploadMovie @channels = Channel.all @vid = Movie.new(movies_params) @channel = Channel.find(params[:channel_id]) @vid.channel = @channel if @vid.save flash[:notice] = t("flash.saved") render :add else render :add end end Do I have to do this in controller method or in the carrierwave uplaoder?
Update: I tried it this way:
if @vid.save flash[:notice] = t("flash.saved") movieFile = FFMPEG::Movie.new(@vid.video.to_s) screenshot = movieFile.screenshot("uploads/screenshot", :seek_time => 10) render :add else But then I got tis error:
s3.amazonaws.com/uploads/movie/video/6/2016-04-24_16.26.10.mp4' does not exist
-4276758 0 Given that sqlite only supports UTF-8 and UTF-16 as the encodings, you would have noticed if Android would create databases in something other than UTF-8. sqlite3_open defaults to create the database in UTF-8, and that is what Android is likely to use.
-19503112 0 PhantomJS is a headless (GUI-less) WebKit with JavaScript API. It has native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG. This tag deals specifically with PhantomJS version 1.9. -39304358 0Yes, you can do it that way. If it's not a hard work, I'll include the database load on the Perl step. This probably avoids to handle an intermediate file, but I don't know if it's a viable task on your project.
In order to use RabbitMQ, I'll recommend you the AnyEvent::RabbitMQ CPAN module. As the documentation establishes, You can use AnyEvent::RabbitMQ to:
This makes it easier when defining method return types such as this:
class A<B extends A<B>> { public B getMe(){ return (B) this; } } This tells Java compiler that you are in getMe() method returning a subclass of class A.
class C extends A<C> { } C c = new C(); c.getMe(); //returns C
-13617532 0 Indexing during assignment Say I have this sample data
A = 1.0000 6.0000 180.0000 12.0000 1.0000 5.9200 190.0000 11.0000 1.0000 5.5800 170.0000 12.0000 1.0000 5.9200 165.0000 10.0000 2.0000 5.0000 100.0000 6.0000 2.0000 5.5000 150.0000 8.0000 2.0000 5.4200 130.0000 7.0000 2.0000 5.7500 150.0000 9.0000 I wish to calculate the variance of each column, grouped by class (the first column).
I have this working with the following code, but it uses hard coded indices, requiring knowledge of the number of samples per class and they must be in specific order.
Is there a better way to do this?
variances = zeros(2,4); variances = [1.0 var(A(1:4,2)), var(A(1:4,3)), var(A(1:4,4)); 2.0 var(A(5:8,2)), var(A(5:8,3)), var(A(5:8,4))]; disp(variances); 1.0 3.5033e-02 1.2292e+02 9.1667e-01 2.0 9.7225e-02 5.5833e+02 1.6667e+00
-14562363 0 Selenium web driver not able to close firefox instance if a Test cases is failed i folks, i am using junit with selenium web driver 2.28. the problem is if i run a successful test case the web drives is able to close the firefox instance, but when a test case fails the selenium web driver is not able to close the firefox. i am using FF 15.0.1 with selenium-server-standalone-2.28.0.jar. please respond thanks Sahil
private void startWebdriver() throws UIException{ //2) Prevent re-use. if(UIHandlerWD.this.profile == null) throw new UIException( UIException.Code.UI, "Webdriver instance cannot be instantiated." ); //3) Configure Selenium Webdriver. if (this.profile.browserType.equalsIgnoreCase("*firefox")){ FirefoxProfile fProfile = new FirefoxProfile(); // profile.SetPreference("network.http.phishy-userpass-length", 255); fProfile.setAcceptUntrustedCertificates(true); DesiredCapabilities dc = DesiredCapabilities.firefox(); dc.setJavascriptEnabled(true); dc.setCapability(FirefoxDriver.PROFILE, fProfile); //this.webdriver = new FirefoxDriver(dc); this.webdriver = new FirefoxDriver(dc); } else if (this.profile.browserType=="INTERNETEXPLORER") this.webdriver = new InternetExplorerDriver(); else throw new UIException( UIException.Code.UI, "Unknown browser type '" + this.profile.browserType +"'." ); //4) Start Webdriver. this.webdriver.get(this.profile.getURL().toString()); this.webdriver.manage().timeouts(). implicitlyWait(5, TimeUnit.SECONDS); this.webdriver.manage().timeouts(). pageLoadTimeout(this.profile.timeout, TimeUnit.SECONDS); } void stopWebdriver() { if(this.webdriver != null){ try{ Thread.sleep(5000); } catch (Exception e) { // TODO: handle exception } this.webdriver.close(); } this.webdriver = null; this.profile = null; }
-35124826 0 How to insert CheckBoxList Checked Item to Database I have a check box list, and I want to insert its Checked items to Database; I used this code:
for (int i = 0; i < checkBox_service.Items.Count; i++) { if (checkBox_service.Items[i].Selected == true) { strcheck += "" + checkBox_service.Items[i].ToString() + ","; } } In Database it is displaying
System.Web.UI.WebControls.CheckBoxList in CheckBox field instead of Selected item. All other fields are having correct data as per entered... I couldn't find any error, please guide me...
-34142422 0 How do I add fields to log4j2's JSON logsSay I have a standard JSON log as in the example in the docs (below)
{ "logger":"com.foo.Bar", "timestamp":"1376681196470", "level":"INFO", "thread":"main", "message":"Message flushed with immediate flush=true" } Now I want to add custom info to this log like so:
{ "logger":"com.foo.Bar", "timestamp":"1376681196470", "level":"INFO", "thread":"main", "message":"Message flushed with immediate flush=true", "extrainformation":"Some very important stuff I need to include", "extrainformation2":"Some other very important stuff I need to include" } Is there a way to do this? The docs don't seem to mention anything about adding properties to the log object. Do I need to make a custom layout or programmatically add fields or what?
-23647244 0 Google dictionary as my databaseCan I use Google dictionary as my database for the application developed in Php ? I want to create an application which will pop up meaning of each word,displayed in output window. So I thought that it will be useful if I use Google dictionary as my database,from there I can fetch meaning of each word.
I don't know whether my question is meaningful. Is it possible?
-19152083 0Python's print statement displays the string representation of an object. So if it prints as 'h1' (without the quotes), you could try testing if that is the object's string representation :
if str(h) == 'h1': servpro() else: hostpro()
-129115 0 You can use SQL Profiler to find that out.
EDIT: If you can stop the app you are running, you can start SQL Profiler, run the app and look at what's running including stored procedures.
-20647178 0 Winston logging to multiple file logs without duplicating log messagesHere is my Winston config:
winston = require 'winston' logger = new winston.Logger transports: [ new winston.transports.File name: 'file#debug' level: 'debug' filename: '/tmp/debug.log' new winston.transports.File name: 'file#error' level: 'error' filename: '/tmp/error.log' ] Currently when I log:
logger.error 'error' # both logs logger.debug 'debug' # on debug log What I want is the errors to only go to error.log, and debug messages to only go to debug.log. How can i do that? Searched the File transport options but didnt find anything like that.
-7941162 0Does your scheme target dropdown list show "iOS Device" or does it show the "name" of your iPod Touch (something like "jons ipod touch"):

If it shows "iOS Device", that means your iPod isnt recognized by xcode and you may need to enable the device for developing by clicking "Use For Development" like so:

If _disable_f2 is being given two arguments, let it have what it wants.. try below... :)
from Tkinter import * class App: def _disable_f2(self, master): if self.filt.get() == 'bandpass': self.filter_menu.configure(state='normal') else: self.filter_menu.configure(state='disabled') def __init__(self, master): self.f2var = StringVar() self.f2var.set('5.0') self.f2_entry = Entry(master, textvariable=self.f2var, width=5) self.f2_entry.pack() self.filt = StringVar() self.filt.set('bandpass') self.filter_menu = OptionMenu(master, self.filt, 'bandpass', 'lowpass ', 'highpass', command=self._disable_f2) self.filter_menu.pack(ipadx=50) root = Tk() app = App(root) root.mainloop()
-6457620 0 Convert a string to datetime Possible Duplicate:
How can I convert a string into datetime in .NET?
i have a string in the following format "15/03/2046". how can convert this string to a DateTime object?
My problem is when i do Convert.ToDateTime("15/03/2046") i get an exception.
when i do Convert.ToDateTime("03/03/2046") every thing works fine.
so i guess that i have to specify the format somehow while converting....
I am learning to create RESTful services using WCF. There are a myriad of options to choose from. I am confused as to what should i use. 1.)REST Starter kit - Seems to be obsolete 2.)WCF WEbhttp service 3.)WCF Web API 4.)ASP.NET web api
I dont want to use ASP.NET MVC to build RESTFul services. I dont like the idea of services being in the same solution structure of a presentation layer. So what is it i should use?ASP.NET web api seems to be having going down the MVC route where the requests are handled by a controller which i feel does not fit into a "Service" terminology.
-18125809 0If you want the TimePicker to be correctly initialized with the current time in 24h format use the following:
import java.util.Calendar; timePicker.setIs24HourView(true); timePicker.setCurrentHour(Calendar.getInstance().get(Calendar.HOUR_OF_DAY)); Otherwise, due to Android bug, the picker will start with an incorrect hour (2 instead of 14 etc).
-24522005 0if I understand your question correctly,
MyProject.Properties is like a container for your project to manage all your static references (language files/images/data connection etc...) that independent need to your project. it is like pre-defined namespace for each of your project so that you can easily know where you looking for your static resources.
-11603209 0Do you mean to return it as a 32-bit integer?
unsigned int get_color(cv::Mat img, float x, float y) { int i = x*img.cols; int j = y*img.rows; unsigned char R = img.ptr<unsigned char>(j)[3*i]; unsigned char G = img.ptr<unsigned char>(j)[3*i+1]; unsigned char B = img.ptr<unsigned char>(j)[3*i+2]; return (R << 16) | (G << 8) | B; } Or perhaps you want to return it as floats in which case you need to do the following
struct FloatColour { float r; float g; float b; }; float get_color(cv::Mat img, float x, float y) { int i = x*img.cols; int j = y*img.rows; unsigned char R = img.ptr<unsigned char>(j)[3*i]; unsigned char G = img.ptr<unsigned char>(j)[3*i+1]; unsigned char B = img.ptr<unsigned char>(j)[3*i+2]; FloatColour retCol; retCol.r = R / 255.0f; retCol.g = G / 255.0f; retCol.b = B / 255.0f; return retCol; }
-31406320 0 Modal window with Angular (UI-Router / Directive) I have spent some time now looking into a generic way of controlling a modal window with AngularJS and none of the proposed options are anywhere near 'good' solution.
I found this demo, however the downside of that is you have to manually manage and store the state of the modal and cross-scope update it:
scope.$parent[attrs.visible] = true; Also if you had to add more functionality like actually adding an item with a popup that would involve even more ugly code on the parent page scope.
This is the official guide on how to use modals with ui router.
This however is using ui.bootstrap.modal
My question is, is there any simple and elegant solution to what is quite frankly a very simple problem...
Something like this for example:
.state('popup', { url: '/item/add/', views: { 'popupView': { templateUrl: "/myPopup.html", controller: "myPopupController" } }, type: 'modal' }) And things like close, redirect, submit, all are handled in the myPopupController.
I am not seeking an explanation of why the examples are above are as they are, or how I should be using them. I am simply looking if anyone has come up with a better solution.
-33328442 0I have done this job,I have just edited jquery
$(".left-menu-button").click(function() { $(this).parent().children('.left-menu-content').toggle("slow", function() { }); });
-31890607 0 If you turn stop on errors on, then interrupting it, even with ctrl+c, brings you to the place where it was executing and you have the whole workspace available:
dbstop if error
-21332719 0 Hide on-screen menu bar android from code Is there a way to hide on-screen menu bar in an android app from code?
https://www.dropbox.com/s/cbs7rbac07rs5ks/Screenshot%202014-01-24%2014.24.48.png
-6554732 0marcos is right, but you have a couple other options as well. First of all, there is an either/or:
assertThat(result, either(is(1)).or(is(2))); but if you have more than two items it would probably get unwieldy. Plus, the typechecker gets weird on stuff like that sometimes. For your case, you could do:
assertThat(result, isOneOf(1, 2, 3)) or if you already have your options in an array/Collection:
assertThat(result, isIn(theCollection)) See also Javadoc.
-35819031 0A simple way to do this is to send a response back to the client in the form of html:
response.setContentType("text/html"); PrintWriter out = response.getWriter(); //Returns a PrintWriter object that can send character text to the client out.println("<h1>Registered successfully</h1>"); For more information, go through these Tutorials
If you dont want the page to reload then you should:
now you can set the result of response accordingly in your specific div.
See this answer for more information on how to use Ajax with Servlets.
Why not use a ListView instead? It gives you better control when using an MVC model where there's a dataset tied to a View. So you could have a class that extends BaseAdapter. This class binds your data to the View and this class also has a method: notifyDataSetChanged() which is what should solve your problem.
You may find notifyDataSetChanged example and customListView helpful.
Let me know if you need any help further.
-21127641 0You need to remove the & operator when passing the client variable to the lpParameter param of CreateThread():
//CreateThread(..., &client, ...); CreateThread(..., client, ...); SendToPeer() is expecting to receive a Peer* pointer but you are actually sending it a Peer** pointer instead.
<%= i.awards.sum(:points) %> For for the sum of all points from all recipes:
<%= @user.recipes.map { |r| r.awards.sum(:points) }.sum %> Although it might be sensible to do this calculation within the model. You'll remove a lot of duplication that way if you use it in more than one view.
UPDATE:
As per the comments below, you could also ask the DB to calculate the sum for you:
<%= @user.recipes.joins(:awards).sum('awards.points') %>
-3344788 0 There are a lot of other conditions that I've been hearing about with non-relational systems vs relational. I prefer this terminology over sql/no-sql as I personally think it describes the differences better, and several of the "no-sql" servers have sql add-ons, so anyway.... what sort of concurrency pattern or tranaction isolation is required in your system. One of the purported differences between rel and non-rel dbs is the "consistent-always", "consistent-mostly" or "consistent-eventually". Relation dbs by default usually fall into the "consistent-mostly" category and with some work, and a whole lot of locking and race conditions, ;) can be "consistent-always" so everyone is always looking at the most correct representation of a given piece of data. Most of what I've read/heard about non-rel dbs is that they are mainly "consistent-eventually". By this it means that there may be many instances of our data floating around, so user "A" may see that we have 92 widgets in inventory, whereas user "B" may see 79, and they may not get reconciled until someone actually goes to pull stuff from the warehouse. Another issue is mutability of data, how often does it need to be updated? The particular non-rel db's I've been exposed to have more overhead for updates, some of them having to regenerate the entire dataset to incorporate any updates.
Now mind, I think non-rel/nosql are great tools if they really match your use case. I've got several I'm looking into now for projects I've got. But you've got to look at all the trade offs when making the decision, otherwise it just turns into more resume driven development.
-17998503 0 Accessing variables across different scopes in Javascript & YUI 3I'm new to YUI 3 and YUI in general. I'm trying to pass data between classes and methods.
In this example I'm using the gallery-sm-treeview plugin to build a file tree. There's a class named TreeView to initialize and render the tree. There's another class named MenuBar where I want to access some of the plugin-specific methods through TreeView's getter method.
However, the variable var treeview inside the YUI().use() scope is of course not accessible from outside. How to do it?
YUI.add('treetool.TreeView', function(Y) { Y.treetool.TreeView = Class.extend({ init : function(elementId) { YUI({ gallery: 'gallery-2013.06.20-02-07'}).use('gallery-sm-treeview', function (Y) { // Create a new TreeView with a few nodes. var treeview = new Y.TreeView({ // Tell the TreeView where to render itself. container: elementId, // Populate the treeview with some tree nodes. nodes: [ {label: 'Node 1'}, {label: 'Node 2', children: [ {label: 'Child 1'}, ] }); // Render the treeview inside the #treeview element. treeview.render(); }); }, getSomeData : function () { return treeview.getSelectedNodes(); } }); }, '0.0.1', { requires : [ 'jquery' ] }); and
YUI.add('treetool.MenuBar', function(Y) { Y.treetool.MenuBar = Class.extend({ init : function(treeObj) { var someData = treeObj.getSomeData(); }, }); }, '0.0.1', { requires : [ 'jquery' ] });
-10421426 0 Problem since solved. I was given the answer by Aaron Heckmann over on the mongoose Google Group:
Always declare your child schemas before passing them to you parent schemas otherwise you are passing undefined.
SubCommentSchema should be first, then Comment followed by BlogPost.
After reversing the schemas it worked.
-39385940 0^[a-zA-Z0-9]+(?:\.?[\w!#$%&'*+/=?^`{|}~\-]+)*@[a-zA-Z0-9](?:\.?[\w\-]+)+\.[A-Za-z0-9]+$ No .. and at least 1 . and 1 @.
Also starts/ends with letters/numbers.
The ^ (start) and $ (end) were just added to match a whole string, not just a substring. But you could replace those by a word boundary \b.
An alternative where the special characters aren't hardcoded:
^(?!.*[.]{2})[a-zA-Z0-9][^@\s]*?@[a-zA-Z0-9][^@\s]*?\.[A-Za-z0-9]+$
-35081638 0 How to show same video in two VideoViews simultaneously I'm working with VideoView and I'm trying to show same video in two Videoviews like this application
I'm following this link to show the video in two VideoViews but I'm getting delay in both audio and video on both videoviews so please help me to solve this problem. I need to play the video at the same time without any delay
Thank you..
-6451581 0 PHP Login application - Check if username already exists when creating a new userThe title tells pretty much everthing, that needs to be said. I'm having a registration code looking like this:
I wan't it to check, if the username entered already exists, if it does - write and $errMsg = ""; and echo it out later.. I hope you can help me, thanks.
if(isset($_POST['username']) && isset($_POST['password']) && isset($_POST['name']) && isset($_POST['last_name']) && isset($_POST['company'])){ if($username === '') { $errMsg = "Du skal udfylde brugernavn"; } elseif($password === ''){ $errMsg = "Du skal udfylde password"; } elseif($name === ''){ $errMsg = "Du skal udfylde navn"; } elseif($last_name === ''){ $errMsg = "Du skal udfylde efternavn"; } elseif($company === ''){ $errMsg = "Du skal udfylde firma"; } $sql = ("SELECT * FROM members WHERE username ='$username'"); $result = mysql_query($sql) or die('error'); $row = mysql_fetch_assoc($result); if(mysql_num_rows($result)) { $errMsg = 'Brugernavn findes, vælg et andet.'; } else { $sql = ("INSERT INTO members (username, password, name, last_name, company, salt)VALUES('$username', '$password', '$name', '$last_name', '$company', '$salt')")or die(mysql_error()); if(mysql_query($sql)) echo "Du er oprettet som profil."; } }//End whole if
-18601663 0 Maybe this link RubyTest#165 will fix the error.
-21634124 0 ibeacon powered on as opposed to enter or leaving regionI have been playing around with various test apps that detect when the device enters or leaves the iBeacon's region but my question is are there any apps that will detect when a beacon is turned on?
The reason I ask is that if I sit in the same room as my iPhone and remove the battery from the beacon then re-insert it the none of the apps that I have tried so far trigger a region entered response.
Please excuse my non tech question as until I can find out if this type of detection is possible I haven't yet fully immersed myself in the coding as it may not be suitable for my application.
-10867437 1 finding the area of a closed 2d uniform cubic B-splineI have a list of 2d points which are the control vertices (Dx) for a closed uniform cubic B-spline. I am assuming a simple curve (non-self-intersecting, all control points are distinct).
I am trying to find the area enclosed by the curve:

If I calculate the knot points (Px), I can treat the curve as a polygon; then I "just" need to find the remaining delta areas, for each segment, between the actual curve and the straight line joining the knot points.
I understand that the shape (and therefore area) of a Bspline is invariant under rotation and translation - so for each segment, I can find a translation to put the t=0 knot at the origin and a rotation to put the t=1 knot on the +x axis:

I can find the equation for the curve by plugging the points in and re-grouping:
P(t) = ( (t**3)*(-Dm1 + 3*D0 - 3*D1 + D2) + (t**2)*(3*Dm1 - 6*D0 + 3*D1) + t*(-3*Dm1 + 3*D1) + (Dm1 + 4*D0 + D1) ) / 6. but I'm tearing my hair out trying to integrate it - I can do
1 / | Py(t) dt / t=0 but that doesn't give me area. I think what I need is
Px(t=1) / | Py(t) (dPx(t) / dt) dt / x = Px(t=0) but before I go further, I'd really like to know:
Is this the correct calculation for area? Ideally, an analytic solution would make my day!
Once I find this area, how can I tell whether I need to add or subtract it from the base poly (red vs green areas in the first diagram)?
Are there any Python modules which would do this calculation for me? Numpy has some methods for evaluating cubic Bsplines, but none which seem to deal with area.
Is there an easier way to do this? I am thinking about maybe evaluating P(t) at a bunch of points - something like t = numpy.arange(0.0, 1.0, 0.05) - and treating the whole thing as a polygon. Any idea how many subdivisions are needed to guarantee a given level of accuracy (I'd like error < 1%)?
I'd like to run my test suite as if I were on a mobile or dial up connection. I'm using a rails stack with rspec2, selenium. Any advice?
-36033212 0 Mathematica DSolve diff. equation over a particular domainI am looking for a way to solve the following differential equation:
DSolve[(1 - b*Abs[z])*f[z]/a == f''[z], f[z], z] Therefore I tried to DSolve it distinguishing z>0 from z<0 such as:
DSolve[(1 - b*z)*f[z]/a == f''[z], f[z], z>0] But I still does not work. Maybe adding a domain explicitly would help but I can't find a way to do so.
Does anyone has any idea how do do such things?
Thank you for your help and time
-9321027 0 How to send files with node.jsHow do you send files on node.js/express.
I am using Rackspace Cloudfiles and wanna send images/videos to their remote storage but I am not sure that it's as simple as reading the file (fs.readFileSync()) and send the data in the request body, or is it?
What should the headers be.
What if it's a very large file on a couple of GBs?
Is it possible to use superagent (http://visionmedia.github.com/superagent) for this or is there a better library for sending files?
Please give me some information about this.
Thanks!
-38914083 0you can use the title property
<p class="hover" title="{{item.name}}"> or if you what to use angular for it and not the tooltip
angular.module('app', []) .controller('myController', function($scope) { $scope.myText = "some very very very very very long text"; }) .directive('hoverText', function () { return { restrict: 'A', scope: { hoverText: '=', maxChars: '=' }, link: function (scope, element) { element.text(scope.hoverText.substr(0, scope.maxChars) + '...') element.on('mouseenter', function() { element.text(scope.hoverText); }); element.on('mouseleave', function() { element.text(scope.hoverText.substr(0, scope.maxChars) + '...'); }); } }; }) p <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app" ng-controller="myController"> <p hover-text="myText" max-chars="20"> </p> </div> I know this won't help too much, but this code works perfectly fine in Chrome and Firefox
http://jsbin.com/iluXOGe/2/edit
-10584163 0Is the simple answer, you have to extend CIs functionality and use a library from a third party to provide these features for you. CI doesn't focus on the aesthetics of the "front-end". Its primary focus was "back-end".
look into Phil Sturgeons template library, and CI Sprinkles library first is for layout/theme/partials management, second is for asset management js/css minification and caching.
Phil's Template Library: http://philsturgeon.co.uk/demos/codeigniter-template/user_guide/
Sprinkles Library: https://github.com/edmundask/Sprinkle
This is a great intro video how to do such. I have used this in the past, before i got into using Sparks. http://www.youtube.com/watch?v=gvGymDhY49E
In 2.1 sparks aren't included however it is in the dev builds of CI so im sure at a later date it will be merged in with the base code. FOr now you can use this site to install Sparks to help you manage third party libraries.
-13365989 0$a == $b Equal TRUE if $a is equal to $b after type juggling. $a === $b Identical TRUE if $a is equal to $b, and they are of the same type.
it looks that
if you check 0 against a string with == then PHP returns true:
php -r 'var_dump(0 == "statuses");' -> returns TRUE
but not if your string has a number at the beginning:
php -r 'var_dump(0 == "2statuses");' -> returns FALSE
from the specs I get it that it attempts a conversion - in this case the string to number.
so better use ===
http://php.net/manual/en/language.operators.comparison.php
-31505625 0 My first lyx file only compiles like in verbatim mode. Why?I type the following text in Lyx, compile it with Apple+R, but get a verbatim version. How can I compile such a document as we do in pdflatex?
\documentclass{article} \title{Cartesian closed categories and the price of eggs} \author{Jane Doe} \date{September 1994} \begin{document} \maketitle Hello world! \end{document}
-22642695 0 Proper Unit Test for ASP.NET MVC5 I have got following code and I have no clue which proper Unit Test I have write out for those methods and how it can be done. Basically I would like to use NUnit.Framework.
Thank you in advance for ANY clue!
[AllowAnonymous] public ActionResult ForgotPassword(string id) { var model = new ForgotPasswordViewModel(); if (!string.IsNullOrEmpty(id)) { #region Process Reset Password Key try { var forgotPasswordEvent = AppModel.ForgotPasswordEvents.SingleOrDefault(x => x.UIDHash == id); if (forgotPasswordEvent != null) { var stringToHash = string.Format("{0}---{1}---{2}", forgotPasswordEvent.UID.ToString(), forgotPasswordEvent.UserId.ToString(), forgotPasswordEvent.Created.ToString()); var readyHash = SecurityHelper.GetHashString(stringToHash); if (id == readyHash) { var forgotPasswordEventUserId = forgotPasswordEvent.UserId.ToString(); var realUser = AppModel.AspNetUsers.SingleOrDefault(x => x.Id == forgotPasswordEventUserId); if (realUser != null) { var resetPasswordViewModel = new ResetPasswordViewModel(); resetPasswordViewModel.ResetPasswordData = id; resetPasswordViewModel.UserName = realUser.UserName; return RedirectToAction("ResetPassword", "Account", resetPasswordViewModel); // ResetPassword(resetPasswordViewModel); } } } else { return RedirectToAction("Index", "Home"); } } catch (Exception) { } #endregion } #region Check if the user is logged in and fill out fileds for him. var sessionManager = SessionWrapper.GetFromSession<SessionManager>("_SessionManager"); if (sessionManager != null) { var clientId = sessionManager.AppUser.ClientId; if (clientId != null) { model.Email = sessionManager.AppUser.EmailID; model.UserName = sessionManager.AppUser.UserName; model.IsLoggedInUser = true; } } #endregion return View(model); } [HttpPost] [AllowAnonymous] public ActionResult ForgotPassword(ForgotPasswordViewModel model, FormCollection formCollection) { if (ModelState.IsValid) { try { #region Check user input var user = AppModel.AspNetUsers.SingleOrDefault(x => x.UserName == model.UserName); var areErrors = false; if (user == null) { ModelState.AddModelError("UserDoesnotExist", DLMModelEntities.Properties.Resource.UserDoesNotExist); areErrors = true; } if (user.EmailID != model.Email) { ModelState.AddModelError("EmailIsWrong", DLMModelEntities.Properties.Resource.EmailIsWrong); areErrors = true; } if (areErrors) return View(model); #endregion #region Send Email and inform user try { var forgotPasswordEvent = new ForgotPasswordEvent(); var resetPasswordEmailUserState = new ResetPasswordEmailUserState(); resetPasswordEmailUserState.ForgotPasswordEventId = Guid.NewGuid(); resetPasswordEmailUserState.UserId = Guid.Parse(user.Id); resetPasswordEmailUserState.Created = DateTime.Now; forgotPasswordEvent.UID = resetPasswordEmailUserState.ForgotPasswordEventId; forgotPasswordEvent.UserId = resetPasswordEmailUserState.UserId; forgotPasswordEvent.IsSent = false; forgotPasswordEvent.Created = resetPasswordEmailUserState.Created; var stringToHash = string.Format("{0}---{1}---{2}", resetPasswordEmailUserState.ForgotPasswordEventId.ToString(), resetPasswordEmailUserState.UserId.ToString(), resetPasswordEmailUserState.Created.ToString()); forgotPasswordEvent.UIDHash = SecurityHelper.GetHashString(stringToHash); AppModel.ForgotPasswordEvents.Add(forgotPasswordEvent); AppModel.SaveChanges(); var smtp = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp"); // Set the MailerModel properties that will be passed to the MvcMailer object. var m = new MailerModel(); m.UserName = user.UserName; m.ResetPasswordLink = string.Format("{0}/{1}", Request.Url.AbsoluteUri, forgotPasswordEvent.UIDHash); m.FromEmail = smtp.From; m.Subject = AppConfiguration.ResetEmailSubject; m.ToEmail = model.Email; var client = new SmtpClientWrapper(); client.SendCompleted += (sender, e) => { if (e.Error != null || e.Cancelled) { // Handle Error } else { try { var forgotPasswordEventsToUpdate = AppModel.ForgotPasswordEvents.SingleOrDefault(x => x.UID == resetPasswordEmailUserState.ForgotPasswordEventId); if (forgotPasswordEventsToUpdate != null) { forgotPasswordEventsToUpdate.IsSent = true; AppModel.SaveChanges(); } } catch (Exception ex) { ModelState.AddModelError("EmailEx", ex.Message); } } }; Mailer.PasswordReset(m).SendAsync(resetPasswordEmailUserState, client); model.IsResetEMailSent = true; } catch (Exception ex) { ModelState.AddModelError("EmailEx", ex.Message); } #endregion } catch (Exception ex) { ModelState.AddModelError("EmailEx", ex.Message); } } return View(model); }
-21783196 0 assuming you are using rake to apply an active record migration. The file path will be relative to where you started rake which I'm sure will be the projects root.
The file path would be:
content = File.read("app/views/layouts/application.html.erb")
-26828432 0In Python 3.x or Python 2.7.6
if type(x) == str:
-240190 0 Let's say you want to keep track of a collection of stuff. Said collections must support a bunch of things, like adding and removing items, and checking if an item is in the collection.
You could then specify an interface ICollection with the methods add(), remove() and contains().
Code that doesn't need to know what kind of collection (List, Array, Hash-table, Red-black tree, etc) could accept objects that implemented the interface and work with them without knowing their actual type.
-18645609 0 Can't get eclipse to start after a computer crashI am running eclipse in a virtual machine. The vm ran out of memory so it had to shut down. Now when I try to start eclipse, nothing happens. A process starts in the task manager but it hardly is holding any memory and no windows pop up, simply nothing happens. Here is the log file in .metadata
Log: !ENTRY org.eclipse.core.resources 2 10035 2013-09-05 14:49:58.989 !MESSAGE The workspace exited with unsaved changes in the previous session; refreshing workspace to recover changes. !ENTRY org.eclipse.egit.ui 2 0 2013-09-05 14:50:14.848 !SESSION 2013-09-05 15:03:21.108 ----------------------------------------------- eclipse.buildId=M20130204-1200 java.version=1.6.0_45 java.vendor=Sun Microsystems Inc. BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=en_US Framework arguments: -product org.eclipse.epp.package.jee.product Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.jee.product And now, whenever I try to start eclipse, nothing ever gets appended to the log. Any ideas on how to fix this?
-19515861 0If you have a populated select widget, for example:
<select> <option value="1">one</option> <option value="2" selected="selected">two</option> <option value="3">three</option> ... you will want to convince select2 to restore the originally selected value on reset, similar to how a native form works. To achieve this, first reset the native form and then update select2:
$('button[type="reset"]').click(function(event) { // Make sure we reset the native form first event.preventDefault(); $(this).closest('form').get(0).reset(); // And then update select2 to match $('#d').select2('val', $('#d').find(':selected').val()); }
-12335952 0 You haven't put the shared library in a location where the loader can find it. look inside the /usr/local/opencv and /usr/local/opencv2 folders and see if either of them contains any shared libraries (files beginning in lib and usually ending in .so). when you find them, create a file called /etc/ld.so.conf.d/opencv.conf and write to it the paths to the folders where the libraries are stored, one per line. Then run
sudo ldconfig -v for example, if the libraries were stored under /usr/local/opencv/libopencv_core.so.2.4 then I would write this to my opencv.conf file:
/usr/local/opencv/ If you can't find the libraries, try running
sudo updatedb && locate libopencv_core.so.2.4 in a shell. You don't need to run updatedb if you've rebooted since compiling OpenCV.
References:
About shared libraries on Linux: http://www.eyrie.org/~eagle/notes/rpath.html
About adding the OpenCV shared libraries: http://opencv.willowgarage.com/wiki/InstallGuide_Linux
-8172405 0I do not know much about CAM::PDF. However, if you are willing to install PDF::API2, you can do:
#!/usr/bin/env perl use strict; use warnings; use Data::Dumper; use PDF::API2; my $pdf = PDF::API2->open('U3DElements.pdf'); print Dumper { $pdf->info }; Output:
$VAR1 = { 'ModDate' => 'D:20090427131238-07\'00\'', 'Subject' => 'Adobe Acrobat 9.0 SDK', 'CreationDate' => 'D:20090427125930Z', 'Producer' => 'Acrobat Distiller 9.0.0 (Windows)', 'Creator' => 'FrameMaker 7.2', 'Author' => 'Adobe Developer Support', 'Title' => 'U3D Supported Elements' };
-40859847 0 Gravity forms unset fields dynamically I'm successfully populating the Gravity form fields using "gform_pre_render " hook. now i need to remove few fields dynamically. I spend hours to looking into documentation and did google searches but no luck. Its really helpful if someone know how to unset fields in gravity form. Thanks in advance
-1934978 0It sounds like you've defined the copy constructor without defining any other constructor.
Once you declare an constructor explicitly, the compiler no longer provides a default constructor for you. Consequently, you no longer have a mechanism to construct an object of the class in the first place (and therefore wouldn't be able to copy it).
-23835668 0Other answers pointing to the fact that Strings are immutable are accurate.
But if you want to have the functionality of "clearing a String", you can use a StringBuffer instead and call this on it:
stringBuffer.delete(0, stringBuffer.length());
-24958344 0 By using this package https://sublime.wbond.net/packages/RegReplace you can create regex patterns and bind them to shortcuts.
Also if there are multiple occurrences of one word, you can put cursor on whatever part of the word and press CTRL+D multiple times. One CTRL+D press will select the word under the cursor, every other press will select next occurrence of the word.
You could also use https://sublime.wbond.net/packages/Expand%20Selection%20to%20Whitespace to expand the selection to whitespace if your word contain some random characters, and then press CTDL+D to select next occurrences of the word.
Edit: With the package regex shortcuts indeed you have to create regexes before binding them. But the CTRL+D does work without it. I don't see a problem with using "Expand selection to whitespace" and than doing the CTRL+D as I wrote in the answer.
I've checked the usage of visual as you wrote in the question and this solution seems much faster to do. You don't have to place cursor in the beggining of the word as It can be whereever in the word and no find/replace is needed, since you'll multiselect all occurrences by holding CTRL+D for a sec and You'll be free to edit it.
You can also use https://sublime.wbond.net/packages/Expand%20Selection%20to%20Quotes to select text inside quote and combine it with CTRL+D if standard CTRL+D doesn't work with some text, or if select to whitespace selects too much text.
-10355924 0When you open the exported data file directly with Excel, all formats are set as General. In General format, Excel applies formatting to what it recognizes as numbers and dates. So, to be clear, the issue is not with your export, but rather with how Excel is reading your data by default. Try the following to get around this issue.
Export to CSV. Then, rather than opening the CSV in Excel, use Excel's 'Get External Data From Text' tool to import the data into an empty workbook. Here you can specify to treat this field as TEXT rather than as GENERAL.
Note that once Excel applies number (or date) format to a cell, the data in the cell has been changed. No application of a new format will bring back your desired data. For this reason you must specify the format before Excel opens the file.
-28779170 0 Writing jQuery in separte files to support concatenation in productionFor now I have written my .js files as followed because I think, this is simple for maintenance.
//main.js $(function() { //declare variables, functions }); //page1.js $(function() { //whatever for page1 }); //page2.js $(function() { //whatever for page2 }); In .html I just have to specify which .js files to load, this is working so far because the individual .html is assigned with the right .js files
<!-- page1.html --> <script src="main.js"> <script src="page1.js"> <!-- page2.html --> <script src="main.js"> <script src="page2.js"> If I plan to concatenate all .js files into one single .js file for production purpose, how should i restructure my .js files to support concatenation so in each .html i can only use <script src="all.js">
Please guide what to do. Thanks.
-36740364 0I believe aerospike would serves your purpose, you can configure it for hybrid storage at namespace(i.e. DB) level in aerospike.conf which is present at /etc/aerospike/aerospike.conf
For details please refer official documentation here: http://www.aerospike.com/docs/operations/configure/namespace/storage/
-21317678 0Not sue why you would need to do this but you can use identical to do the comparison. However, since identical only compares two arguments, you will have to loop over your list, preferably using lapply...
lapply( a , function(x) identical( substitute(1 + 2) , x ) ) #[[1]] #[1] TRUE #[[2]] #[1] FALSE Or similarly you can still use ==. Inspection of substitute(1 + 2) reveals it to be a language object of length 3, whilst your list a is obviously of length 2, hence the warning on vector recycling. Therefore you just need to loop over the elements in your list which you can do thus:
lapply( a , `==` , substitute(1 + 2) ) #[[1]] #[1] TRUE #[[2]] #[1] FALSE
-13409129 0 Which loops and which co-ordinate system can I use to automate this example of a truss structure I am completely new to matlab and can't seem to get an if loop to work. For example if Ln > k , plot point i(n-1) to i(n). How would I automatically assign the correct row or column vectors to i(n)?
Here is a diagram of what I'm wanting

What I want to achieve is connect i(0) to i(1) to ... i(n-1) to i(n).
I also am a bit confused at which co-ordinate system to use? I thought it would be easy to use a polar co-ordinate system. Defining a distance and angle from point i(o) and then doing the same from point i(1) but from what I could find, it is necessary to convert back to a cartesian co-ordinate system.
Once I am comfortable with this section I am confident I can take on the next steps, and develop a full solution to my problem. If you are interested in what I am trying to achieve, here's a link
[PLEASE NOTE] In that question I linked to, I was told I made a mess of it. I'm sorry if this question is also not clear. I really have spent the time to make it as clear as possible. I find it hard to express myself sometimes.
-743094 0 App_Data/ASPNETDB.MDF to Sql Server 2005 (or 08)I've been developing an ASP.NET WebForms app that needed account login functionality (e.g. register new users, change passwords, recover passwords, profiles, roles, etc). To do this, I used FormsAuthentication with the default data store, which, to my surprise, is an MDF file in App_Data. When it comes time to actually deploy this app. live on the web, I'm going to use some shared hosting like GoDaddy or another cheap company.
For efficiency, I'd like to switch over from this MDF to actual SQL Server 2005 or 2008 (who in their right mind uses flat files?). With shared hosting, however, I'm not going to be able to run any programs like aspnet_regsql.exe. I'll just have a single login and password to a SQL Server database, and an FTP account into the domain root. No MSTSC remote desktop, no console access, no tinkering in IIS, etc.
I won't need to transfer any user accounts from ASPNETDB.MDF (site will be starting with zero users), but how am I suppose to:
1) Easily create the tables, procedures, etc. that Visual Studio automatically created in ASPNETDB.MDF when I used Web Site Administration Tool to get started with FormsAuthentication?
2) Have the SQL membership provider use a connection string I give it instead of using whatever it is now to connect to this ASPNETDB.MDF. Hell, I don't even see any connection string to this MDF in the web.config; how the hell is my app. even finding it? Machine.config? That would be a poor decision if that's the case. This behind-the-scenes crap drives me nuts.
Any help from someone who has been through this migration would be very, very much appreciated!
-20477511 0 createjs load local files loadqueueIm have been working on a project with the createjs library and I have used Brackets with Live preview where everything works perfectly, but if I just open the file in a browser I get the following error message in chrome.
XMLHttpRequest cannot load file:///C:/Users/Maskinen/Docuemnts/fail.fail. Cross origin requests are only supported for HTTP. I have read that if I set loadqueue(false) I wouldnt get problems with loading local files. I therefore thought that when it was working in live preview in brackets everything was fine. Is it possible to run chrome or firefox as Brackets in live preview or similar? The project is part of an assignment and it isnt possible to use a webserver :(
-10727481 0 Determine Cobol coding styleI'm developing an application that parses Cobol programs. In these programs some respect the traditional coding style (programm text from column 8 to 72), and some are newer and don't follow this style.
In my application I need to determine the coding style in order to know if I should parse content after column 72.
I've been able to determine if the program start at column 1 or 8, but prog that start at column 1 can also follow the rule of comments after column 72.
So I'm trying to find rules that will allow me to determine if texts after column 72 are comments or valid code.
I've find some but it's hard to tell if it will work everytime :
dot after column 72, determine the end of sentence but I fear that dot can be in comments too
find the close character of a statement after column 72 : " ' ) }
look for char at columns 71 - 72 - 73, if there is not space then find the whole word, and check if it's a key word or a var. Problem, it can be a var from a COPY or a replacement etc...
I'd like to know what do you think of these rules and if you have any ideas to help me determine the coding style of a Cobol program.
I don't need an API or something just solid rules that I will be able to rely on.
-29336575 0Isn't what you want to implement the scanl1 function? I'm a beginner too, but from what I understood, it goes like this:
scanl1 :: (a -> a -> a) -> [a] -> [a] scanl1 f (x:xs) = scanl f x xs scanl1 _ [] = [] The scanl function. which scanl1 uses, goes like this:
scanl :: (b -> a -> b) -> b -> [a] -> [b] scanl = scanlGo where scanlGo :: (b -> a -> b) -> b -> [a] -> [b] scanlGo f q ls = q : (case ls of [] -> [] x:xs -> scanlGo f (f q x) xs) Here's what hackage has to say about scanl:
scanl :: (b -> a -> b) -> b -> [a] -> [b] Source scanl is similar to foldl, but returns a list of successive reduced values from the left:
scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...] Note that
last (scanl f z xs) == foldl f z xs. So, I guess the flow of execution goes like this:
scanl1 (+) [2, 4, 1, 1] scanl (+) 2 [4, 1, 1] scanlGo (+) 2 [4, 1, 1] 2 : scanlGo (+) (+ 2 4) [1, 1] 2 : 6 : scanlGo (+) (+ 6 1] [1] 2 : 6 : 7 : scanlGo (+) (+ 7 1) [] 2 : 6 : 7 : 8 : scanlGo [] 2 : 6 : 7 : 8 : [] [2, 6, 7, 8] The same thing happens with the (*) and the max functions that you mentioned. Hope this helps.
You should make content pane transparent too.
frame.setUndecorated(true); frame.getContentPane().setBackground(new Color(1.0f,1.0f,1.0f,0.0f)); frame.setBackground(new Color(1.0f,1.0f,1.0f,0.0f));
-29395807 0 The data you have published is not the same as you used in your test.
This program checks both of the regex patterns against the data copied directly from an edit of your original post. Neither pattern matches any of the lines in your data
use strict; use warnings; use 5.010; my (%STA_DATA, $file, $path); while ( <DATA> ) { if ( /^-?\s{1,2}Arrival\sTime/ ) { say 'match1'; $STA_DATA{$file}{$path}{Arrival_Time} = m/\sArrival\sTime\s+(.*)\s+$/ } if ( /^-\sArrival\sTime/ or m/^\s{1,2}Arrival\sTime/ ) { say 'match2'; $STA_DATA{$file}{$path}{Arrival_Time} = m/\sArrival\sTime\s+(.*)\s+$/ } } __DATA__ Arrival Time 3373.000 - Arrival Time 638.700 | 100.404 Arrival Time Report
-28393390 0 Cordova - ANDROID_HOME is not set and "android" command not in your PATH. You must fulfill at least one of these conditions I've installed nodejs and cordova and downloaded android sdk. The thing is when I try and add an android platform here's what sortf happen:
$ sudo cordova platform add android Creating android project... /home/blurt/.cordova/lib/npm_cache/cordova-android/3.6.4/package /bin/node_modules/q/q.js:126 throw e; ^ Error: ANDROID_HOME is not set and "android" command not in your PATH. You must fulfill at least one of these conditions. None of the solutions that I found in the Internet worked.
When I type :
$ echo $ANDROID_HOME it gives nothing.
When I type:
echo $PATH it prints
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games: /usr/local/games:/opt/android-sdk/tools:/opt/android-sdk/platform- tools:/opt/node/bin:/opt/android-sdk/tools:/opt/android-sdk/platform-tools:/opt/node/bin shows this.
I believe my SDK path is :/opt/android-sdk/tools
I am using a UITableViewCell subclass in a highly customized UITableView. Now I want to implement a edit button. So I implemented a button, an action, setting the UITableview to editing:YES and so on. The problem is that my cells do not show the delete or move buttons or handlers. Do I need to implement something in my subclass for this?
Bests,
Philip
I have the next query:
SELECT chat.*, message.time as last_message, message.content as last_message_content FROM chat LEFT JOIN message ON chat.id = message.chat_id GROUP BY chat.id ORDER BY message.time ASC now, I want to pick the newest message.time, but right now it gives me the first one..
any idea on how this could be accomplished?
thanks
-5213408 0 Problem getting height from div after ajax requestI'm having a problem getting height from a div which is being filled by an ajax request. Consider following code
(function($) { $.fn.flickr = function(o){ var s = { api_key: '', // [string] required, see http://www.flickr.com/services/api/misc.api_keys.html type: null, // [string] allowed values: 'photoset', 'search', default: 'flickr.photos.getRecent' photoset_id: null, // [string] required, for type=='photoset' text: null, // [string] for type=='search' free text search user_id: null, // [string] for type=='search' search by user id group_id: null, // [string] for type=='search' search by group id tags: null, // [string] for type=='search' comma separated list tag_mode: 'any', // [string] for type=='search' allowed values: 'any' (OR), 'all' (AND) sort: 'date-posted-asc', // [string] for type=='search' allowed values: 'date-posted-asc', 'date-posted-desc', 'date-taken-asc', 'date-taken-desc', 'interestingness-desc', 'interestingness-asc', 'relevance' thumb_size: 's', // [string] allowed values: 's' (75x75), 't' (100x?), 'm' (240x?) size: 'o', // [string] allowed values: 'm' (240x?), 'b' (1024x?), 'o' (original), default: (500x?) per_page: 100, // [integer] allowed values: max of 500 page: 1, // [integer] see paging notes attr: '', // [string] optional, attributes applied to thumbnail <a> tag api_url: null, // [string] optional, custom url that returns flickr JSON or JSON-P 'photos' or 'photoset' params: '', // [string] optional, custom arguments, see http://www.flickr.com/services/api/flickr.photos.search.html api_callback: '?', // [string] optional, custom callback in flickr JSON-P response callback: null // [function] optional, callback function applied to entire <ul> }; if(o) $.extend(s, o); return this.each(function(){ // create unordered list to contain flickr images var list = $('<ul>').appendTo(this); var url = $.flickr.format(s); $.getJSON(url, function(r){ if (r.stat != "ok"){ for (i in r){ $('<li>').text(i+': '+ r[i]).appendTo(list); }; } else { if (s.type == 'photoset') r.photos = r.photoset; // add hooks to access paging data list.append('<input type="hidden" value="'+r.photos.page+'" />'); list.append('<input type="hidden" value="'+r.photos.pages+'" />'); list.append('<input type="hidden" value="'+r.photos.perpage+'" />'); list.append('<input type="hidden" value="'+r.photos.total+'" />'); for (var i=0; i<r.photos.photo.length; i++){ var photo = r.photos.photo[i]; // format thumbnail url var t = 'http://farm'+photo['farm']+'.static.flickr.com/'+photo['server']+'/'+photo['id']+'_'+photo['secret']+'_'+s.thumb_size+'.jpg'; //format image url var h = 'http://farm'+photo['farm']+'.static.flickr.com/'+photo['server']+'/'+photo['id']+'_'; switch (s.size){ case 'm': h += photo['secret'] + '_m.jpg'; break; case 'b': h += photo['secret'] + '_b.jpg'; break; case 'o': if (photo['originalsecret'] && photo['originalformat']) { h += photo['originalsecret'] + '_o.' + photo['originalformat']; break; }; default: h += photo['secret'] + '.jpg'; }; list.append('<li><a href="'+h+'" '+s.attr+' rel="photographs"><img src="'+t+'" alt="'+photo['title']+'" /></a></li>'); }; if (s.callback) s.callback(list); $('#photographs ul li a img').fadeTo('fast', 0.7); $('#photographs ul li a img').hover(function() { $(this).fadeTo('fast', 1); },function() { $(this).fadeTo('fast', 0.7); }); $("#photographs ul li a").fancybox({ 'hideOnContentClick': false, 'zoomSpeedIn': 0, 'zoomSpeedOut': 0, 'overlayShow': true, 'overlayColor': '#000', 'overlayOpacity': 0.9, 'padding': 0 }); var outer = $('#photographs').outerHeight(), inner = $('#test').height(); if(inner>outer){ alert('Inner exceeded outer'); } }; }); }); }; At the very end, all my code in the callback is working on the ajax added images itself. I need to calculate the height of the inner div but i always get '0' because the images haven't been added yet. How do it do that?
Thank you very much if anyone can help me!
Mathijs
-40956811 0You have to do this with values() but restrict fields that you want to group by
Core.objects.values('age_id', 'cat_id').filter(state='ABC').annotate(Max('date'), Count('age_id', 'cat_id'))
-25567424 0 The maxElements could be a limit for the list. You can use x.size() > 0 check if you want x.get(0).
ArrayList<Points> x = new ArrayList<>(); for (int i = 0; i < maxElements; i++) { x.add(new Point(0, 0)); } Points p; if (x.size() > 0) p = x.get(0);
-25710105 0 I would go with a different approach (though yours is not wrong in any way but I think is less common):
Let the status be part of HTTP header with an HTTP return code (200, 201, ..., 400, 404, ..., etc.) and in the case you mentioned, an JSON array instead of the result field: [{...}, ...]
A simple example:
Request:
GET /api/v1/users HTTP/1.1 Response:
200 OK Content-Type: application/json Date: Sun, 07 Sep 2014 15:24:04 GMT Content-Length: 261 .... [ { "username": ..., "email": ..., "firstName": ..., "lastName": ..., "password": ..., ... }, { "username": ..., "email": ..., "firstName": ..., "lastName": ..., "password": ..., ... } ]
-20046163 0 As @user488074 said, your controller must have an argument that it is looking for when you create an instance of it. Go to that controller and look at what it is looking for in the contstruct function. If you don't want to pass an argument all the time for this controller then add something like this to the construct function argument
public function foo($argument = NULL){ } so it has a default value if you don't want to pass something.
-24309149 0The question is a bit old, but maybe this can be useful for someone with the same issue.
Here is a simple example from the code I used:
On my controller, I generate a markers array with this structure:
var markers = new Array(); for(var i = 0; i < someData.length; i++ ){ var newMarker = { id: parseInt(i), latitude: parseFloat(someData[i].latitude), longitude: parseFloat(someData[i].longitude), showWindow: false, title: "Marker"+i, } newMarker.onClicked = function () { alert(newMarker.id); } markers.push(newMarker); } $scope.markers = markers; Then on the view:
<google-map center="map.center" draggable="true" options=map.options zoom="map.zoom"> <markers models="markers" coords="'self'" doCluster=true click="'onClicked'"> </markers> </google-map>
-31460552 0 Okay, given the DCOS template, the LaunchConfiguration for the slaves looks like this: (I've shortened it somewhat)
"MasterLaunchConfig": { "Type": "AWS::AutoScaling::LaunchConfiguration", "Properties": { "IamInstanceProfile": { "Ref": "MasterInstanceProfile" }, "SecurityGroups": [ ... ], "ImageId": { ... }, "InstanceType": { ... }, "KeyName": { "Ref": "KeyName" }, "UserData": { ... } } } To get started, all you need to do is add the SpotPrice property in there. The value of SpotPrice is, obviously, the maximum price you want to pay. You'll probably need to do more work around autoscaling, especially with alarms and time of day. So here's your new LaunchConfiguration with a spot price of $1.00 per hour:
"MasterLaunchConfig": { "Type": "AWS::AutoScaling::LaunchConfiguration", "Properties": { "IamInstanceProfile": { "Ref": "MasterInstanceProfile" }, "SecurityGroups": [ ... ], "ImageId": { ... }, "InstanceType": { ... }, "KeyName": { "Ref": "KeyName" }, "UserData": { ... }, "SpotPrice": 1.00 } }
-16747658 0 You should to init needed layout messages through Mage_Core_Controller_Varien_Action::_initLayoutMessages()
Example:
public function resultAction() { $this->_title($this->__('Printer Applicable Products')); $this ->loadLayout() ->_initLayoutMessages('checkout/session') ->_initLayoutMessages('catalog/session') $this->renderLayout(); } You need to init a session model that contains needed messages.
Also keep in mind that printer/finder/result.phtml should contain
$this->getMessagesBlock()->getGroupedHtml()
-10980861 0 make draggable div property false in prototype I have a div in prototype and it is draggable I want to make its draggable property false. How can I do it? Thanks.
<div id="answer_0_3" class="dragndrop_0 foreign dropped_answer" >Notebook</div> My draggables are as follows:
var draggables = []; $$('.answer.dragndrop_0').each(function(answer) { draggables.push( new Draggable( answer, {revert: 'failure', scroll: window} ) ); });
-206751 0 MySQL autoincrement column jumps by 10- why? I have a couple tables in which I created an object ID as either an Int or Bigint, and in both cases, they seem to autoincrement by 10 (ie, the first insert is object ID 1, the second is object ID 11, the third is object ID 21, etc). Two questions:
Why does it do that?
Is that a problem?
I have the following code
String entitySQL = "(SELECT o.VehicleTypeID, (o.Engine_Capacity * cast(16039.99 as System.Double) ) " + " FROM CarRentalModelEntities.VehicleTypes AS o where o.VehicleTypeID = 20014) "; query = new ObjectQuery<DbDataRecord>(entitySQL, context); DataRetriever.InitializeTest(context.objectContext.MetadataWorkspace); DataRetriever.GetResultSet(query); xmlRetrievedData = DataRetriever.GetRetrievedTestData(); I want to use DBContext instead of Object Context. How to write the above query using DBQuery? Anyone please help.
-17490386 0Check your log files (find them in your vhosts file or the sites-available files) to get the error. Your .htaccess appears to be fine.
-32488489 0Okay, so first of all you will need to implement the MouseListener interface. You can either have your main class implement MouseListener, or attach a generic implementation to a JPanel via addMouseListener(). The latter method is described below:
public class MyPanel extends JPanel { public MyPanel() { // ... this.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { // Handle left-click } else if (e.getButton() == MouseEvent.BUTTON2) { // Handle right-click } } }); } } You can also check e.isShiftDown() to see if the Shift key is being held.
strtotime() should be able to handle it.
-1414562 0In fact CoCreateGuid() calls UuidCreate(). The generated Data Types(UUID,GUID) are exactly the same. On Windows you can use both functions to create GUIDs
-21881379 0You can check out the official angular tutorial at Step 09 - Filters.
More info about how to create custom filters ;)
-10925210 0 How can I conditionally suppress logging in Express (or Connect)?When using the logger middleware which is part of Connect (as well as Express), I would like to be able to disable logging on certain requests, say by setting a flag on the response or something.
I managed to do it by saying:
res.doNotLog = true; and then, deep in logger.js (part of the Connect module), I put
if(res.doNotLog) return; in the right place. But of course I don't want to be modifying code in the module itself. Is there any way I can cause the same to happen without having to hack the module?
Edit:
This worked:
var app = _express.createServer(); // set 'hello' routing...note that this is before middleware // so it won't be logged app.get('/sayhello', function(req, res) {res.send("hey");}); // configure middleware: logging, static file serving app.configure(function() { app.use(_express.logger()); app.use(_express.static(__dirname + '/www')); }); // set 'goodbye' routing...note that this is after middleware // so it will be logged app.get('/saygoodbye', function(req, res) {res.send("later...");});
-33682821 0 I hope these php scripts can help you:
Order SSL Certificates
<?php /** * Order SSL certificate * * This script orders a SSL Certificate * * Important manual pages: * @see http://sldn.softlayer.com/reference/services/SoftLayer_Product_Order/placeOrder * @see http://sldn.softlayer.com/reference/datatypes/SoftLayer_Container_Product_Order * @see http://sldn.softlayer.com/reference/datatypes/SoftLayer_Container_Product_Order_Security_Certificate * * @license <http://sldn.softlayer.com/wiki/index.php/license> * @author SoftLayer Technologies, Inc. <sldn@softlayer.com> */ require_once "C:/PhpSoftLayer/SoftLayer/SoftLayer/XmlrpcClient.class.php"; /** * Your SoftLayer API username * @var string */ $username = "set me"; /** * Your SoftLayer API key * Generate one at: https://control.softlayer.com/account/users * @var string */ $apiKey = "set me"; // Create a SoftLayer API client object for "SoftLayer_Product_Order" services $productService = Softlayer_XmlrpcClient::getClient("SoftLayer_Product_Order", null, $username, $apiKey); /** * Define SSL Certificates Properties * @var int $quantity * @var int $packageId * @var int $serverCount * @var int $validityMonths * @var string $orderApproverEmailAddress * @var string $serverType */ $quantity = 1; $packageId = 210; $serverCount = 1; $validityMonths = 24; $serverType = "apache2"; $orderApproverEmailAddress = "admin@rubtest.com"; /** * Build a skeleton SoftLayer_Container_Product_Order_Attribute_Contact object for administrativeContact, * billingContact, technicalContact and organizationInformation properties. You can use the same information * for all of these properties, or you can create this object for each one. * @var string addressLine1 * @var string city * @var string countryCode * @var string postalCode * @var string state * @var string email * @var string firstName * @var string lastName * @var string organizationName * @var string phoneNumber * @var string title */ $addressInfo = new stdClass(); $addressInfo -> address = new stdClass(); $addressInfo -> address -> addressLine1 = "Simon Lopez Av."; $addressInfo -> address -> city = "Cochabamba"; $addressInfo -> address -> countryCode = "BO"; $addressInfo -> address -> postalCode = "0591"; $addressInfo -> address -> state = "OT"; $addressInfo -> emailAddress = "noreply@softlayer.com"; $addressInfo -> firstName = "Ruber"; $addressInfo -> lastName = "Cuellar"; $addressInfo -> organizationName = "TestCompany"; $addressInfo -> phoneNumber = "7036659886"; $addressInfo -> title = "TitleTest"; /** * Define a collection of SoftLayer_Product_Item_Price objects. You can verify the item available for a given package using * SoftLayer_Product_Package::getItemPrices method * @see http://sldn.softlayer.com/reference/services/SoftLayer_Product_Package/getItemPrices */ $price = new stdClass(); $price->id = 1836; /** * Declare the CSR * @var string */ $certificateSigningRequest = "-----BEGIN CERTIFICATE REQUEST----- MIIC8TCCAdkCAQAwgasxCzAJBgNVBAYTAkNaMR8wHQYDVQQIExZDemVjaCBSZXB1 YmxpYywgRXVyb3BlMRQwEgYDVQQHEwtQcmFndWUgQ2l0eTEWMBQGA1UEChMNTXkg VW5saW1pbnRlZDEMMAoGA1UECxMDVlBOMRQwEgYDVQQDEwtydWJ0ZXN0LmNvbTEp MCcGCSqGSIb3DQEJARYacnViZXIuY3VlbGxhckBqYWxhc29mdC5jb20wggEiMA0G CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDnusRc9LDjfm21A/fz1UhuMoUqkeji BX/oTXsD/GmRaraOb0QnzjGoaM2K07nMENpQiJRpmEj3tEKwAXNitlapLwlXFvB7 rVd9lkvGmCIEkkDp5nbsdejS7BqJ8ikgEI+HATmdoyi9jxWrM/i6c9pnhF4j9ejI XQnxd3yvpuxgybF3tN+HOOpXwVH4FQC7x/FRRai8jNxd2f+VzW7EgtIYxgl3L8gr 4DPPAAiX07lEAccEEUhQ3/LbTlSPiT0hiGh8tMcImYFDDyGOIRJKXSptuvYgwHRC 67D6fzT4ITtG2XMkzo5kgyZtwemRiikAzVbmtEFKwht0j0Q+3nf1Yv2BAgMBAAGg ADANBgkqhkiG9w0BAQUFAAOCAQEAJCRjsdmVhcM+mKbG8NE4YdDyBfKvC03g/mCn wWZWca1uRbYeJUNH2/LFy9tQ/8J07Cx0KcPmRnHbXkZaSMHsorv4sg6M3XDRaIiu D/ltOZYlGYC1zFVM+pgiQd84krO0lTf/NiJxyyL3e3owO91h07jPuGGFygSOeKZa cMMNdLQlPfZIS+hwZUuJSgormGhr+dfPkHbjP3l3X+uO59VNE+1zHTctCqooyCRa HrHFjNbVD4Ou7Ff6B0LUiw9I54jH69MrtxdrsF+kvOaa44fN1NjqlM1sI4ZQs0O1 15B5NKrFMxG+5BrZYL7n8qEzra7WYFVrebjKexQqSBi4B6XU+g== -----END CERTIFICATE REQUEST-----"; /* * Build a skeleton SoftLayer_Container_Product_Order object with details required to order */ $container = new stdClass(); $container -> complexType = "SoftLayer_Container_Product_Order_Security_Certificate"; $container -> packageId = $packageId; $container -> quantity = $quantity; $container -> serverCount = $serverCount; $container -> serverType = $serverType; $container -> prices = array($price); $container -> certificateSigningRequest = $certificateSigningRequest; $container -> validityMonths = $validityMonths; $container -> orderApproverEmailAddress = $orderApproverEmailAddress; // technicalContact, administrativeContact, organizationInformation and billingContact $container -> technicalContact = $addressInfo; $container -> administrativeContact = $addressInfo; $container -> organizationInformation = $addressInfo; $container -> billingContact = $addressInfo; $order = new stdClass(); $order->orderContainers = array(); $order->orderContainers[0] = $container; try { /* * SoftLayer_Product_Order::verifyOrder() method will check your order for errors. Replace this with a call * to placeOrder() when you're ready to order. Both calls return a receipt object that you can use for your * records. */ $result = $productService -> verifyOrder($order); print_r($result); } catch(Exception $e) { echo "Unable to order SSL Certificates: " . $e -> getMessage(); } Order Firewall Device
<?php /** * Order dedicated Firewall for a Device (Virtual Guest) * Important manual pages: * http://sldn.softlayer.com/reference/datatypes/SoftLayer_Container_Product_Order_Network_Protection_Firewall_Dedicated * http://sldn.softlayer.com/reference/datatypes/SoftLayer_Product_Item_Price * http://sldn.softlayer.com/reference/services/SoftLayer_Product_Order/verifyOrder * http://sldn.softlayer.com/reference/services/SoftLayer_Product_Order/placeOrder * * License <http://sldn.softlayer.com/article/License> * Author SoftLayer Technologies, Inc. <sldn@softlayer.com> */ require_once "C:/PhpSoftLayer/SoftLayer/SoftLayer/SoapClient.class.php"; /** * Your SoftLayer API username * @var string */ $username = "set me"; /** * Your SoftLayer API key * Generate one at: https://control.softlayer.com/account/users * @var string */ $apiKey = "set me"; // Define the virtual guest Id that you wish to add the firewall $virtualGuestId = 5074554; // Creating a SoftLayer API client object $softLayerProductOrder = SoftLayer_SoapClient::getClient('SoftLayer_Product_Order', null, $username, $apiKey); /** * Building a skeleton SoftLayer_Product_Item_Price objects. These objects contain * much more than ids, but SoftLayer's ordering system only needs the price's id * to know what you want to order. * to get the list of valid prices for the package * use the SoftLayer_Product_Package:getItems method */ $prices = array ( 409, # Price to 100Mbps Hardware Firewall ); /** * Convert our item list into an array of skeleton * SoftLayer_Product_Item_Price objects. */ $orderPrices = array(); foreach ($prices as $priceId){ $price = new stdClass(); $price->id = $priceId; $orderPrices[] = $price; } // Define location, packageId and quantity $location = "AMSTERDAM"; $packageId = 0; // The package Id for order monitoring packages is 0 $quantity = 1; // Build a skeleton SoftLayer_Virtual_Guest object to model the id // of the virtual guest where you want add the monitoring package $virtualGuests = new stdClass(); $virtualGuests->id = $virtualGuestId; $orderVirtualGuest = array ( $virtualGuests ); // Build a SoftLayer_Container_Product_Order_Network_Protection_Firewall_Dedicated object containing // the order you wish to place. $orderContainer = new stdClass(); $orderContainer->location = $location; $orderContainer->packageId = $packageId; $orderContainer->prices = $orderPrices; $orderContainer->quantity = $quantity; $orderContainer->virtualGuests = $orderVirtualGuest; try { // Re-declare the order template as a SOAP variable, so the SoftLayer // ordering system knows what type of order you're placing. $orderTemplate = new SoapVar ( $orderContainer, SOAP_ENC_OBJECT, 'SoftLayer_Container_Product_Order_Network_Protection_Firewall', 'http://api.service.softlayer.com/soap/v3.1/' ); /* * SoftLayer_Product_Order::verifyOrder() method will check your order for errors. Replace this with a call * to placeOrder() when you're ready to order. Both calls return a receipt object that you can use for your * records. */ $receipt = $softLayerProductOrder->verifyOrder($orderTemplate); print_r($receipt); } catch (Exception $e) { echo 'Unable to order the firewall for device: ' . $e->getMessage(); } Firewall for VLAN
<?php /** * Order Firewall for a VLAN * Important manual pages: * http://sldn.softlayer.com/reference/datatypes/SoftLayer_Container_Product_Order_Network_Protection_Firewall_Dedicated * http://sldn.softlayer.com/reference/datatypes/SoftLayer_Product_Item_Price * http://sldn.softlayer.com/reference/services/SoftLayer_Product_Order/verifyOrder * http://sldn.softlayer.com/reference/services/SoftLayer_Product_Order/placeOrder * * License <http://sldn.softlayer.com/article/License> * Author SoftLayer Technologies, Inc. <sldn@softlayer.com> */ require_once "C:/PhpSoftLayer/SoftLayer/SoftLayer/SoapClient.class.php"; /** * Your SoftLayer API username * @var string */ $username = "set me"; /** * Your SoftLayer API key * Generate one at: https://control.softlayer.com/account/users * @var string */ $apiKey = "set me"; // Create a SoftLayer API client object for "SoftLayer_Product_Order" services $softLayerProductOrder = Softlayer_SoapClient::getClient("SoftLayer_Product_Order", null, $username, $apiKey); // Declare the vlan id that you wish to add the firewall $vlanId = 765032; /** * Building a skeleton SoftLayer_Product_Item_Price objects. These objects contain * much more than ids, but SoftLayer's ordering system only needs the price's id * to know what you want to order. * to get the list of valid prices for the package * use the SoftLayer_Product_Package:getItemPrices method */ $prices = array ( 2390, // Hardware Firewall (Dedicated) //21514, FortiGate Security Appliance ); /** * Convert our item list into an array of skeleton * SoftLayer_Product_Item_Price objects. */ $orderPrices = array(); foreach ($prices as $priceId){ $price = new stdClass(); $price->id = $priceId; $orderPrices[] = $price; } // Declare the location, packageId and quantity $location = "AMSTERDAM"; $packageId = 0; // The package Id for order Firewalls $quantity = 1; // Build a SoftLayer_Container_Product_Order_Network_Protection_Firewall_Dedicated object containing // the order you wish to place. $orderContainer = new stdClass(); $orderContainer->location = $location; $orderContainer->packageId = $packageId; $orderContainer->prices = $orderPrices; $orderContainer->quantity = $quantity; $orderContainer-> vlanId = $vlanId; try { // Re-declare the order template as a SOAP variable, so the SoftLayer // ordering system knows what type of order you're placing. $orderTemplate = new SoapVar ( $orderContainer, SOAP_ENC_OBJECT, 'SoftLayer_Container_Product_Order_Network_Protection_Firewall_Dedicated', 'http://api.service.softlayer.com/soap/v3/' ); /* * SoftLayer_Product_Order::verifyOrder() method will check your order for errors. Replace this with a call * to placeOrder() when you're ready to order. Both calls return a receipt object that you can use for your * records. */ $receipt = $softLayerProductOrder->verifyOrder($orderTemplate); print_r($receipt); } catch (Exception $e) { echo 'Unable to place the order: ' . $e->getMessage(); } Order Security Software (Anti Virus)
<?php /** * Purchase an Anti-virus for a server * * Important manual pages: * @see http://sldn.softlayer.com/reference/services/SoftLayer_Ticket * @see http://sldn.softlayer.com/reference/services/SoftLayer_Ticket/createUpgradeTicket * * @license <http://sldn.softlayer.com/wiki/index.php/license> * @author SoftLayer Technologies, Inc. <sldn@softlayer.com> */ require_once "C:/PhpSoftLayer/SoftLayer/SoftLayer/SoapClient.class.php"; /** * Your SoftLayer API username * @var string */ $username = "set me"; /** * Your SoftLayer API key * Generate one at: https://control.softlayer.com/account/users * @var string */ $apiKey = "set me"; /** * Define the hardware id where you wish to add the McAfee ANtivirus * @var int $attachmentId */ $attachmentId = 251708; // Define a brief description of what you wish to upgrade $genericUpgrade = "Add / Upgrade Software"; // $upgradeMaintenanceWindow = "9.30.2015 (Wed) 01:00(GMT-0600) - 04:00(GMT-0600)"; // Declare a detailed description of the server or account upgrade you wish to perform $details ="I would like additional information on adding McAfee AntiVirus (5$.00 monthly) to my account."; // Declare the attachmentType e.g. HARDWARE - VIRTUAL_GUEST - NONE $attachmentType = "HARDWARE"; // Create a SoftLayer API client object for "SoftLayer_Ticket" service $ticketService = SoftLayer_SoapClient::getClient("SoftLayer_Ticket", null, $username, $apiKey); try { $result = $ticketService -> createUpgradeTicket($attachmentId, $genericUpgrade, $upgradeMaintenanceWindow, $details, $attachmentType); print_r($result); } catch(Exception $e) { echo "Unable to create the ticket: " . $e -> getMessage(); }
-8678625 0 Put the complete code in brackets :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier"; NSArray *listData =[self->tableContents objectForKey: [self->sortedKeys objectAtIndex:[indexPath section]]]; UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier: SimpleTableIdentifier]; if(cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier]; NSUInteger row = [indexPath row]; textClass *myText = (textClass*)[listData objectAtIndex:row]; cell.textLabel.text = myText.text; UIImageView *unchecked = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"unchecked.png"]]; UIImageView *checked = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"checked.png"]]; cell.accessoryView = (myText.isChecked ? checked : unchecked); } return cell; } This should definitely work.
-24005181 0I got the same problem using Robomongo. I solve it creating the function manually on shell.
Right-click on your database -> Open Shell.
db.system.js.save({ _id : "getNextSequence" , value : function (name) { var ret = db.counters.findAndModify({ query: { _id: name }, update: { $inc: { seq: 1 } }, new: true }); return ret.seq; } });
-16547451 0 I'd like to recommend these:
Add the namespace to your class file. using System.Net.Mail;
Provide arguments when you call the function (SendMailMessage).
Make class SendMail as a static class, SendMailMessage as static function.
Tom,
I too have been experiencing issues with Sql CE and the Entity Framework. BUT, I may be able to explain the post that you are referencing because I am versed in using it now that I have fought my way through it.
For starters, that blog entry was for the MVCScaffolding NuGet package. Not sure if you know what this package does but it basically adds a reference to the Scaffolder that Scott & Company created to dynamically generate CRUD for you once you have built your models.
My understanding is that once you create a model, build your project, you can run the following command in the Package Manager Console and it will create the CRUD that I mentioned above.
Scaffold Controller [WhateverYourModelNameIs] Now, once this process is complete, it generates a Context class for your application under the Models folder. If you see above in your code (for SQLCEEntityFramework.cs) in the Start method, it mentions that you need to uncomment the last line of the method in order for it to create the db if it does not exist.
Lastly, once you execute your application, a SQL CE database "should" be created and if you click on the App_Data folder and choose to 'Show All Files' at the top of the Solution Explorer and hit the Refresh icon, you should see your database.
UPDATE:
So sorry, after testing this, Tom, you are correct. Only way the database is created is if you execute one of the views that were created by the Scaffolder.
-33855005 0 Get frame by frame data from mp4 using C# and .NET 2.0I'm currently developing using Unity 3D, however my background is Apple development. In iOS/OSX development I can use AVFoundation to load an mp4 and get frame by frame data from it as it plays in BGRA format.
I was wondering what the equivalent of this is for .NET (Unity uses .NET 2.0)?
I know it's possible to call functions in an Objective-C++ file from unity but I need a way to do this on any platform not just iOS.
-25465706 0Here is code that handles it:
page = Mechanize.new.get "http://page_u_need" page.iframe_with(id: 'beatles').content
-39516498 0 I agree, there are better ways to create a header for CCDA documents, however, if you'd like to stick with your solution here is the missing part:
var clinicalDocument = new XML ("<clinicalDocument></clinicalDocument>"); clinicalDocument['realmCode']['@code']="US"; clinicalDocument['typeId']['@extension']="POCD_HD000040"; clinicalDocument['typeId']['@root']="2.16.840.1.113883.1.3"; createSegment('templateId', clinicalDocument); createSegment('templateId', clinicalDocument, 1); createSegment('templateId', clinicalDocument, 2); clinicalDocument['templateId'][0]['@root']="2.16.840.1.113883.10.20.22.1.1"; clinicalDocument['templateId'][1]['@root']="2.16.840.1.113883.10.20.24.1.1"; clinicalDocument['templateId'][2]['@root']="2.16.840.1.113883.10.20.24.1.2"; clinicalDocument['documentationOf']['serviceEvent']['performer']['assignedEntity']['code']['@codeSystemName']="Healthcare Provider Taxonomy"; clinicalDocument['documentationOf']['serviceEvent']['performer']['assignedEntity']['code']['@displayName']="Adult Medicine"; logger.info("Data : "+clinicalDocument);
-10944321 0 Do following,
public void sendGmail(Activity activity, String subject, String text) { Intent gmailIntent = new Intent(); gmailIntent.setClassName("com.google.android.gm","com.google.android.gm.ComposeActivityGmail"); gmailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject); gmailIntent.putExtra(android.content.Intent.EXTRA_TEXT, text); try { activity.startActivity(gmailIntent); } catch(ActivityNotFoundException ex) { // handle error } }
-36803162 0 Youd need to pad your data with at least order n zeros; then you could set stride[n]==-stride[m] to achieve the intended effect, and avoid allocating order n*m zeros.
But something tells me there must be a more elegant solution to your problem, if you take a bigger-picture view.
-34800652 0The issue is that your app does not have a module named uwsgi. You change the directory to /home/user/appname but it looks like the actual module would be appname.uwsgi since the uwsgi.py file lives within /home/user/appname/appname/uwsgi.py.
Typically though, you don't need to specify both --wsgi-file and --module so I would either do
uwsgi --http :9010 --chdir /home/user/appname --wsgi-file /home/user/appname/appname/wsgi.py or
uwsgi --http :9010 --chdir /home/user/appname --module appname.uwsgi I personally prefer the second.
-20890855 0 Adding a ContactsContract.CommonDataKinds.Event to Android contacts, does not show upI'm trying to add a birthday event to contacts but the event doesn't show up when displaying the contact in the People app. When going into 'Edit' mode of the contact, an event DOES show up, but no selected date (see attached screenshot) as if the format is wrong.
When inspecting the contacts2.db in an sqlite viewer, it seems that the date are formatted just fine, like other events/birthdays that are properly showing (see attached image. First row is a manually entered birthday through the app, and the second row, was added by my app and doesn't show)
Here is the code I am using, which follows the SampleSyncAdapter from the $ANDROID_HOME sdk
public ContactOperations addBirthday(Date date) { mValues.clear(); if(date!=null) { mValues.put(ContactsContract.CommonDataKinds.Event.TYPE, ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY); mValues.put(ContactsContract.CommonDataKinds.Event.START_DATE, BIRTHDATE_FORMATTER.format(date)); mValues.put(ContactsContract.CommonDataKinds.Event.MIMETYPE, ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE); addInsertOp(); } return this; } private void addInsertOp() { if (!mIsNewContact) { mValues.put(ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID, mRawContactId); } ContentProviderOperation.Builder builder = newInsertCpo(ContactsContract.Data.CONTENT_URI, mIsSyncOperation, mIsYieldAllowed); builder.withValues(mValues); if (mIsNewContact) { builder.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, mBackReference); } mIsYieldAllowed = false; mBatchOperation.add(builder.build()); } 

how about that:
value = value > 0 ? value: ~value + 1 its based on the fact that negative numbers are stored as 2's complement to there positive equivalent, and that one can build the 2's complement by first building the 1's complement and adding 1, so
5 -> 0000 0101b -5 -> (1111 1010b) + 1 -> 1111 1011b what I did was basically to reverse this, so
-5 -> 1111 1011b 5 -> (0000 0100b) + 1 -> 0000 0101b I know it's a bit late but just had the same issue and landed here, hope this helps.
-22388214 0Yes, this is really supported, but it has been broken since February 3rd. It has now been fixed!
-16485114 0You can first delete, then write.
hadoop fs -rmr <path> removes everything under given path in hdfs including the path itself
rm -rf <path> removes in local file system.
Make sure that there is no other file in the directory.
-33865131 0 How to deleted record as false in SQL Server from winforms UI using c#?I have a problem to set deleted record as false in my SQL Server.I tried a lot.
My problem is i have a table in some Of the columns id,name etc...id as primary key constraint. When the user delete the record? so that record should be present on the table. i will make that record as false in my table?
In future he want to add the record with the deleted id? we give the chance to add a record with that id?
plz tell me the example of doing this? i tried a lot but i don't know. because primary key doesn't accept duplicates so i strucked here.
My delete stored procedure:
If user press the delete button in my UI:
This stored procedure is execute in my back-end:
update table set id=id*-1, flag=1 where id=@id and flag=0; In front i have shown record is deleted.
But if he want to add the record with that deleted id. Primary key voilation error from my database.when he insert the record.
Thanks
-24653870 0When you define operators like operator- inside your class as member functions, then when you use it
C3 = C1 + C2; The compiler is actually calling your member function like
C3 = C1.operator+(C2); From this you should be able to figure out that operators as member functions only takes one argument, and that the first object in the operator is the this object.
For stand-alone (non-member) functions they need two arguments.
You might want to check e.g. this reference on operator overloading.
-3900262 0If you have template<class T> class X; you don't expect X<3> to work and deduce that T is int, do you? The same is here IsFunc<FunctionA> is invalid, but IsFunc<void()> is fine. HTH
My new computer have Windows 8.1 64-bit Spanish version; the previous one had Windows XP and I never messed before with Credentials, Privileges, etc. In my computer there is just one user account that is marked as Administrator: "They have access to all files and programs stored in the computer". However, if I open a command-line window and execute chkdsk I get this:
Microsoft Windows [Versión 6.2.9200] (c) 2012 Microsoft Corporation. Todos los derechos reservados. C:\Users\Antonio> chkdsk Acceso denegado porque no tiene privilegios suficientes. Invoque esta utilidad ejecutándola en modo elevado. That is: "Access denied because you have not enough privileges. Invoke this utility executing it in elevated mode". I tried to use runas command, but I don't understand what parameters I must give.
I get the same result when I execute fsutil with these options:
C:\Users\Antonio> fsutil fsinfo ntfsInfo C: Error: Acceso denegado. How can I execute these programs in my computer? TIA
-13553946 0If you can't find a method, you can build one using ruby's include? method.
Official documentation: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-include-3F
Usage:
array = [1, 2, 3, 4] array.include? 3 #=> true Then, you can do a loop:
def array_includes_all?( array, comparision_array ) contains = true for i in comparision_array do unless array.include? i contains = false end end return contains end array_includes_all?( [1,2,3,2], [1,2,2] ) #=> true
-5591702 0 Any tutorial on building a VB6.0 form will do. Google is your friend.
Try this one: http://www.vbforums.com/showthread.php?t=445165
-26950797 0If you only need to find direct members, you can use Attribute Scope Query (ASQ). This requires domain/forest functional level of 2003 (forgot domain or forest).
DirectoryEntry groupEntry = new DirectoryEntry("LDAP://<server>/<group DN>", "user", "pwd"); DirectorySearcher searcher = new DirectorySearcher(groupEntry); searcher.SearchScope = SearchScope.Base; searcher.AttributeScopeQuery = "member"; searcher.Filter = "(&(objectCategory=person)(objectClass=user))"; searcher.PropertiesToLoad.Clear(); searcher.PropertiesToLoad.Add("name"); searcher.PropertiesToLoad.Add("mail"); searcher.PropertiesToLoad.Add("displayName"); foreach (SearchResult result in searcher.FindAll()) { Console.WriteLine(result.Path); } For nested group members, you may use the LDAP_MATCHING_RULE_IN_CHAIN matching rule. This requires domain/forest functional level of 2008 R2 (again, forgot domain or forest).
DirectoryEntry rootEntry = new DirectoryEntry("GC://<server>", "user", "pwd"); DirectorySearcher searcher = new DirectorySearcher(rootEntry); searcher.SearchScope = SearchScope.Subtree; searcher.Filter = "(&(objectCategory=person)(objectClass=user)(memberOf:1.2.840.113556.1.4.1941:=<group DN>))"; searcher.PropertiesToLoad.Clear(); searcher.PropertiesToLoad.Add("name"); searcher.PropertiesToLoad.Add("mail"); searcher.PropertiesToLoad.Add("displayName"); foreach (SearchResult result in searcher.FindAll()) { Console.WriteLine(result.Path); } Limitations:
I Have a requirement to model some BPMN data from within Excel. I would like to have standard Excel data in spreadsheet format but somehow get the link data into a standard BPMN 2.0 file so that I can import the generated data with ease. What is the best technology/framework that can be used here?
Below is an example of a possible file structure
I would appreciate any help with some guidance about generating a bpmn file, I am willing to use XSLT or a script to parse the data to BPMN.. just really dont know where to start. Thanks!
-33733533 0 How configure fsync for specific command in redisI try to find about custom AOF configuration. I found only that:
There are three options:
- fsync every time a new command is appended to the AOF. Very very slow, very safe.
- fsync every second. Fast enough (in 2.4 likely to be as fast as snapshotting), and you can lose 1 second of data if there is a disaster.
- Never fsync, just put your data in the hands of the Operating System. The faster and less safe method.
Can I configure fsync which every time append a command to the AOF only for specific command (INCR)? Is it possible ?
-14289000 0Windows Azure machines are yours for the using so if you want a different time zone, go right ahead and set it.
The easiest approach is to create a very simple startup task and use tzutil, the Windows Time Zone Utility. We use the following:
tzutil /s "GMT Standard Time" This is installed by default only on the Windows Server 2008 R2 or Windows Server 2012 images.
Full details are here: http://wely-lau.net/2011/06/26/setting-timezone-in-windows-azure-3/
-6607522 0I don't know about such tool. You can write your own generator using database metadata info: Connection.getMetadata()
You just need to multiply your concepts by your documents:
(20(currentConceptCount*currentDocumentCount) * 10(previousTime)) / 100(previousConceptCount*previousDocumentCount)
-37709154 0 in project.json you need this dependency
"Microsoft.Extensions.Localization": "1.0.0-rc2-final", in Startup.cs in ConfigureServices you need code like this:
services.AddLocalization(options => options.ResourcesPath = "GlobalResources"); services.Configure<RequestLocalizationOptions>(options => { var supportedCultures = new[] { new CultureInfo("en-US"), new CultureInfo("en"), new CultureInfo("fr-FR"), new CultureInfo("fr"), }; // State what the default culture for your application is. This will be used if no specific culture // can be determined for a given request. options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US"); // You must explicitly state which cultures your application supports. // These are the cultures the app supports for formatting numbers, dates, etc. options.SupportedCultures = supportedCultures; // These are the cultures the app supports for UI strings, i.e. we have localized resources for. options.SupportedUICultures = supportedCultures; // You can change which providers are configured to determine the culture for requests, or even add a custom // provider with your own logic. The providers will be asked in order to provide a culture for each request, // and the first to provide a non-null result that is in the configured supported cultures list will be used. // By default, the following built-in providers are configured: // - QueryStringRequestCultureProvider, sets culture via "culture" and "ui-culture" query string values, useful for testing // - CookieRequestCultureProvider, sets culture via "ASPNET_CULTURE" cookie // - AcceptLanguageHeaderRequestCultureProvider, sets culture via the "Accept-Language" request header //options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(async context => //{ // // My custom request culture logic // return new ProviderCultureResult("en"); //})); }); in Configure you need code something like this:
var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>(); app.UseRequestLocalization(locOptions.Value); I have some working demo code here, if you need more
-2004576 0CheckStyle to enforce coding standard, Cobertura for checking code coverage.
On a related note also check the book Java Power Tools
which covers around 30 open source tools that help to do better development with Java
Your code gives me the following compiler error, skipping some bits
/usr/include/boost/spirit/home/support/action_dispatch.hpp:142:13: error: no matching function for call to ‘action_dispatch<>::do_call( const main()::<lambda(const string&)>&, action_dispatch<>::fwd_tag<std::vector<char>>, ... which boils down to that the argument passed to your lambda is vector<char>, not string
So, replace string with vector<char>:
(+qi::alpha)[[](const std::vector<char>& s) { cout << std::string(s.begin(), s.end()) << '\n'; }]
-28846159 0 I have identified a workaround.
I'm using a tuple for the constraint and handling it myself in the didApplyConstraints handler.
The format for the custom constraint assumes that the range begins at the first value and travels counter clockwise until the second value. It makes no allowances for constraint values above PI or below -PI. This solution also doesn't deal with total ranges greater than 2*PI.
Ranges that do not cross the +/- PI boundary are "normal" and can be handled normally.
Ranges that DO cross the +/- PI boundary are "goofy" and must be handled as a special case (if possible).
A solution to the special case seems impossible unless you are tracking angular velocity with an SKPhysicsBody (or manually). This value is required to identify which boundary the node likely "crossed" and should thus be constrained to.
// constraint = (CGFloat(M_PI/2), -CGFloat(M_PI/2)) override func didApplyConstraints() { var r = rotationSprite.zRotation if constraint.0 < constraint.1 { // regular constraint, easy to handle. rotationSprite.zRotation = min(max(r, constraint.0),constraint.1) } else // "goofy" constraint that crosses PI boundary { if r < constraint.0 && r > constraint.1 { if rotationSprite.physicsBody?.angularVelocity < 0 { // clockwise, crossed first value (so long as absolute angular vel is < 2PI rotationSprite.zRotation = constraint.0 } else if rotationSprite.physicsBody?.angularVelocity > 0 // counter clockwise, crossed second value (so long as absolute angular vel is < 2PI { rotationSprite.zRotation = constraint.1 } else { // If 0 velocity (or no velocity), no way to find out which boundary was crossed. rotationSprite.zRotation = constraint.0 // Probably better to default to closest angle } rotationSprite.physicsBody?.angularVelocity = 0 // Alternately, multiply by a negative restitution factor. } } }
-40054710 0 Run Breeze Entity Manager in Node How is everyone else testing their breeze client-side entity functions?
I have entity Ticket that has Tags navigation property with hundreds of Tags.
Each Tag has many boolean properties IsChanged, IsTagged, IsReplaced, etc
Each tag also has an Item navigation property. The Item has ItemType (ItemType is another entity with properties like TestFrequency), IsCondemened, etc
I have functions on the Ticket and Tag and Item entities, that filter, map, and reduce over all the related entities, to summarize all the tags and items for each Ticket.
I need to test these functions, and I'm finding that to create all these objects by hand for my tests is a ton of duplication of code.
If I could just have a json file on disk with some sample entities straight from the database, then not only would it eliminate a bunch of boilerplate factory code, but I could be sure that whenever my data schema changes in EF on server side, my json would also change to reflect that.
Here's where I'm scratching my head:
I need to be able to run breeze-client in node so my npm script can grab the data and save it to disk with one command.
I cannot find ONE complete solution ANYWHERE for using breeze-client in node.
There is another question that asks about it 3 years ago, and no definitive working answer was ever given.
Also this github issue last year, with one comment coming really close to a full answer, but the actual implementation of the adapter was never shared.
With the vast number of people who use the breeze library, I feel like I'm doing something wrong when the only way I can see to reliably test my entities is to run breeze-client in node, and NO ONE ELSE seems interested in running breeze-client in node.
I was trying to figure out how to create an ajaxAdapter myself for node, but I keep striking out.
Please can someone either give me a clue for how to make a node ajaxAdapter, or tell me a better way to be testing my business logic on my breeze entities?
-2774789 0 PDF generated with jasperreport not showing well on Linux but yes on Mac, could the os be related?A PDF I generate with jasper reports renders Ok in my MAC but some labels show wrong on Linux. For example, I have a static label that doesn't show completely on linux (only a part of the whole word) but yes on Mac. Can the OS be somehow related? What is the usual source of this kind of problems?
-22567320 0 Django edit user profileI'm trying to create an "Edit Profile" form in the fronted. What happens is that my form(i'm not 100% sure) tries to create a user instead of finding the current user and update his profile. So I think that's the issue. Checked many questions here but none was clear enough. The fields I'm trying to edit are email, first name and last name. (Also I would like to add uda
forms.py
class UpdateProfile(forms.ModelForm): username = forms.CharField(required=True) email = forms.EmailField(required=True) first_name = forms.CharField(required=False) last_name = forms.CharField(required=False) class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name') def clean_email(self): username = self.cleaned_data.get('username') email = self.cleaned_data.get('email') if email and User.objects.filter(email=email).exclude(username=username).count(): raise forms.ValidationError('This email address is already in use. Please supply a different email address.') return email def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() return user views.py
def update_profile(request): args = {} if request.method == 'POST': form = UpdateProfile(request.POST) form.actual_user = request.user if form.is_valid(): form.save() return HttpResponseRedirect(reverse('update_profile_success')) else: form = UpdateProfile() args['form'] = form return render(request, 'registration/update_profile.html', args)
-35699252 0 You might as well disable it from being clicked and it does not listen to action anymore
-1487194 0 Subclasses causing unexpected behavior in superclasses — OO design questionAlthough I'm coding in ObjC, This question is intentionally language-agnostic - it should apply to most OO languages
Let's say I have an "Collection" class, and I want to create a "FilteredCollection" that inherits from "Collection". Filters will be set up at object-creation time, and from them on, the class will behave like a "Collection" with the filters applied to its contents.
I do things the obvious way and subclass Collection. I override all the accessors, and think I've done a pretty neat job - my FilteredCollection looks like it should behave just like a Collection, but with objects that are 'in' it that correspond to my filters being filtered out to users. I think I can happily create FilteredCollections and pass them around my program as Collections.
But I come to testing and - oh no - it's not working. Delving into the debugger, I find that it's because the Collection implementation of some methods is calling the overridden FilteredCollection methods (say, for example, there's a "count" method that Collection relies upon when iterating its objects, but now it's getting the filtered count, because I overrode the count method to give the correct external behaviour).
What's wrong here? Why does it feel like some important principles are being violated despite the fact that it also feels like OO 'should' work this way? What's a general solution to this issue? Is there one?
I know, by the way, that a good 'solution' to this problem in particular would be to filter the objects before I put them into the collection, and not have to change Collection at all, but I'm asking a more general question than that - this is just an example. The more general issue is methods in an opaque superclass that rely on the behaviour of other methods that could be changed by subclasses, and what to do in the case that you want to subclass an object to change behaviour like this.
-36516637 0It is a very clear algorithm and seems you got it right. So for changing the way of accessing the characters, why didn't you use the String#charAt method?
Also you may want to change the return type of the method from String "YES" or "NO" to true or false of type boolean:
static boolean isValidBracketString(String string) { Stack<Character> stack = new Stack<>(); for(int i=0; i< string.length(); i++){ if(string.charAt(i) == '{' || string.charAt(i) == '[' || string.charAt(i) == '('){ stack.push(string.charAt(i)); } else if(string.charAt(i) == '}' || string.charAt(i) == '}' || string.charAt(i) == ')') { if(stack.size() == 0) return false; switch(stack.pop()){ case '(': if(string.charAt(i) != ')') return false; break; case '[': if(string.charAt(i) != ']') return false; break; case '{': if(string.charAt(i) != '}') return false; break; } } } return stack.size() == 0; }
-10185458 0 Finding Bitrate of video file How can we find bitrate of a video file in c++? Can we do this by file handling?
Thanks
-5511715 1 Python - Understanding error: IndexError: list index out of rangeI'm fairly new to python. I have an error that I need to understand.
The code:
config.py:
# Vou definir os feeds feeds_updates = [{"feedurl": "http://aaa1.com/rss/punch.rss", "linktoourpage": "http://www.ha.com/fun.htm"}, {"feedurl": "http://aaa2.com/rss.xml", "linktoourpage": "http://www.ha.com/fun.htm"}, {"feedurl": "http://aaa3.com/Heaven", "linktoourpage": "http://www.ha.com/fun.htm"}, {"feedurl": "http://aaa4.com/feed.php", "linktoourpage": "http://www.ha.com/fun.htm"}, {"feedurl": "http://aaa5.com/index.php?format=feed&type=rss", "linktoourpage": "http://www.ha.com/fun.htm"}, {"feedurl": "http://aaa6.com/rss.xml", "linktoourpage": "http://www.ha.com/fun.htm"}, {"feedurl": "http://aaa7.com/?format=xml", "linktoourpage": "http://www.ha.com/fun.htm"}, {"feedurl": "http://aaa8/site/component/rsssyndicator/?feed_id=1", "linktoourpage": "http://www.ha.com/fun.htm"}] twitterC.py
# -*- coding: utf-8 -*- import config # Ficheiro de configuracao import twitter import random import sqlite3 import time import bitly_api #https://github.com/bitly/bitly-api-python import feedparser ... # Vou escolher um feed ao acaso feed_a_enviar = random.choice(config.feeds_updates) # Vou apanhar o conteudo do feed d = feedparser.parse(feed_a_enviar["feedurl"]) # Vou definir quantos feeds quero ter no i i = range(8) print i # Vou meter para "updates" 10 entradas do feed updates = [] for i in range(8): updates.append([{"url": feed_a_enviar["linktoourpage"], "msg": d.entries[i].title + ", "}]) # Vou escolher ums entrada ao acaso print updates # p debug so update_to_send = random.choice(updates) print update_to_send # Para efeitos de debug And the error that appears sometimes because of the nature of the random:
Traceback (most recent call last): File "C:\Users\anlopes\workspace\redes_sociais\src\twitterC.py", line 77, in <module> updates.append([{"url": feed_a_enviar["linktoourpage"], "msg": d.entries[i].title + ", "}]) IndexError: list index out of range I'am not getting to the error, the list "feeds_updates" is a list with 8 elements, I think is well declareted and the RANDOM will choose one out of the 8...
Can someone give me a clue on what is happenning here?
PS: Sorry for my bad english.
Best Regards,
-5285569 0 Reflection Type vs TypeDescriptorLately I have been using reflection to work in my project, and I have the current question.
While in Type.GetProperties(Flags), we can filter the properties we get using 'Flags'; in TypeDescriptor.GetProperties(), we don't.
In type.GetProperties I can filter to get only properties not inherited. Is it possible to do the same with TypeDescriptor.GetProperties() (only properties not inherited)?
Thank you
-19006197 0 IIS NullReferenceException when deployed but not in Dev ServerI have developed an IIS Application using C# code behind ASPX pages with entity framework for database access. When I run it in the Visual Studio Development Server it works fine but if I either Publish it to IIS or run it on the Local IIS Web Server from Visual Studio (which is pretty much the same as Publishing I guess) I get
NullReferenceException: Object reference not set to an instance of an object.] System.Web.Hosting.RecyclableCharBuffer.Append(String s) +15 System.Web.Hosting.ISAPIWorkerRequest.SendUnknownResponseHeader(String name, String value) +93 System.Web.HttpResponse.WriteHeaders() +233 System.Web.HttpResponse.Flush(Boolean finalFlush) +219 System.Web.HttpRuntime.FinishRequest(HttpWorkerRequest wr, HttpContext context, Exception e) +127 This Exception is thrown after my Home.aspx has finished it's Page Load. Some simple ASPX pages work ok. Setting a NullReferenceException break point just drops into disassembly.
I am stuck for ideas about how to track this issue down. Any thoughts???
-16343319 0Thank you! I have an embedded TextEdit in the last row of ListView embedded in the alert dialog fragment. I used your solution of clearing the flags as a post runnable and now it works perfectly.
@Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setTitle("My Title"); m_adapter = new MyAdapter(getContext()); builder.setAdapter(m_adapter, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }); final AlertDialog dialog = builder.create(); final ListView listView = dialog.getListView(); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { } }); listView.post(new Runnable() { @Override public void run() { dialog.getWindow().clearFlags( WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); } }); return dialog; }
-9716854 0 Changing the 'src' attribute of an image using javascript I'm using javascript, so that when a refresh button is clicked it begins to spin around until the refresh is completed. This is my function:
function RefreshHome() { // Refreshes the home page via the image link. // Make the refresh link animate. var refresh = document.getElementById("refresh_button"); refresh.src = "images/refresh_animated.gif"; // Refresh the page. window.location = "home.aspx"; return false; } This worked perfectly for a while then, as far as I can see, inexplicably stopped working! When the refresh button is clicked on now, the image just disappears.
Does anybody know why this might happen?
-5081180 0My buddy wrote an entry on this exact thing a while back:
http://blogs.collab.net/subversion/2007/03/authz_and_anon_/
He has a few suggestions in there about how you might handle this, although I'm not guaranteeing you'll agree with the options.
-23315169 0 How to add NSDictionary to NSArray to use it in tableviewNSDictionary *recipe = arrayOfPlist[i];
that I use it in a for loop
and in a if statement I added this dictionary to an NSArray results= [recipe allValues]; like this
and I segue it like this
destViewController.filteredContent=results; I checked it the results array is not null but when I compile it and try to go to a PageView with selected array I'm having this exception
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFString 0x109268e40> valueForUndefinedKey:]: this class is not key value coding-compliant for the key recipeName.' RecipeName is a key from my Dictionary which I use it to write to cell.
I couldn't see the problem so I came here.
It turned out that s not my real problem. The crash happened at the next view controller which is a pageViewController. I passed the results array and it should only have 1 elements in it but when i checked it it says the count 8= number of keys in my dictionaries. It added all of the keys as a unique array element and thats where the problem happened. There is really not a recipeName ...
how can i fix this??
<plist version="1.0"> <array> <dict> <key>category</key> <string>desert</string> <key>numberOfPerson</key> <string>3</string> <key>recipeImage</key> <string>asdd.jpg</string> <key>time</key> <string>15</string> <key>recipeName</key> <string>Puding</string> <key>recipeDetail</key> the count is 8 for this reason. It consider each key as an array element.
-21319479 0I did something like this years ago in VB6. Copied below is the code. As you can see, the code just steps through the HTML character-by-character and removes everything between (and including) the < and > tags. Hopefully you can do something similar in whatever tool you are using.
Function CleanTags(HTML As String) As String Dim result As String, b As Boolean, c As String, i As Long b = False For i = 1 To Len(HTML) c = Mid(HTML, i, 1) If c = "<" Then b = True If b = False Then result = result & c If c = ">" Then b = False Next i CleanTags = result End Function
-32928102 0 This is C not C++ (eventhough C++ brings enough C compatibility to make that code valid using a conforming C++ compiler with #include <stdio.h>).
The specifier %c is for characters. You're reading and writing int.
Thus, you should use %i.
int a; int b; printf("a"); scanf("%i", &a); printf("b"); scanf("%i", &b); a=a+b; printf("%i", a); Output
a5 b7 12
-17955241 0 Because you are using strings rather than parameters, your example is vulnerable to SQL injection. It's best to avoid pg_ functions. In your case there are two things you need to take into account:
or
Normally you use stored procedures in addition to PDO, unfortunately sometimes this is not manageable because you have too much code. My advice is to use as much stored procedures as possible.
-15043393 0 Unexplained heroku timeoutsI have a rails 3.2.11 app deployed on Heroku that has been fairly stable over time. In the last 24 hours, pingdom has been reporting Timeouts which I can't find any "H1X" related errors in the logs at the same time.
I am occassionally able to reproduce the timeouts in google chrome. where I would get this message after about 30 seconds of requesting any page:
Chrome browser error No data received Unable to load the webpage because the server sent no data. Here are some suggestions: Reload this webpage later. Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data.
The app will then begin serving requests normally until it happens again.
I know this is not enough info, but I can't find anything useful yet in newrelic or scanning the logs that correlates to when the error occured.
In one instance, i was reproducing the error in the browser while viewing the heroku logs and when the timeout occurred, there was no evidence of the request showing up in the logs. Its like the failed requests never make it into the app.
-35871671 0Figured that the build was failed because of parameter CONFIGURATION_BUILD_DIR=jenkinsOutput. I've got rid of it and build succeeded. Confusing error message.
I have a string that is being put into a JSONObject. It looks like this before it is passed:
Before: /storage/sdcard/Download/signature-1383757302516.jpg After: \/storage\/sdcard\/Download\/signature-1383757302516.jpg Here is what my code looks like:
// make JSON object to hold the information, which is sent to the server JSONObject jsonObjSend = new JSONObject(); jsonObjSend.put("signature", signatureFile.getAbsolutePath()) The output for jsonObjSend().toString() is:
\/storage\/sdcard\/Download\/signature-1383757302516.jpg Is JSONOBject encoding the information? How do I prevent it from modifying the forward slash?
*EDIT: I solved it using regex to remove the escape characters.
jsonObjSend.toString().replaceAll("\\\\/", "/")
-35587438 0 SSRS Render Multiple Pages from Report in C# I have a service that renders a report from SSRS which works perfectly fine with one page, however when I tried to change the code to render multiple pages separately I can't seem to get it to work as expected.
I used a guide on the MSDN blogs (http://blogs.msdn.com/b/bryanke/archive/2004/02/11/71491.aspx#code) to try and achieve this, but my StreamIDs doesn't seem to be working as I expected.
Here's my code from the Render() method onwards (the rest seems to be okay, but I can provide on request):
var firstPage = rsExec.Render(format.ToString(), deviceInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); var numberOfPages = streamIDs.Length + 1; results = new Byte[numberOfPages][]; results[0] = firstPage; if (numberOfPages > 1) { for (int i = 1; i < numberOfPages; i++) { deviceInfo = $@" <DeviceInfo> <OutputFormat>JPEG</OutputFormat> <StartPage>{i + 1}</StartPage> </DeviceInfo>"; results[i] = rsExec.Render(format.ToString(), deviceInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); } } This generates the report okay, but I expected the streamIDs to become the number of extra pages required, but it always only has one entry in it. Am I doing something stupidly wrong here?
I'm using SQL Server 2008 R2.
-25674559 0you could also add it directly in your page-template (this is called 'inline styling'):
a couple of lines below your opening body tag you'll find
<div> <a href="http://forum.banaisbul.com"><img src="http://forum.banaisbul.com/wp-content/uploads/2014/09/banaisbulsiyah.jpg" border="0" alt="Link to this page"></a> </div> and you need to change it to
<div style="background-color:#404040"> <a href="http://forum.banaisbul.com"><img src="http://forum.banaisbul.com/wp-content/uploads/2014/09/banaisbulsiyah.jpg" border="0" alt="Link to this page"></a> </div>
-3488058 0 <Edit> Although one object can access private properties of all objects of the same class, you cannot access protected methods of an object from other class even if the protected method is defined in a common super class.
So while this code compiles:
public class Test { private int x; private void change(Test test) { test.x = test.x + 1; } public static void main() { Test test1 = new Test(); Test test2 = new Test(); test1.change(test2); } } The following code will not compile:
public class Test2 { public static void main() { Test1 test1 = new Test1(); test1.clone(); // The method clone() from the type Object is not visible } } </Edit>
Being able to call toString(), equals(Object), hashCode() and getClass() on all objects makes things a lot easier.
clone() and finalize() are protected. So in order to be able to call them from the outside the subclass has to increase the visibility. And that is obviously a design decision.
To be honest, i have no idea why Sun decided that all object are "locks" and have notify(), notifyAll(), wait(long), wait(long, int). From my point of view those method should not be in Object at all but in a specialized Lock-class. But I guess there was a good reason to have them there in the very early days and it cannot be changed nowadays without breaking compatibility.
this way i was trying to convert dropdown value to array by jquery but routine is not working.
<select name="DropDownList1" id="DropDownList1"> <option value="00">00</option> <option value="05">05</option> <option value="10">10</option> <option value="15">15</option> </select> function cboValueToArray(targetid) { var $target = $("select[id*=" + targetid + "]"); var results = []; $($target).each(function () { var val = $(this).val(); if (val !== '') results.push(val); }); alert(results.toString()); return results; } alert(cboValueToArray('DropDownList1').toString()); this line $($target).each() is causes problem. guide me how to fix this. thanks
Hide the Prelude's (!!) operator and you can define your own (!!) operator:
import Prelude hiding ((!!)) (!!) :: MyType1 -> MyType2 -> MyType3 x !! i = ... -- Go wild! You can even make a type class for your new (!!) operator if you prefer.
How i can draw a lot of image in canvas?
I have a lot of images url array and need output it. How to do with good perfomance.
me example code (jsfiddle: http://jsfiddle.net/6sunguw4/):
$(document).ready(function () { var bgCanvas = document.getElementById("bgCanvas"); var bgCtx = bgCanvas.getContext("2d"); bgCanvas.width = window.innerWidth; bgCanvas.height = window.innerHeight + 200; var array = new Array(); array[1] = 'https://developer.chrome.com/webstore/images/calendar.png'; array[2] = 'http://www.w3schools.com/html/html5.gif'; array[3] = 'http://www.linosartele.lt/wp-content/uploads/2014/08/images-9.jpg'; img0 = new Image(); img0.onload = function() { bgCtx.drawImage(img0, 0,0, 100, 100); } img0.src = array[1]; img2 = new Image(); img2.onload = function() { bgCtx.drawImage(img2, 100,0, 100, 100); } img2.src = array[2]; img3 = new Image(); img3.onload = function() { bgCtx.drawImage(img3, 200,0,100,100); } img3.src = array[3]; });
-6234021 0 Reflection and Private Native Methods I am using reflection to dynamically call some methods from extended class. Unfortunately one of these methods is declared as private native and as soon as I make the call... I receive the following exception:
java.lang.IllegalAccessException: Class com.something.somewhere.MyThing ca n not access a member of class com.something.somewhere.AnotherThing with modifier s "private native" Is there a way around this?
-23105566 0 JQuery button click function not workingI'm new to JQuery and my problem is that I have a button in a modal such that when I click it, a JQuery script is run. Pieces of code so far:
<a id="submitMe" class="btn btn-default btn-primary">Submit</a> $(document).ready(function (){ $("#submitMe").click(function(){ alert("Something to alert"); }); }); Thanks for all your help!
-858207 0If you can modify the configuration file on the server here's what you can do to get the exception information through the service.
You need to add a service behavior section to the server's config.
<behaviors> <serviceBehaviors> <behavior name="serviceNameBehavior"> <serviceDebug includeExceptionDetailInFaults="True" /> </behavior> </serviceBehaviors> </behaviors> Then associate the service with that behavior.
<service name="serviceName" behaviorConfiguration="serviceNameBehavior" ...
-9824833 0 The problem is that you are loading the lang file from inside a function, which means that $lang does not get placed into the global scope but rather the local function scope.
Minimum required change to make it work (but not a good idea)
Assuming you want $lang to be placed inside the global scope, you could do so explicitly:
public function lang($file, $language){ require 'languages/'.$language.'/'. $file . '.php'; $GLOBALS['lang'] = $lang; // "export" to global scope } A much better idea
There are several things that can be improved:
$lang "behind the caller's back" -- that's not good design, and it makes the code harder to maintainYou can kill both birds with one stone by storing the language file contents inside a static local variable and returning it from the function: there is no more writing to the global scope, and the variable keeps its contents so you don't have to reload the language file every time. It would look like this:
public function lang($file, $language){ static $cache = array(); if (empty($cache[$language][$file])) { // load language files on demand require 'languages/'.$language.'/'. $file . '.php'; $cache[$language][$file] = $lang; } return $lang; // return requested data, which is now definitely cached } And to use it, you would do:
$lang = $this->lang('global', 'en'); Dumping raw variables into the global scope like this is not always the best idea, but depending on the circumstances (small projects) it might be OK.
-37785931 0 store array data retrieved from forms to databaseI have a form. And there is add button to add more forms according to requirement. The Working demo is in JSFiddle. https://jsfiddle.net/szn0007/eanhpLkg/
My PHP code is :
$data['client_name'] = $_POST['client_name']; $data['address'] = $_POST['address']; $data['fiber_length'] = $_POST['fiber_length']; $data['phone_number'] = $_POST['phone_number']; $data['package'] = $_POST['package']; $data['result'] = $_POST['result']; $data['remarks'] = $_POST['remarks']; foreach($data['client_name'] as $c ) { $sql = "INSERT INTO ct_staff_activity_ftth(client_name) VALUE('$c') "; $this->db->query($sql); } How can i insert all the dataas entered at once.
-261667 0You can find the error codes here
-32201061 0 Google Pie Chart Using ArrayI have tried to implement the following code using an array of two sets of values but the line graph does not show:
function drawChart() { var lineTotalDistance = <?php echo json_encode($DistanceTotalArray) ?>; var lineSpeed = <?php echo json_encode($SpeedArray) ?>; //alert(lineTotalDistance.length); //alert(lineSpeed.length); var data = new google.visualization.DataTable(); data.addColumn('number', 'Total Distance'); data.addColumn('number', 'Speed KM/H'); for(var i=0;i < lineTotalDistance.length; i++) { data.addRows([ [lineTotalDistance, lineSpeed ] ]); } }
-4993145 0 $sql = "SELECT * FROM my_table"; $ressource_sql = execute_sql($sql); while ($row = mysql_fetch_assoc($ressource_sql)) { $ligne_hve.=$row['id'] . ';'; $ligne_hve.= iconv(input charset, 'windows-1252//TRANSLIT', $row['name']) . ';'; $ligne_hve.= iconv(input charset, 'windows-1252//TRANSLIT', $row['products']) . ';'; $ligne_hve .= "\n"; } $file_hve = fopen($file_export_hve, "w+"); fwrite($file_hve, $ligne_hve); fclose($file_hve); The input charset is iso-8859-1.
-31834593 0 Target framework dnx451 or net451 in class library projectsFrom what I understand, the target frameworks dnx451 and net451 both use the desktop .NET Framework 4.5.1. dnx451 is especially intended for DNX runtime application and supports ASP.NET 5.
If we have a solution with a ASP.NET 5 project and multiple class libraries, should they all target dnx451 or does only the web project need to target dnx451? Could the class libraries just target net451?
There is never a guarantee that you will not get stuck in a local optimum, sadly. Unless you can prove certain properties about the function you are trying to optimize, local optima exist and hill-climbing methods will fall prey to them. (And typically, if you can prove the things you need to prove, you can also select a better tool than a neural network.)
One classic technique is to gradually reduce the learning rate, then increase it and slowly draw it down, again, several times. Raising the learning rate reduces the stability of the algorithm, but gives the algorithm the ability to jump out of a local optimum. This is closely related to simulated annealing.
I am surprised that Google has not helped you, here, as this is a topic with many published papers: Try terms like, "local minima" and "local minima problem" in conjunction with neural networks and backpropagation. You should see many references to improved backprop methods.
-18634136 1 Why do I get IndexError: list index out of range?I keep getting the IndexError with a list. My code looks like this:
for x in range(len(MAIN_list[0])): print(x) print(MAIN_list[9][x]) print(MAIN_list[10][x]) print(MAIN_list[0][x] + "; " + MAIN_list[1][x] + \ "; " + MAIN_list[2][x] + "; " + MAIN_list[3][x] + \ "; " + MAIN_list[4][x] + "; " + MAIN_list[5][x] + \ "; " + MAIN_list[6][x] + "; " + MAIN_list[7][x] + \ "; " + MAIN_list[8][x] + "; " + MAIN_list[9][x] + \ "; " + MAIN_list[10][x]) Now, the output is:
0 cross tick Traceback (most recent call last): File "C:\Users\Michele2\Desktop\Arcrate\MyCASH\Python Code\Scraping\Scraping1.3(clean)TEST.py", line 246, in <module> "; " + MAIN_list[10][x]) IndexError: list index out of range I know that you'd usually get this error for variables outside the actual length of the list, but here I get the right output when I call it singularly (ie. row 3 of the output) but not when I try to print the list as a whole. Any though would be welcome.
Thanks
-3081292 0I'm assuming this doesn't happen the first run through, but after some time. Is this correct?
edit: removed incorrect assumption, but there's still an issue with IDisposable
You're not disposing of NewImage, and this will cause you issues in production.
I'd normally say 'just use a using', but try/finally is the same thing. Refactor to us a using at your own discretion.
System.Drawing.Image NewImage = null; System.Drawing.Image FullsizeImage = null; try { FullsizeImage = System.Drawing.Image.FromFile(OriginalFile); [... snip ... ] NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero); // Clear handle to original file so that we can overwrite it if necessary FullsizeImage.Dispose(); // Save resized picture NewImage.Save(NewFile); } finally { if (FullsizeImage != null) FullsizeImage.Dispose(); if (NewImage != null) NewImage.Dispose(); }
-34977147 0 Bind Two DataGridView ComboBoxColumn to the same Datasource I have a DataGridView with two ComboBoxColumns.
One shall show ID of a Person and the other the Name of the same person.
I want to bound both to the same DataSource so both will be Synchronized.
When I use the same DataSource for a regular ComboBox (not inside a DataGridView), it's synchronized. Why isn't it Synchronized when using it inside a DataGridView?
-34476128 0First, to specify E explictly, you could use the more verbose lambda syntax. This would look like this:
myObservable.handleError { it : IOException -> it.printStackTrace() } Alternativly, you could add an additional parameter to help the compiler infer the type. This could look something like this:
public inline fun <reified E : Throwable, R> Observable<R>.handleError( typeHint: (E) -> Unit, crossinline handler: (E) -> Unit ) = onErrorResumeNext f@{ return@f when (e) { is E -> { handler(e); Observable.empty() } else -> Observable.error(e) } } fun <T> of() : (T) -> Unit = {} Usage:
myObservable.handleError(of<IOException>()) { it.printStackTrace() }
-11585253 0 background-size: 100% should do the trick.
Here, http://jsfiddle.net/xGQtF/6/
-27273825 0Can you please share which upload type you require? It seems that this code has a mix of both signed and unsigned uploads. For example, you use the unsigned_upload_tag method while also passing the timestamp, api_key and signature which are required only for signed uploads.
In header file .h
@interface MemoryAppDelegate:NSObject <UIApplicationDelegate> { Class1 *class1_obj; } In Implementation file .m
@implementation Memory : (UIApplication*) application { NSLog(@"Retain Count of class1_obj %d",[class1_obj retainCount]); //ouput retainCount is 0 Class2 *class2_obj; NSLog(@"Retain Count of class2_obj %d",[class2_obj retainCount]); // gives EXC_Bad_Access error As in the above code, when I declare a object in header file and try to access its retain count is gives me 0. But if I declare the object in implementation file and access its retainCount it throws Bad_Access. Kindly can you say why this error occurs?
-10531745 0(1) I always add this as you suggested
config.assets.initialize_on_precompile = false (2) But also, if using ActiveAdmin and/or Devise, exclude their routes when precompiling assets by coding routes.rb as follows
unless ARGV.join.include?('assets:precompile') ActiveAdmin.routes(self) devise_for :admin_users, ...etc.... devise_for :users, ...etc... devise_scope :user do get "/login", ..etc end as per here and elsewhere
-36841914 0 How do I get the column count of a table when there are cells with rowspan/colspan?How do I get the column count of a table when there are cells with rowspan/colspan?
UPDATE: In this question I mean the classical (as far as I know) use of tables, when it's necessary to use the colspan, though it's not required by the specification (and table will look ugly but it will be valid).
I need JavaScript/jQuery to get 11 for the following table (as 11 is the maximum number of columns for this table):
<table border="1"> <thead> <tr> <th rowspan="3">Lorem</th> <th rowspan="3">ipsum</th> <th rowspan="3">dolor</th> <th colspan="4">sit</th> <th colspan="4">amet</th> </tr> <tr> <th colspan="3">consectetur</th> <th rowspan="2">adipisicing</th> <th rowspan="2">elit</th> <th rowspan="2">sed</th> <th rowspan="2">do</th> <th rowspan="2">eiusmod</th> </tr> <tr> <th>tempor</th> <th>incididunt</th> <th>ut</th> </tr> </thead> <tbody></tbody> </table> https://jsfiddle.net/toahb3a3/
My personal solution is:
$(function(){ var max = 0; $('tr').each(function(){ var current = 0; $(this).find('th').each(function(){ var colspan = $(this).attr('colspan'); current += Number(colspan ? colspan : 1); }); max = Math.max(current, max); }); console.log(max); }); https://jsfiddle.net/mt7qhbqd/
UPDATE: To solve this problem we need the sum of th elements plus their colspan in the very first row of thead. Thanks to Andy for his code, it's really compact and it gave me the thought that I need only the first row. Also, thanks to Quentin who pointed me to the case when colspan is not necessarily used, so Andy's alogrithm won't work (but Quentin's will). Also thanks to Quentin for helping me with the title, as my English isn't good enough.
Can anybody explain why my question is voted negatively? What's wrong with it
-26489068 0"Exception: The null object does not have a method 'querySelector'."
Could that error possibly be because the <polymer-element> definition has no <template>? Perhaps a shadow DOM is never created in that instance, so shadowRoot is null. Just guessing here...
I wonder, also, if this..append() attaches elements to the shadow DOM. Seems unlikely.
The functionality available in IOUtils is all you need. This code (tested on my Nexus 7) populates a TMemo with the files in your folder (if there are any):
uses IOUtils; procedure THeaderFooterForm.SpeedButton1Click(Sender: TObject); var DirList: TStringDynArray; DirPath: string; s: string; begin DirPath := TPath.Combine(TPath.GetDocumentsPath, 'assets'); DirPath := TPath.Combine(DirPath, 'internal'); // Display where we're looking for the files Memo1.Lines.Add('Searching ' + DirPath); if TDirectory.Exists(DirPath, True) then begin // Get all files. Non-Windows systems don't typically care about // extensions, so we just use a single '*' as a mask. DirList := TDirectory.GetFiles(DirPath, '*'); // If none found, show that in memo if Length(DirList) = 0 then Memo1.Lines.Add('No files found in ' + DirPath) else // Files found. List them. begin for s in DirList do Memo1.Lines.Add(s); end; end else Memo1.Lines.Add('Directory ' + DirPath + ' does not exist.'); end;
-38630923 0 Use:
Ext.Date.format(timestampDate ,'Y-m-d H:i:s') Y - A full numeric representation of a year, 4 digits.m - Numeric representation of a month, with leading zeros.H - 24-hour format of an hour with leading zeros.i - Minutes, with leading zeross - Seconds, with leading zeroshttp://docs.sencha.com/extjs/6.0.2-classic/Ext.Date.html
-39857165 0 F5 responsive tables: horizontal scroll is not visibleI used Foundation 5 Responsive Table. But I have this:
If I understood examples, in the bottom of the 1st columns should be horizontal scroll (for mobile). But I can't move it. I can move content only in the right side.
How to fix this problem?
My code:
<h3><?php print t('Organization’s contact person'); ?></h3> <table class="responsive" summary="<?php print t('Organization’s contact person'); ?>"> <thead> <tr> <th scope="column"><?php print t('Contact person'); ?></th> <th scope="column"><?php print t('Country'); ?></th> <th scope="column"><?php print t('City'); ?></th> <th scope="column"><?php print t('Street'); ?></th> <th scope="column"><?php print t('Email'); ?></th> <th scope="column"><?php print t('Phone'); ?></th> <th scope="column"><?php print t('Other'); ?></th> <th scope="column"><?php print t('Image'); ?></th> <th scope="column"><?php print t('Body'); ?></th> </tr> </thead> <tbody> <tr> <td scope="row"> <?php print render($content['field_dir_surname']); ?> <?php print render($content['field_dir_name']); ?> <?php print render($content['field_dir_second_name']); ?> </td> <td scope="row"> <?php isset($content['field_country_list']) ? print render($content['field_country_list']) : print '-'; ?> </td> <td scope="row"> <?php isset($content['field_city']) ? print render($content['field_city']) : print '-'; ?> </td> <td scope="row"> <?php print render($content['field_street']); ?> <?php print render($content['field_building_no']); ?> </td> <td scope="row"> <?php isset($content['field_email']) ? print render($content['field_email']) : print '-'; ?> </td> <td scope="row"> <?php isset($form['field_phone']) ? print render($form['field_phone']) : print '-'; ?> </td> <td scope="row"> <?php isset($form['field_other']) ? print render($form['field_other']) : print '-'; ?> </td> <td scope="row"> <?php isset($content['field_image']) ? print render($content['field_image']) : print '-'; ?> </td> <td scope="row"> <?php isset($content['body']) ? print render($content['body']) : print '-'; ?> </td> </tr> </tbody> </table> <div><?php print render($content['field_share_content']); ?></div>
-25993553 0 You should use DateTime class method Subtract as:
var date2 = DateTime.Parse(DateTime.Now.ToShortDateString() + " 10:00"); System.TimeSpan diff1 = date2.Subtract(DateTime.Now);
-24332673 0 Try increasing the "outer_window" option in config/initializers/kaminari_config.rb. Example:
Kaminari.configure do |config| config.outer_window = 12 end
-13775100 0 It seems that as of Vista there is a property system (1 and 2) in which the properties are stored in the files themselves for portability, in contrast to data stored in alternative data streams. See Alex Martelli's answer in this question, which is a similar one about Python. If I have understood that answer, you will want to find a way to hook into the Windows Search API and query for the System.Keywords and System.Comment properties.
PowerShell may be the way to go in this case; there is an example in the section "Windows Desktop Search cmdlet" at this link, for instance. You may be able to talk to a COM object or WMI from Ruby, however.
-23005156 0CCActionCallFunc is expecting a selector with no arguments, you should use CCActionCallBlock instead. There is an example in this answer.
-17171699 0Using the list monad would let you structure the computation like a tree, but it would lose the source information. At the end, you would have a list of results, but you would not know where each individual result came from.
If this is all you care about, the list monad is perfect. Let's imagine you have a non-deterministic step function:
step :: State -> [State] if we want to just step it through a bunch of times, we could write something like:
startState >>= step >>= step >>= step this will give us all the possible results after 3 steps. If we wanted to generalize this to any number, we could write a simple helper function by using the monadic composition operator (<=<) from Control.Monad. This works just like ., except for function of the form a -> m b instead of normal functions (a -> b). It could look something like this:
stepN :: Int -> (State -> [State]) -> State -> [State] stepN n f = foldr (<=<) return (replicate n f) Now to get three non-deterministic steps, we can just write stepN 3 step. (You'll probably want to come up with better names for the functions :P.)
In summary: using the list monad, the computation itself is shaped like a tree, but you only get to look at the results at the end. This should be clear from the types involved: at the end, you get a [State], which is by its very nature flat. However, the function State -> [State] branches, so the computation to arrive to the end has to look like a tree.
For things like that, the list type is very convenient to use.
-26381925 0'12.10.13_file' as a filename, does have '13_file' as it's file extension. At least regarding the file system.
But, instead of finding the last . yourself, use os.path.splitext:
import os fileName, fileExtension = os.path.splitext('/path/yourfile.ext') # Results in: # fileName = '/path/yourfile' # fileExtension = '.ext' If you want to exclude certain extensions, you could blacklist those after you've used the above.
-5991414 0output = rs.getString("column");// if data is null `output` would be null, so there is no chance of NPE unless `rs` is `null` if(output == null){// if you fetched null value then initialize output with blank string output= ""; }
-20684967 1 Python - Assigning 2 variables from one string values is an array; eventTokens is a string (first element of values). What does the double assignment do? (What are the values of eventToken1 & eventToken2?)
values = data.split("\x01") eventTokens = values.pop(0) eventToken1, eventToken2 = eventTokens I've done an output task (on the Python source) that resulted in the following:
eventTokens is →☹ eventToken1 is → eventToken2 is ☹ I concluded that the vars somehow split the initial string. However, if I tried compiling an (apparently) similar thing:
arr = ["some", "elements", "inarray"] c = arr.pop(0) a, b = c print c print a print b It resulted in an exception: ValueError: too many values to unpack .
Note: print is not a parameterized method in the tested environment
Merge the two insert into single insert like this
INSERT INTO @EventValueResultSet(....) SELECT .... .... FROM dbo.EventValue EV WITH (NOLOCK)) INNER JOIN dbo.DataRun_ DR WITH (NOLOCK) ON EV.dataRunId = DR.Id AND DR.PersonId = @PersonId WHERE PhysioCurrentDataTime BETWEEN @blockStartTime AND @endTime OR ( ( CurrentDataTime < @blockStartTime ) AND ( EventEndTime = 0 OR EventEndTime >= @blockStartTime ) )
-30092126 0 Modifying the primary key on a table is a tricky exercise. This is doubly true when the existing key is defined auto-increment.
You can create a composite unique key, though.
ALTER TABLE ADD UNIQUE KEY (`column1`, `column2');
-5018958 0 I don't have a real answer myself, but your question reminded me of this post:
Selenium doesn't work with Cucumber/Capybara (out of the box) - MacOSX
Where the questioner shows how he used ruby-debug to figure out why a missing dependency was helping selenium fail to open the browser.
Hope this helps!
-22771957 1 python subprocess sends backslash before a quoteI have a string, which is a framed command that should be executed by in command line
cmdToExecute = "TRAPTOOL -a STRING "ABC" -o STRING 'XYZ'"
I am considering the string to have the entire command that should be triggered from command prompt. If you take a closer look at the string cmdToExecute, you can see the option o with value XYZ enclosed in SINGLE QUOTE. There is a reason that this needs to be given in single quote orelse my tool TRAPTOOL will not be able to process the command.
I am using subprocess.Popen to execute the entire command. Before executing my command in a shell, I am printing the content
print "Cmd to be exectued: %r" % cmdToExecute myProcess = subprocess.Popen(cmdToExecute, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False) (stdOut, stdErr) = myProcess.communicate() The output of the above command is, Cmd to be executed: TRAPTOOL -a STRING "ABC" -o \'XYZ\'.
You can see that the output shows a BACKWARD SLASH added automatically while printing. Actually, the \ is not there in the string, which I tested using a regex. But, when the script is run on my box, the TRAPTOOL truncates the part of the string XYZ on the receiving server. I manually copy pasted the print output and tried sending it, I saw the same error on the receiving server. However, when I removed the backward slash, it sent the trap without any truncation.
There are examples of usage Openlayers in Wicket. Did you try this: https://wicket-stuff.svn.sourceforge.net/svnroot/wicket-stuff/trunk/wicketstuff-core/openlayers-parent/openlayers-examples/src/main/java/org/wicketstuff/openlayers/MapUsingWFSGetFeaturePage.java
?
-14548106 0 Using the file name captured with the html browse button in javascriptI am trying to create a form where I can upload demographic information such as name, etc. as well as upload jpg image files. I cannot figure out how to catch the file the user chooses from the browse button. Where is the file name stored? How can I access it for the upload? How can I access it to assign it as a variable eg:
var theFileName; function() if (filename !=null) { //manipulate the variable }; else { //something else}; I am new to JavaScript and trying to teach myself with web sources and books and cannot seem to find an answer. In addition to an answer to this question, can anyone suggest a good web source for further information on this subject? The ultimate goal is to be able to upload the info and files with PHP into a database so it can be recalled on another page but a different user.
-28686099 0 Why NOP/few extra lines of code/optimization of pointer aliasing helps? [Fujitsu MB90F543 MCU C code]I am trying to fix an bug found in a mature program for Fujitsu MB90F543. The program works for nearly 10 years so far, but it was discovered, that under some special circumstances it fails to do two things at it's very beginning. One of them is crucial.
After low and high level initialization (ports, pins, peripherials, IRQ handlers) configuration data is read over SPI from EEPROM and status LEDs are turned on for a moment (to turn them a data is send over SPI to a LED driver). When those special circumstances occur first and only first function invoking just a few EEPROM reads fails and additionally a few of the LEDs that should, don't turn on.
The program is written in C and compiled using Softune v30L32. Surprisingly it is sufficient to add single __asm(" NOP ") in low level hardware init to make the program work as expected under mentioned circumstances. It is sufficient to turn off 'Control optimization of pointer aliasing' in Optimization settings. Adding just a few lines of code in various places helps too.
I have compared (DIFFed) ASM listings of compiled program for a version with and without __asm(" NOP ") and with both aforementioned optimizer settings and they all look just fine.
The only warning Softune compiler has been printing for years during compilation is as follows:
*** W1372L: The section is placed outside the RAM area or the I/O area (IOXTND)
I do realize it's rather general question, but maybe someone who has a bigger picture will be able to point out possible cause.
Have you got an idea what may cause such a weird behaviour? How to locate the bug and fix it?
During the initialization a few long (about 20ms) delay loops are used. They don't help although they were increased from about 2ms, yet single NOP in any line of the hardware initialization function and even before or after the function helps.
Both the wait loops works. I have checked it using an oscilloscope. (I have added LED turn on before and off after).
I have checked timming hypothesis by slowing down SPI clock from 1MHz to 500kHz. It does not change anything. Slowing down to 250kHz makes watchdog resets, as some parts of the code execute too long (>25ms).
One more thing. I have observed that adding local variables in any source file sometimes makes the problem disappear or reappear. The same concerns initializing uninitialized local variables. Adding a few extra lines of a code in any of the files helps or reveals the problem.
void main(void) { watchdog_init(); // waiting for power supply to stabilize wait; // about 45ms hardware_init(); clear_watchdog(); application_init(); clear_watchdog(); wait; // about 20ms test_LED(); {...} } void hardware_init (void) { __asm("NOP"); // how it comes it helps? - it may be in any line of the function io_init(); // ports initialization clk_init(); timer_init(); adc_init(); spi_init(); LED_init(); spi_start(); key_driver_init(); can_init(); irq_init(); // set IRQ priorities and global IRQ enable }
-1108442 0 Problem with ModelAndView and ModelMap in AnnotationController, Springframework I have a question that is a point difference between ModelAndView and ModelMap.
I want to maintain modelAndView when requestMethod is "GET" and requestMethod is "POST". My modelAndView saved others.
So I made modelAndView return type to "GET", "POST" methods.
But, Request lost commandObject, form:errors..., if request return showForm on "POST" because request validation failed.
example)
private ModelAndView modelAndView; public ControllerTest{ this.modelAndView = new ModelAndView(); } @RequestMapping(method = RequestMethod.GET) public ModelAndView showForm(ModelMap model) { EntityObject entityObject = new EntityObject(); CommandObject commandObject = new CommandObject(); commandObject.setEntityObject(entityObject); model.addAttribute("commandObject", commandObject); this.modelAndView.addObject("id", "GET"); this.modelAndView.setViewName("registerForm"); return this.modelAndView; } @RequestMapping(method = RequestMethod.POST) public ModelAndView submit(@ModelAttribute("commandObject") CommandObject commandObject, BindingResult result, SessionStatus status) { this.commandValidator.validate(commandObject, result); if (result.hasErrors()) { this.modelAndView.addObject("id", "POST"); this.modelAndView.setViewName("registerForm"); return this.modelAndView; } else { this.modelAndView.addObject("id", "after POST"); this.modelAndView.setViewName("success"); } status.setComplete(); return this.modelAndView; }
-18305658 0 If you follow this tutorial it should work:
http://sfmlcoder.wordpress.com/2011/08/16/building-sfml-2-0-with-make-for-gcc/
then put the sfml 2 folder with all the dependencies inside of your /usr/include/ folder and compile with g++ main.o -o main -lsfml-graphics -lsfml-window -lsfml-system and run with with ./main it should work perfectly. I actually setup a key mapping in vim that compiles using that command and then runs it and its works flawlessly for me.
Linq was build with an functional style in mind. Using it the imperative way would not end up in elegant code. So don't transform after the query but in the query - put the logic in the projection section (select). (Much like Anthony's answer)
var str = (from i in Regex.Split("TheQuickBrownFox", "") select Regex.IsMatch(i, "[A-Z]") ? " " + i : i) .Aggregate((str1, str2) => str1 + str2); Console.WriteLine(str);
-22395104 0 The exact value of the float is 1.100000000000000088817841970012523233890533447265625. Python isn't somehow keeping track of the original string. When Python stringifies it with str, it truncates to 12 digits.
>>> x = 1.0/9 >>> print decimal.Decimal(x) # prints exact value 0.111111111111111104943205418749130330979824066162109375 >>> print x # truncated 0.111111111111 Even with repr, Python uses the shortest string that will round to the original float when parsed with float.
>>> print repr(x) 0.1111111111111111 If you want to parse JSON and get Decimal instances instead of float, you can pass a parse_float argument to the load(s) function:
>>> json.loads('{"foo": 1.234567890123456789}', parse_float=decimal.Decimal) {u'foo': Decimal('1.234567890123456789')} The above call causes decimal.Decimal to be called to parse numbers in the JSON string, bypassing the rounding that would occur with intermediate float or str calls. You'll get exactly the number specified in the JSON.
Note that the API distinguishes between the functions used to parse things that look like floats, things that look like ints, and things that look like Infinity, -Infinity, or NaN. This can be a bit inconvenient if you want all 3 categories to be handled the same way:
>>> json.loads('{"foo": 1.234567890123456789}', ... parse_float=decimal.Decimal, ... parse_int=decimal.Decimal, ... parse_constant=decimal.Decimal) {u'foo': Decimal('1.234567890123456789')}
-29483549 0 I would define a question class that has a list of answers and return that.
public class Answer { public string AnswerText {get; set;} } public class Question { public List<Answer> Answers {get; set; } } In your class that calls getQuestion, you should return the question object you're looking for that contains its answers.
public class MainClass { public List<Question> Questions {get; set;} public Question GetQuestion(/* some criteria, like question number or something */) { var selectedQuestion = // get the question from Questions based on some criteria return selectedQuestion; } } And then do whatever you need to do in the presentation layer for the end-user to show them the question and answers.
-19315061 0You can get path of executable of default browser from registry (look at the following answer for example: http://stackoverflow.com/a/17599201/2870402) and create new process passing the URL as the parameter:
string pathToExecutable = ...; string url = @"file:///c:\Projects\HTMLTest\Debug\help\index.htm#Modules\Administration\UserInterface\MainWindow\Processing.htm"; System.Diagnostics.Process.Start(pathToExecutable, url);
-11721648 0 What you'll typically do in such a scenario is first create an interface, like ITableStorage and then create an implementation (AzureTableStorage for example) that wraps around the Azure specific stuff.
This makes it easy to replace the actual implementation with a mock/stub during your unit tests. You can take a look at the Windows Azure Helpers for an example of such an interface and a wrapper implementation: Windows Azure Helpers.
This is a good blog post about unit testing and Windows Azure: http://blogs.southworks.net/fboerr/2010/07/23/windows-azure-storage-tdd-and-mocks/
And to answer your question, yes you can use this with MSTest.
-21098752 0Like @CL was saying you can't have 2 records with the same PRIMARY KEY
this Table should be built with 3 columns.
A_ID PRIMARY KEY AUTO INCREMENT NOT NULLtime DATETIME (probably NOT NULL as welldata REALin other words, Never set the Primary key in your code, let the database auto increment it for you, or use a GUID.
this line
data=(1,2) is the only thing that is being inserted into your database. so the only record in the database will be the one you insert, which is 1,2
I'm using DwmExtendFrameIntoClientArea in my WPF application to get the glass effect. This is working fine. What I'd like to do is change the colour used for the glass -- I'm writing a countdown timer, and I'd like the window to be the normal glass colour most of the time, and then to go red (but still with glass) when the time runs out.
I found this question, which talks about how to apply a gradient glass, and that works fine when picking a different colour. Unfortunately, the borders are not coloured appropriately.
When I turn off the borders by using ResizeMode="NoResize", then I end up with square corners. I'd like to keep the rounded corners.
I looked at creating an irregularly-shaped window, by using AllowTransparency="True" and that works fine, but doesn't look like an Aero glass window. It looks a bit flat.
So: my question: how do I create a window in WPF that looks like Aero glass transparency, but uses a different colour?
-36503261 0If you want to do it with DSC, here's a sample: https://github.com/bmoore-msft/AzureRM-Samples/tree/master/VMDSCInstallFile. Ed's answer might be a simpler approach though. The key here is getting the credentials to the VM to be able to pull from storage. That means whether you're using DSC or a custom script, you need to get the location/uri and a sasToken to the script (unless the files are unsecured). The DSC sample above will give you a way to pass the uri/token that will work in either workflow. Look at the PS script in the root to see how the uri & token are created and passed to the template deployment.
-25411166 0 Progressbar for two or more operationsI have this code in doInBackground method of an AsyncTask:
for (int i = 0; i < lenght; i++) { // Do something count++; publishProgress(count * 100 / lenght); } and all works fine. If i add another operation, how to reflect this with the progress bar?
Now i have this code:
for (int i = 0; i < lenght1; i++) { // Do something count++; publishProgress(count * 100 / lenght1); } for (int i = 0; i < lenght2; i++) { // Do something count++; publishProgress(count * 100 / lenght2); } How to make the bar start from 0 when operation 1 starts and finish at 100 when operation 2 ends? I tried to change count*100 to count*50 but it seems not to be the right way...
-17177624 0Every object has an internal property, [[Prototype]], linking it to another object:
object [[Prototype]] -> anotherObject Some environments expose that property as __proto__:
anObject.__proto__ === anotherObject You create the [[Prototype]] link when creating an object:
var object = Object.create( anotherObject ) // imagine: // object.__proto__ = anotherObject In traditional javascript, the linked object is the prototype property of a function:
object [[Prototype]] -> aFunction.prototype and you create the [[Prototype]] link with new (but this isn't obvious):
var object = new aFunction; // imagine: // object.__proto__ = aFunction.prototype; Remember:
__proto__.prototype property. It may be a source of values shared with other objects, or it may go unused.Its a rails method. You can get into a rails console by rails c and pass include ActionView::Helpers::DateHelper. Then work around something like
t = Time.parse("2013-04-19 11:07:37 +0530") time_ago_in_words(t) HTH
-10339384 0Here is a stab at a solution. It needs a bit of cleanup but should give you everything you need.
Create a custom ActionFilter, and then decorate your methods with it.
[ManagerIdAuthentication] public ActionResult Details(int id) { // Gets executed if the filter allows it to go through. } The next class can be created in a separate library so you can include it in all your actions that require this validation.
public class ManagerIdAuthentication : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { // the next line needs improvement, only works on an httpGet since retrieves // the id from the url. Improve this line to obtain the id regardless of // the method (GET, POST, etc.) var id = filterContext.HttpContext.Request.QueryString["id"]; var employee = employeeRepository.Get(id); var user = filterContext.HttpContext.User.Identity; if (employee.managerId == user.managerId) { var res = filterContext.HttpContext.Response; res.StatusCode = 402; res.End(); filterContext.Result = new EmptyResult(); //may use content result if want to provide additional info in the error message. } else { // OK, let it through. } } }
-37668301 1 Move Rows Up By One Of Specified Column In Pandas I have a file like this:
value1, value2, value3, value4, value5 NAN NAN value8, value9, value0 value6, value7, NAN NAN NAN And I would like to push row 3 up to do the following:
value1, value2, value3, value4, value5 value6, value7, value8, value9, value0 NAN NAN NAN NAN NAN I would also like the rows below these rows to move up as well.
How is this done in pandas?
-40141440 0in one line
decimal num13= Math.Round((decimal)num10 / num11, 2);
-4810935 0 I chalk this one up to bad drivers.
-8498496 0I would suggest you to let the user use drag & drop to add files directly from their favorite file browser. As I did this in wxpython without any trouble and user-feedbacks are pretty good :)
-27953649 0Even if you look up the method in both cases (i.e. before 2nd and 3rd loop), the first lookup takes way less time than the second lookup, which should have been the other way around and less than a regular method call on my machine.
Neverthless, if you use the 2nd loop with method lookup, and System.out.println statement, I get this:
regular call : 740 ms look up(2nd loop) : 640 ms look up ( 3rd loop) : 800 ms Without System.out.println statement, I get:
regular call : 78 ms look up (2nd) : 37 ms look up (3rd ) : 112 ms
-14948053 0 Turns out only the captures, not the args get passed down the chain.
According to the doc:
$c->visit( $action [, \@captures, \@arguments ] )
So I was able to have success by doing the following:
$c->visit('/assets/widget',[$arg],[$arg]) The first array of args hits the first action and stops, but the second array travels all the way down the chain like I wanted.
I expected $c->visit('/assets/widget',[],[$arg]) to work, but it does not.
However, after all that I realized I can't just grab the body response that way, which was the ultimate goal. Either way, hopefully my goose chase was helpful to someone.
-34868604 02 MB is the limit for i cloud e mail attachment. One problem with icloud is that if you send files more that 10-15 MBs from another mail service provide.icloud server will not receive the mail instead it will reject and deliver a postmaster intimation at the source mail
-35023578 0As far as 've heard about R / MARS integration, Salford Systems has announced earlier in 2015/Q1 an extension to their system to allow users to access MARS from R-session.
Hope this helps.
-27331705 0A regular expression like /([a-zA-Z0-9]*)=([^&]*)/ig will return all matches with the variable and value conveniently sorted.
Sorry for all the long code...BUT...In order for me to work with my program and solve some issues, I need it to actually work. I'm working with a .html and .jsp files to insert data to MYSQL database. Can anybody tell me why I get this: This page cannot be display, make sure address http: //localhost:8081 is correct... ??? Please help, thanks!
<!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Help Desk Ticket System</title> </head> <body> <script language ="JAVASCRIPT"> function check(form) { if(form.equipment.value =="") { alert("Please enter equipment type") form.equipment.focus() return false } if(form.problem.value =="") { alert("Please enter a description before hitting submit") form.problem.focus() return false } if(form.empid.value =="") { alert("Please enter employee ID.") form.empid.focus() return false } if(form.empfname.value =="") { alert("Please enter a first name.") form.empfname.focus() return false } if(form.emplname.value =="") { alert("Please enter a last name.") form.emplname.focus() return false } if(form.empemail.value =="") { alert("Please enter your email") form.empemail.focus() return false } if(form.empphone.value =="") { alert("Please enter a your phone number.") form.empphone.focus() return false } if(form.empcellphone.value =="") { value = "n/a" } selected = form.empdept.selectedIndex if (selected<=0) { alert("Please choose the department") form.empdept.focus() return false } selected = form.technician.selectedIndex if (selected<=0) { alert("Please choose a technician") form.technician.focus() return false } alert("Your ticket has been created.") return true } </script> <FORM method="post" action="http://localhost:8081/finalproject/help.jsp" onsubmit="return check(this)"> <h2> Please fill out the following details for your ticket </h2> <br/> Equipment: <input type="text" name="equipment" /><br/> <br/> Description of the problem: <br/> <textarea name="problem" rows="4" cols="50"></textarea><br/> <br/> <hr> <br/> Employee ID: <input type = "text" name="empid" /><br/> Employee First name: <input type = "text" name="empfname" /><br/> Employee Last name: <input type = "text" name="emplname" /><br/> Employee email: <input type = "text" name="empemail" /><br/> employee Phone: <input type = "text" name="empphone" /><br/> employee cell Phone: <input type = "text" name="empcellphone" /><br/> <br/> Employee Department: <br/> <select name = "empdept"> <option> Please select the department</option> <option>Marketing</option> <option>Human Resources</option> <option>Operations</option> <option>Legal</option> <option>Accounting</option> <option>Production</option> </select> <hr> <br/> Choose Technician: <select name ="technician"> <option value="0">Select</option> <option value="12345">Sierra: Applications </option> <option value="12344">Michael: Network</option> <option value="12343">Greg: Phones</option> <option value="12342">Aaron: Hardware</option> <option value="12341">Phil: Database </option> </select><br/> <br/> <br/> <button type="submit">Submit</button> <button type="reset" value="Clear Form">Reset</button> </form> </body> </html> <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <%@ page import="java.sql.*" %> <%@ page import="java.util.Random" %> <% Connection conn = null; Statement st = null; ResultSet rs = null; //Random rand = new Random(); //int randomnumber = rand.nextInt(90000) + 10000; try { Class.forName("com.mysql.jdbc.Driver").newInstance(); conn = DriverManager.getConnection("jdbc:mysql://localhost/helpdesk?user=root&password=password"); st = conn.createStatement(); //String ticket = request.getParameter("ticketid"); String a = request.getParameter("equipment"); String b = request.getParameter("problem"); String c = request.getParameter("empid"); String d = request.getParameter("empfnname"); String e = request.getParameter("emplname"); String f = request.getParameter("empemail"); String g = request.getParameter("empphone"); String h = request.getParameter("empcellphone"); String i = request.getParameter("department"); String j = request.getParameter("technician"); String jointables = ("Select tech_id from technician inner join ticket on technician.tech_id = ticket.tech_id;"); String insert1 = ("insert into ticket (t_date,t_equpipment, t_descript,emp_id,tech_id)" + " values( NOW(),'"+a+"', '"+b+"', '"+c+"', '"+j+"')"); String insert2 = ("insert into employee (emp_id, emp_fname,emp_lname,emp_email, emp_phone,emp_cellphone,emp_dept)" + "values ('"+ c +"','" + d + "','" + e + "','" + f + "','" + g + "','"+ h +"','" + i + "')"); String intodatabase = insert1 + insert2; out.println("<b>Executed the following SQL statement:</b><br>"); out.println(intodatabase); //print out the actual sql statement that was generated //Execute the "insert into" sql statement st.executeUpdate(intodatabase); out.println ("<br><br><b>Successfully Added the tuple..</b>"); } catch (java.sql.SQLException ex) { out.println("<br><b>Ouch, an SQLException was thrown..</b>"); ex.printStackTrace(); } finally { if (rs != null) rs.close(); if (st != null) st.close(); if (conn != null) conn.close(); } %> </body> </html>
-4291769 0 How do I notify a MATLAB object of an event in a Java object? For simplicity, say I have a Java object which generates a random number at randomly spaced time intervals. I wish to have a MATLAB object notified every time one of these random numbers is generated (so that the MATLAB object can then perform some task on the data).
How can I implement something like this? How can I have the Java object notify a MATLAB object that something has happened?
P.S. I am a strong programmer in MATLAB but fairly new to Java.
-37622539 0This seems to be a problem on Ubuntu (perhaps other Debian-based distros) with the Java CACerts keystore. For some reason this does not always include the full list of entries.
To solve this, try the following:
Delete the cacerts file
sudo rm /etc/ssl/certs/java/cacerts
Re-build the cacerts file using the dpkg postinstall script:
sudo /var/lib/dpkg/info/ca-certificates-java.postinst configure
This should re-generate the cacerts file and the problem should be resolved.
-38874661 0 How to append Json.obj into Json.arr Scala?I am newbie to Scala.
I want to append Json.obj into Json.arr during runtime in Scala.
Json Object:
var x: JsValue = Json.obj("name" -> "Fiver", "age" -> 4,"role" -> JsNull) Json Array:
var y: JsValue = Json.arr(x) Here, I am able to append single Json.obj to Json.arr but I want to add multiple Json.obj to Json.arr dynamically.
I can do like this:
var y: JsValue = Json.arr( Json.obj("name" -> "Fiver", "age" -> 4,"role" -> JsNull), Json.obj("name" -> "Fiver", "age" -> 4,"role" -> JsNull) ) but it is not appending in one by one. I want to append Json.Obj dynamically.
-20803245 0 How to write and read (including spaces) from text fileI'm using fscanf and fprintf.
I tried to delimit the strings on each line by \t and to read it like so:
fscanf(fp,"%d\t%s\t%s",&t->num,&t->string1,&t->string2); The file contents:
1[TAB]string1[TAB]some string[NEWLINE] It does not read properly. If I printf("%d %s %s",t->num,t->string1,t->string2) I get:
1 string1 some Also I get this compile warning:
warning: format specifies type 'char *' but the argument has type 'char (*)[15]' [-Wformat] How can I fix this without using binary r/w?
-33907030 0From the information given - assuming "Schedule.java" is just a POJO and not an activity - one way is to create a "Schedule" object in your ActivityMain class, so you can pull "Music" from the schedule array and update your text view. Make sure the schedule array has more private accessibility, or you can write getters in Schedule.java to return the relevant strings.
-7058223 0 opengl - point sprites rendering problemI'm trying to render point sprites but I get points. Where is the problem ? (changing a color via glUniform3f works)
Vertex shader:
private static String vertexShader = "#version 330" + "\n" + "layout (location = 0) in vec4 position;" + "\n" + "uniform mat4 pMatrix;" + "\n" + "uniform mat4 mMatrix;" + "\n" + "void main()" + "\n" + "{" + "\n" + "gl_Position = pMatrix * mMatrix * position;" + "\n" + "}"; Fragment shader:
private static String fragmentShader = "#version 330" + "\n" + "out vec4 vFragColor;" + "\n" + "uniform vec3 Color;" + "\n" + "uniform vec3 lightDir;" + "\n" + "void main()" + "\n" + "{" + "\n" + "vec3 N;" + "\n" + "N.xy = gl_PointCoord* 2.0 - vec2(1.0);" + "\n" + "float mag = dot(N.xy, N.xy);" + "\n" + "if (mag > 1.0) discard;" + "\n" + "N.z = sqrt(1.0-mag);" + "\n" + "float diffuse = max(0.0, dot(lightDir, N));" + "\n" + "vFragColor = vec4(Color,1) * diffuse;" + "\n" + "}"; Rendering:
gl.glUseProgram(shaderProgramID); gl.glUniformMatrix4fv(projectionMatrixUniform, 1, false, projectionMatrix, 0); gl.glUniformMatrix4fv(modelViewMatrixUniform, 1, false, modelViewMatrix, 0); gl.glUniform3f(colorUniform, 1.0f, 0.0f, 0.0f); gl.glUniform3f(lightDirUniform, 0.0f, 0.0f, 1.0f); gl.glBindBuffer(GL3.GL_ARRAY_BUFFER, vbo[0]); gl.glEnableVertexAttribArray(0); gl.glVertexAttribPointer(0, 4, GL3.GL_FLOAT, false, 0, 0); gl.glDrawArrays(GL3.GL_POINTS, 0, n_particles); gl.glDisableVertexAttribArray(0); gl.glUseProgram(0);
-7305565 0 If you have some form of session identifier you can increment a count of times that request has been made. This isn't bullet proof however, clearing out session cookies will allow that request to be made again.
You will need some form of login to prevent someone clearing their cookies, or even a cURL script looping.
Edit:
As a stop-gap measure, you could add a form of CSRF protection, a one-time-use hash would need to be applied to each request to make it valid.
-20855544 0 unnecessary movements in my a-star implementationI've made an a-star implementation with euclidean heuristics, and it works, but makes unnecessary movements in some situations.
Here is the screenshot: http://clip2net.com/s/6v2iU4
Path starts on the blue circle and, in theory, cell to the right of it has less F (movement cost + heuristic cost), so a-star takes it first, but it ends up in building not the shortest path.
How can i fix this? Or a-star is supposed to work this way and i dont need to do anything?
My code: http://pastebin.com/02u33jY6 (h + cpp)
-40984308 0You used the [typescript] tag here, so I am going to assume you are using typescript.
Make this a 1-way street. Kill off the circular dependency. I would probably move this into 1 file, but you can still split it up like this.
a.ts (just an interface)
export interface A { name: string; new (name: string); } b.ts (implementation)
import { A } from 'a'; export class B implements A { /*...*/ }
-21138366 0 How to create two independent branches in Mercurial? We are using Mercurial to manage a project A, which links to an old version of external system.
A new version of this external system is now available and I now want to create second version B of the same project to work with this.
Although both versions will share much of their code, I do not want changes to one project to affect that for the other project. I want to change the code base of each independently.
How can I deal with this please?
One way would be to put project B in a new repository, but this would lose the history of previous code. Is there a way to retain the history?
Though I would have preferred a single code base, it is too difficult to add conditional statements to separate these.
-6667348 0Is it good I a idea to use command line instead of GUI?
Yes.
And is it normal to compare every file I modified to the old ones with WinMerge after every time I modified them?
Yes.
Also. Buy this: http://www.syncrosvnclient.com/
-4041826 0You must use the Double.IsInfinity() and Double.IsNaN() methods.
if (Double.IsInfinity(SampleInterval)) { //TODO } if (Double.IsNaN(SampleInterval)) { //TODO } Don't compare directly to Double.NaN, it will always return false.
-20838609 0 Want to know the raw sql query when user other than superuser logs in the systemI have an application which involves large number of users. among those, some are staff members.
My problem
When a user from a certain group let say A logs in, it takes 5 minute to see the admin screen (index page). I want to fix this problem.So the question is , What is the sql query when a user from a certain group logs in the admin of the project.
I know how to see query
str(MyModel.objects.filter(name="my name").query) but again not getting how to generate the query for that case
-17313558 1 Form for multiple modelsSuppose I have two models:
class Topic(models.Model): title = models.CharField() # other stuff class Post(models.Model): topic = models.ForeignKey(Topic) body = models.TextField() # other stuff And I want to create a form contains two fields: Topic.title and Post.body. Of course, I can create the following form:
class TopicForm(Form): title = forms.CharField() body = forms.TextField() # and so on But I don't want to duplicate code, since I already have title and body in models. I'm looking for something like this:
class TopicForm(MagicForm): class Meta: models = (Topic, Post) fields = { Topic: ('title', ), Post: ('body', ) } # and so on Also, I want to use it in class based views. I mean, I would like to write view as:
class TopicCreate(CreateView): form_class = TopicForm # ... def form_valid(self, form): # some things before creating objects As suggested in comments, I could use two forms. But I don't see any simple way to use two forms in my TopicCreate view - I should reimplement all methods belongs to getting form(at least).
Is there something already implemented in Django for my requirements? Or is there a better(simpler) way?
or
Do you know a simple way with using two forms in class based view? If so, tell me, it could solve my issue too.
-669651 0WPCubed (http://wptools.de/) offers WPViewPDF tools with a royalty free distribution license, and Delphi support - 4,5,6,7, 2005, 2006, 2007, BCB 5,6,2006, 2007
-37303993 0There is mistake in the Parcelable implementation.
First of all parcelable implementation states that: the fields passed in News(Parcel in) Constructor should be written in the same sequence in writeToParcel() method. Thats called Marshalling and Unmarshalling.
Corrections:
Drawable cannot be passed a parameter in Parcelable.
News Parcelable implementation.
Missed some of the fields its just for your understanding.
public class News implements Parcelable { public static final String TAG = "model_news"; private JSONObject object; private int id; private String type; private String title; private Boolean comment_disabled; private String category_name; private String url; private Image images; private Date date; private Boolean is_video; protected News(Parcel in) { id = in.readInt(); type = in.readString(); title = in.readString(); category_name = in.readString(); url = in.readString(); } public static final Creator<News> CREATOR = new Creator<News>() { @Override public News createFromParcel(Parcel in) { return new News(in); } @Override public News[] newArray(int size) { return new News[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(id); dest.writeString(type); dest.writeString(title); dest.writeString(category_name); dest.writeString(url); } } public class Image implements Parcelable { public static final String TAG = "model_image"; private JSONObject imageObj; private JSONObject original; private String source; private int width; private Drawable image; protected Image(Parcel in) { source = in.readString(); width = in.readInt(); } public static final Creator<Image> CREATOR = new Creator<Image>() { @Override public Image createFromParcel(Parcel in) { return new Image(in); } @Override public Image[] newArray(int size) { return new Image[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(source); dest.writeInt(width); } }
-5805173 0 All the qt widget classes can be styled via stylesheets, depending where create your popup (designer, or in code) assign it a stylesheet with the look that you want it to have. You can test stylesheets in designer by assigning a style to a widget using the context menu of the widget
After further review, the QSystemTrayIcon::showMessage() call puts up a system notification. Which I don't know if it can be styled. The qsystemtrayicon_win.cpp file in the qt distribution shows a workaround and shows a way of how to find the location of the icon in the tray (see QSystemTrayIconSys::findIconGeometry). Once you have the location you could pop up your own window at that location. I did not look to deep, I don't know if you can get to the location for the icon with the information that you have on the public side of Qt. You might have to go all windows with that.
You cannot stop someone from downloading an image.
You can put text in the image to say "click here to verify", then have that popup a page on your site which verifies the IP of the referrer.
-39013435 0 Android SMSManager sendTextMessage saves messages as draft sometimesi am glad to be able to send SMS from an Android App using
SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage(strNum, null, strTxt, null, null); But in some cases, it saves the message as draft, instead of sending immidiately - why? some ideas? Or does somebody know - as a workaround - how can i send all SMS drafts?
-36411766 0You should set the Adapter before adding the layoutManager
updateUI(); mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
-4544724 0 You'd have to cast to decimal for smaller numbers
select cast(power(cast(101 as float),50) as decimal(38,0)) % 221 or
select power(cast(101 as decimal(38,0)),50) % 221 This fails though with such a large number
But then it makes no sense anyway for larger numbers.
Any answer from the modulo is utter rubbish
Edit:
Decimal goes to around 10^38
Take a float number at 10^39, or 1E+39, then you are accurate to around 1E24 (15 signficant figures).
Your modulo is 221 = 2.2E+2
You margin of error ie 1E+24/2.2E+2 = 4.4E+21
Just to be 100% clear, your accuracy is 4,400,000,000,000,000,000,000,000 times greater than your modulo.
It isn't even approximate: it's rubbish
-25130034 0For future reference,
You should be using a WebService (ASMX) file to process and return your JSON. Remember that the javascript success block will only be called with a returned http 200 status code.
If you ever get to using the MVC framework its even easier by just returning a JSON result type.
If you wanted to keep the aspx hack, you can call the following to remove the HTML
response.clear(); response.write(yourJSON); response.end(); But again i would discourage from doing this and recommend the dedicated service.
-40655961 0You can check xdo which can do a decent job with minimal ressources.
-39642325 0 Sox cannot determine type of fileI'm using node js and express with sox node bindings. I have a temporary uploaded file that I need to identify, but since the file does not have an extension, SoX gives me this error:
sox.identify(file, function(err, info) { if (err) { console.log(err) throw(err) } }); sox FAIL formats: can't determine type of file C:\Users\User\Documents\Project\Media\temp\riqDeq15151sf14FWa
I'm using multer for saving the uploaded file temporarily. Is there anyway to have SoX identify the file even though it doesn't have an extension?
-10039596 0Yep, jQuery has a Checked Selector:
var checkedBoxIds = $("input:checked").id();
-19257166 0 Correct...and to launch you even further, check out this modification.
Here, you'll see that not only are we combining the options, but we're creating our own binding entirely...which results in a much more portable extension of not just this view model, but any view model you may have in your project...so you'll only need to write this one once!
ko.bindingHandlers.colorAndTrans = { update: function(element, valAccessor) { var valdata = valAccessor(); var cssString = valdata.color(); if (valdata.transValue() < 10) cssString += " translucent"; element.className = cssString; } } To invoke this, you just use it as a new data-bind property and can include as many (or as few) options as possible. Under this specific condition, I might have just provided $data, however if you're wanting a reusable option you need to be more specific as to what data types you need as parameters and not all view models may have the same properties.
data-bind="colorAndTrans: { color: color, transValue: number }" Hope this does more than answer your question!
-30422396 0Try this and put profile image
$('img').on('click', function() { $('.hoverelement').toggle(); }); .hoverelement { display: none; border: solid 1px; width: 200px; text-align: left; position: absolute; z-index: 999; top: 100px; } .container { position: relative; top: 45px; float: right; text-align: right; } img { width: 100px; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <img src="http://upload.wikimedia.org/wikipedia/commons/3/33/Vanamo_Logo.png" alt=""/> <div class="hoverelement"> <h1>your content here</h1> <p>put some content here</p> </div> </div> http://jsfiddle.net/9uppsLqa/5/
.arrow_box { border-radius: .1875em; z-index: 99; position: relative; box-shadow: 0 0 0 1px rgba(0,0,0,0.15),inset 0 0 0 1px rgba(255,255,255,0.6), 0 4px 2px -2px rgba(0,0,0,0.2),0 0 1px 1px rgba(0,0,0,0.15); background-repeat: repeat-x; background-position: 0 0; background-image: linear-gradient(to bottom,rgba(255,255,255,0.7) 0,rgba(255,255,255,0) 100%); background-color: #e1e1e1; margin-top: 3em; margin-left: .75em; margin-right: .75em; padding-left: 0; padding-bottom: 0; padding-right: 0; padding-top: 0; width: 340px; height: 160px; } .arrow_box:after, .arrow_box:before { border: 13px solid transparent; position: absolute; content: ''; left: 90%; bottom:100%; } .arrow_box:after { border-bottom-color: #fafafa; border-width: 14px; margin-left: -24px; } .arrow_box:before { border-bottom-color: #999; border-width: 15px; margin-left: -25px; }
-33955850 0 In Excel, you can do it using an array formula to search for the next frequency which is in range:-
=MATCH(1,(B2:B$10>=49)*(B2:B$10<=51),0)-1 if your frequencies start in B2.
Must be entered in C2 with CtrlShiftEnter
Here is a modified version which allows for the case where the last frequency is out of range, assuming there are no blanks between frequency values and one or more blanks at the end:-
=MATCH(1,(B2:B$10>=49)*(B2:B$10<=51)+(B2:B$10=""),0)-1
-2996662 0 ASP.net - Does a return statement in function stop the function? Given the function
'Returns true if no cell is > 1 Function isSolutionValid() As Boolean Dim rLoop As Integer Dim cLoop As Integer For cLoop = 0 To canvasCols - 1 For rLoop = 0 To canvasRows - 1 If canvas(cLoop, rLoop) > 1 Then Return False End If Next Next Return True End Function When 'return false' is fired, I'm assuming that the function is stopped at that point and there's no need for exit fors and things like that?
-30800653 0Options 1, 2, and 5 seems OK. I don't see how the 3rd option could work because the browser does not need to store changes in field values.
So unless you go the single-page-web-application way, like AngularJS, and avoid your navigation problem by not navigating to another page, you need to deal with the browse cache problem. The user could also have clicked a bookmark which is different but similar to the back button problem.
Additionally, not a very strong argument, but if you look at Stack Overflow you can see it uses Cache-Control and ajax requests.
UserDefaults - Gives you a new object, each object is allocated a different memory and deallocated when object scope is finished.
UserDefaults.standard - Gives you the singleton object by using the class method standard the object received by this method is allocated single memory throughout the application.
And the usage of them if you´re interesedted in that:
// Set UserDefaults.standard.set("YOUR STRING", forKey: "key") UserDefaults().set("YOUR STRING", forKey: "key") // Get UserDefaults.standard.string(forKey: "key") UserDefaults().string(forKey: "key")
-28206222 0 If you want to specify a literal color value in a geom_segment, you should not include it in the aes(). For example using this test data
DF_for_plotting <- data.frame( variable=rep("StrpCnCor",4), value=c(0, 50.79330935, 81.127731, 100) ) you can do
ggplot() + geom_segment(data=DF_for_plotting, aes(x=value[1], xend=value[2]-0.001, y=1, yend=1), colour="green", size=10) + geom_segment(data=DF_for_plotting, aes(x=value[2], xend=value[3]-0.001, y=1, yend=1), colour="blue", size=10) + geom_segment(data=DF_for_plotting, aes(x=value[3], xend=value[4]-0.001, y=1, yend=1), colour="red", size=10) 
or with hex colors
ggplot() + geom_segment(data=DF_for_plotting, aes(x=value[1], xend=value[2]-0.001, y=1, yend=1), colour="#9999CC", size=10) + geom_segment(data=DF_for_plotting, aes(x=value[2], xend=value[3]-0.001, y=1, yend=1), colour="#66CC99", size=10) + geom_segment(data=DF_for_plotting, aes(x=value[3], xend=value[4]-0.001, y=1, yend=1), colour="#CC6666", size=10) 
Although because you're not mapping anything to the color aesthetic, no legend will be provided.
When you put it in the aes(), you're not specifying a literal value, you are just specifying a literal value to associate with a color it doesn't matter if you use aes(color="red") or aes(color="determination"); it just treats it as a literal character value and will use it's own color palate to assign a color to that character value. You can specify your own colors with scale_fill_manual For example
ggplot() + geom_segment(data=DF_for_plotting, aes(x=value[1], xend=value[2]-0.001, y=1, yend=1, colour="a"), , size=10) + geom_segment(data=DF_for_plotting, aes(x=value[2], xend=value[3]-0.001, y=1, yend=1, colour="b"), , size=10) + geom_segment(data=DF_for_plotting, aes(x=value[3], xend=value[4]-0.001, y=1, yend=1, colour="c"), size=10) + scale_color_manual(values=c(a="green",b="blue",c="red")) 
ggplot() + geom_segment(data=DF_for_plotting, aes(x=value[1], xend=value[2]-0.001, y=1, yend=1, colour="a"), , size=10) + geom_segment(data=DF_for_plotting, aes(x=value[2], xend=value[3]-0.001, y=1, yend=1, colour="b"), , size=10) + geom_segment(data=DF_for_plotting, aes(x=value[3], xend=value[4]-0.001, y=1, yend=1, colour="c"), size=10) + scale_color_manual(values=c(a="#9999CC",b="#66CC99",c="#CC6666")) 
Here i called the three groups "a", "b", and "c" but you could also call then "green","blue","red" if you want -- it just seems odd to have a legend that tells you what color is green.
-25026161 0How do I read json with bash?
You can use jq for that. First thing you have to do is extract the list of hostnames and save it to a bash array. Running a loop on that array you would then run again a query for each hostname to extract each element based on them and save the data through redirection with the filename based on them as well.
This is how my XML looks like :
<Product sequence_number="1" number="1543448904" id="S1" unit_number="1"> <consumer_narrative name="GLENN,GREGORY" date_filed="02/13/2009"> <message type="Consumer Comments">THE CONSUMER STATES THIS WAS NOT </message> <message type="Consumer Comments">THE PRODUCT REQUESTED.</message> </consumer_narrative></Product> <Product sequence_number="2" number="1543448905" id="S1" unit_number="1"> <consumer_narrative name="JOHN,GORDON" date_filed="08/23/2009"> <message type="Consumer Comments">THE CONSUMER STATES THAT</message> <message type="Consumer Comments">WRONG PRODUCT WAS SENT.</message> </consumer_narrative> </Product> My Query :
SELECT tab.col.value('../@number', 'varchar(30)') [Claim Number], tab.col.value('../@name', 'varchar(30)') [Name], tab.col.value('../@date_filed', 'varchar(30)') [DateField], tab.col.value('@type', 'varchar(50)') [Type], tab.col.value('.', 'varchar(250)') [CustomerComments] FROM XMLTABLE AS B CROSS APPLY xmldocument.nodes('//Product/consumer_narrative/message') tab(col) WHERE B.XMLId = 123 Gives me "null" for Claim Number. What should I have in the place of ../@number to get the claim number.
-29077629 0You could use the automoc feature of CMake like this:
set(CMAKE_AUTOMOC ON) set(CMAKE_INCLUDE_CURRENT_DIR ON) add_library(Display MainWindow.cpp SpiderEditor.cpp OutputPane.cpp) qt5_use_modules(Display Widgets Core)
-12572211 0 So apparently, you can't just take any temporary key and sign the APPX with it. In particular the certificate subject lines must match(the "publisher name"). I do not know of a better way of determining what the subject line much actually be so bare with me. First, try to use signtool and sign the APPX file with any temporary key. Now go to Event Viewer. Then to Applications and Services and then Microsoft and then Windows and then AppxPackaging and finally Microsoft-Windows-AppxPackages/Operational. There should be an error event that just happened from that build. Check it. It should say something like
Error 0x800700B: The app manifest publisher name (CN=random-hex-number) must match the subject name of the signing certificate (CN=MyWrongName) So, now make sure to hang on to that random-hex-number. That needs to be the subject line of the certificate and is the cause of the error. To generate a working certificate:
makecert.exe mycert.cer -r -n "CN=random-hex-number" -$ individual -sv private.pkv -pe -cy end pvk2pfx -pvk private.pkv -spc mycert.cer -pfx mytemporarykey.pfx Now finally, you should have a temporary key that will work with signtool!
Hopefully this answers serves other people well.
-11910787 0It was most likely an issue of permissions, but I never got it to work on its own (might've been something to do with using a Windows server). Anyway, my co-worker tried a different Linux server and got it to run fine. Thanks for the feedback still, CBroe.
-24745352 0Arrays are only meant to store numeric indices, you can create members like Nom but these will in no way react like a normal numeric index.*
Either use an object, or push objects into your array.
var personnes=[]; personnes.push({ "Nom" : "Julie", "Age" : 100 }); personnes[0].Nom // -> Julie or
var personnes={}; personnes["Julie"] = 100; // equal to: personnes.Julie = 100; or
var personnes={}; personnes["Julie"] = {"age":100 /*,"more attributes":"here"*/} However, the last two notations assume that the names are unique!
*You can do the following:
var ar = []; ar.attr = 5; ar.attr; // -> 5 ar.length; // -> 0, since attr is not enumerable // also all other regular array operation won't affect attr
-29456359 0 Did you use DialogFragments ? The missing part will be the setStyle call then. You have to do this before the Fragment gets shown.
@NonNull public static SlowConnectionDialogFragment newInstance(final String errorText) { final Bundle bundle = BundleArgs.create(errorText); final SlowConnectionDialogFragment instance = new SlowConnectionDialogFragment(); instance.setStyle(STYLE_NO_TITLE, android.R.style.Theme_DeviceDefault_Light_Dialog); instance.setArguments(bundle); return instance; } For Dialogs are some kind of other Styling properties needed, to get the floating window back. So you should consider creating another theme for Dialogs.
-29472625 0Do you see this behavior when you start Emacs without your init file (emacs -Q)? I doubt it. If not, then recursively bisect your init file to find out what is causing the problem.
The minibuffer uses its own keymaps, which are local and which therefore take precedence over global keymap bindings.
However, any minor-mode keymaps take precedence over local keymaps. So if, for example, you have a (global) minor mode turned on that binds <tab> then that will override any binding for that key in the minibuffer keymaps.
Another thing you can do is simply bind whatever command you want to <tab> in the minibuffer keymaps. But again, you should not need to do that, if you want the usual <tab> behavior for the minibuffer.
[Another possible confusion: Some things, such as Isearch, which you might think use the minibuffer do not use it. Isearch uses its own keymap, isearch-mode-map.]
UPDATE after your comment:
Assigning a key in the global map, as you have done, should not affect what that key does in the minibuffer, provided it has a different binding in the minibuffer keymaps. TAB is typically bound in all of the minibuffer completion keymaps (but not in the non-completion minibuffer keymaps).
See the Elisp manual, nodes Completion Commands and Text from Minibuffer for information about the minibuffer keymaps.
To see what the current bindings are for a keymap that is associated with a variable (such as minibuffer-local-completion-map), load library help-fns+.el and use C-h M-k followed by the keymap variable's name. (See Help+ for more information about the library.)
If you do not want TAB to use your global command binding in the non-completion minibuffer maps (minibuffer-local-map, minibuffer-local-ns-map), then just bind it in those maps to whatever command you like. But for the completion maps you should not need to do anything - TAB should already be bound there.
Did you try emacs -Q, to see if something in your init file is interfering? If not, do that first.
I have a huge problem with my play 2.4 application. Every time I try to start my application with activator test, I get the following error:
java.net.ConnectException: Connection refused: localhost/127.0.0.1:9000, took 0.0 sec [error] at com.ning.http.client.providers.netty.request.NettyConnectListener.onFutureFailure(NettyConnectListener.java:128) [error] at com.ning.http.client.providers.netty.request.NettyConnectListener.operationComplete(NettyConnectListener.java:140) [error] at org.jboss.netty.channel.DefaultChannelFuture.notifyListener(DefaultChannelFuture.java:409) [error] at org.jboss.netty.channel.DefaultChannelFuture.addListener(DefaultChannelFuture.java:145) [error] at com.ning.http.client.providers.netty.request.NettyRequestSender.sendRequestWithNewChannel(NettyRequestSender.java:283) [error] at com.ning.http.client.providers.netty.request.NettyRequestSender.sendRequestWithCertainForceConnect(NettyRequestSender.java:140) [error] at com.ning.http.client.providers.netty.request.NettyRequestSender.sendRequest(NettyRequestSender.java:115) [error] at com.ning.http.client.providers.netty.NettyAsyncHttpProvider.execute(NettyAsyncHttpProvider.java:87) [error] at com.ning.http.client.AsyncHttpClient.executeRequest(AsyncHttpClient.java:506) [error] at play.libs.ws.ning.NingWSRequest.execute(NingWSRequest.java:509) [error] at play.libs.ws.ning.NingWSRequest.execute(NingWSRequest.java:395) [error] at play.libs.ws.ning.NingWSRequest.post(NingWSRequest.java:322) [error] at controllers.projeckerSystem.LoginController.login(LoginController.java:28) [error] at projeckerSystem.Routes$$anonfun$routes$1$$anonfun$applyOrElse$1$$anonfun$apply$1.apply(Routes.scala:504) [error] at projeckerSystem.Routes$$anonfun$routes$1$$anonfun$applyOrElse$1$$anonfun$apply$1.apply(Routes.scala:504) [error] at play.core.routing.HandlerInvokerFactory$$anon$5.resultCall(HandlerInvoker.scala:139) [error] at play.core.routing.HandlerInvokerFactory$JavaActionInvokerFactory$$anon$14$$anon$3$$anon$1.invocation(HandlerInvoker.scala:127) [error] at play.core.j.JavaAction$$anon$1.call(JavaAction.scala:70) [error] at play.GlobalSettings$1.call(GlobalSettings.java:67) [error] at play.db.jpa.TransactionalAction.lambda$call$5(TransactionalAction.java:19) [error] at play.db.jpa.DefaultJPAApi.withTransaction(DefaultJPAApi.java:136) [error] at play.db.jpa.JPA.withTransaction(JPA.java:159) [error] at play.db.jpa.TransactionalAction.call(TransactionalAction.java:16) [error] at play.core.j.JavaAction$$anonfun$7.apply(JavaAction.scala:94) [error] at play.core.j.JavaAction$$anonfun$7.apply(JavaAction.scala:94) [error] at scala.concurrent.impl.Future$PromiseCompletingRunnable.liftedTree1$1(Future.scala:24) [error] at scala.concurrent.impl.Future$PromiseCompletingRunnable.run(Future.scala:24) [error] at play.core.j.HttpExecutionContext$$anon$2.run(HttpExecutionContext.scala:40) [error] at play.api.libs.iteratee.Execution$trampoline$.execute(Execution.scala:70) [error] at play.core.j.HttpExecutionContext.execute(HttpExecutionContext.scala:32) [error] at scala.concurrent.impl.Future$.apply(Future.scala:31) [error] at scala.concurrent.Future$.apply(Future.scala:492) [error] at play.core.j.JavaAction.apply(JavaAction.scala:94) [error] at play.api.mvc.Action$$anonfun$apply$1$$anonfun$apply$4$$anonfun$apply$5.apply(Action.scala:105) [error] at play.api.mvc.Action$$anonfun$apply$1$$anonfun$apply$4$$anonfun$apply$5.apply(Action.scala:105) [error] at play.utils.Threads$.withContextClassLoader(Threads.scala:21) [error] at play.api.mvc.Action$$anonfun$apply$1$$anonfun$apply$4.apply(Action.scala:104) [error] at play.api.mvc.Action$$anonfun$apply$1$$anonfun$apply$4.apply(Action.scala:103) [error] at scala.Option.map(Option.scala:146) [error] at play.api.mvc.Action$$anonfun$apply$1.apply(Action.scala:103) [error] at play.api.mvc.Action$$anonfun$apply$1.apply(Action.scala:96) [error] at play.api.libs.iteratee.Iteratee$$anonfun$mapM$1.apply(Iteratee.scala:524) [error] at play.api.libs.iteratee.Iteratee$$anonfun$mapM$1.apply(Iteratee.scala:524) [error] at play.api.libs.iteratee.Iteratee$$anonfun$flatMapM$1.apply(Iteratee.scala:560) [error] at play.api.libs.iteratee.Iteratee$$anonfun$flatMapM$1.apply(Iteratee.scala:560) [error] at play.api.libs.iteratee.Iteratee$$anonfun$flatMap$1$$anonfun$apply$14.apply(Iteratee.scala:537) [error] at play.api.libs.iteratee.Iteratee$$anonfun$flatMap$1$$anonfun$apply$14.apply(Iteratee.scala:537) [error] at scala.concurrent.impl.Future$PromiseCompletingRunnable.liftedTree1$1(Future.scala:24) [error] at scala.concurrent.impl.Future$PromiseCompletingRunnable.run(Future.scala:24) [error] at akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:40) [error] at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:397) [error] at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260) [error] at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339) [error] at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979) [error] at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107) [error] Caused by: java.net.ConnectException: Connection refused: localhost/127.0.0.1:9000 [error] at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method) [error] at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717) [error] at org.jboss.netty.channel.socket.nio.NioClientBoss.connect(NioClientBoss.java:152) [error] at org.jboss.netty.channel.socket.nio.NioClientBoss.processSelectedKeys(NioClientBoss.java:105) [error] at org.jboss.netty.channel.socket.nio.NioClientBoss.process(NioClientBoss.java:79) [error] at org.jboss.netty.channel.socket.nio.AbstractNioSelector.run(AbstractNioSelector.java:337) [error] at org.jboss.netty.channel.socket.nio.NioClientBoss.run(NioClientBoss.java:42) [error] at org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108) [error] at org.jboss.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42) [error] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [error] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [error] at java.lang.Thread.run(Thread.java:745) When I start a second application with activator run and execute the test again, there is no problem and the test runs through successfully. I suspect that there is something wrong with the configuration, but I can't find the problem. Can anybody help?
Edit: Here is some of my code.
@Test public void test(){ RequestBuilder requestBuilder = new RequestBuilder() .method(Helpers.POST) .uri("..."); Result result = Helpers.route(request); assertEquals(OK, result.status()); } I start the FakeApplication globally within the BeforeClass method.
@BeforeClass public static void startApp(){ app = Helpers.fakeApplication(); Helpers.start(app); }
-13954594 0 building website using webservice and SOAP in ASP.NET I am new in web application. I don't know much about web services and SOAP. I am studying. Trying to understand what they are?
in parallel i wanted to make a simple demonstration using web service and SOAP protocol. I have a form(default.aspx) in my localhost. Here is the picture:

on clicking submit button, data will be passed to another page say, "welcome.aspx". I think this process can be done through a web service and following SOAP protocol.
I know, this can be done using nothing and following nothing, but to get a simple concept, i want the simplest practical example to be done.
any direction will be great, no code may be needed. Just let me know, at this point, how should i use web services and SOAP.
-22493819 0This is a job for merge:
KEYS <- data.frame(A = AList, B = BList) merge(DATA, KEYS) # A B Value # 1 1 6 9 # 2 3 8 2 Edit: after the OP expressed his preference for a logical vector in the comments below, I would suggest one of the following.
Use merge:
df.in.df <- function(x, y) { common.names <- intersect(names(x), names(y)) idx <- seq_len(nrow(x)) x <- x[common.names] y <- y[common.names] x <- transform(x, .row.idx = idx) idx %in% merge(x, y)$.row.idx } or interaction:
df.in.df <- function(x, y) { common.names <- intersect(names(x), names(y)) interaction(x[common.names]) %in% interaction(y[common.names]) } In both cases:
df.in.df(DATA, KEYS) # [1] TRUE FALSE TRUE FALSE FALSE FALSE
-29713123 0 Sql Server Data Type of a List Type I am currently designing tables for my database. I am having a hard time, since I am just a beginner in VB.Net, to figure it out on how I can store multiple data just like a list in my table. The situation is like this, the system is a Daily Field Report Log. In a particular service request, the number of plumbers will varied. Sometimes in a particular service request there will be two or three plumbers, sometimes only one plumber or more than five plumbers.
Any help or suggestion to this matter is highly appreciated. Thanks!
-21742903 0Are you using sizeof(*h) to determine the number of List elements in an array?
sizeof(*h) returns the size of List. Since tostring() only get's a pointer to a List, it has no way of knowing how many elements are pointed to.
In any case, it appears you are then writing a string to a character array of this size. What does the size of List have to do with the number of elements in the array? What are you trying to do?
We have an Adobe Flex client talking to a .NET server using WebORB. Simplifying things, on the .NET side of things we have a struct that wraps a ulong like this:
public struct MyStruct { private ulong _val; public override string ToString() { return _val.ToString("x16"); } // Parse method } And a class:
public class MyClass { public MyStruct Info { get; set; } } I want the Flex client to treat MyStruct as a string. So that for the following server method:
public void DoStuff(int i, MyClass b); It can call it as (C# here as I don't know Flex)
MyClass c = new MyClass(); c.Info = "1234567890ABCDEF" DoStuff(1, c) I've tried playing with custom WebORB serializers, but the documentation is a bit scarce. Is this possible? If so how?
I think I can work out how to serialize it, but not the other way. Do I need to write a Custom Serializer on the the Flex end as well?
-8057676 0From the install steps you've listed it sounds like you're missing a few steps.
Definitely revisit the Haystack setup instructions with a particular eye to looking at the Create a Search Site and Creating Indexes sections.
The long and short is you seem to be missing an indexes file. Haystack registers a bunch of stuff from your indexes when it is first included, so that explains why you're getting errors from haystack.__init__
Add a file called 'search_indexes.py' to your application directory. This file contains a list of the indexes you want to generate for different models. A simple example would be:
from haystack.indexes import * from haystack import site from myapp.models import MyModel class MyModelIndex(SearchIndex): text = CharField(document=True, use_template=True) def prepare(self, obj): self.prepared_data = super(MyModelIndex, self).prepare(obj) self.prepared_data['text'] = obj.my_field site.register(MyModel, MyModelIndex) This will add a free text search field called 'text' to your index. When you search for free text without a field to search specified, haystack will search this field by default. The property my_field from the model MyModel is added to this text field and is made searchable. This could, for example, be the name of the model or some appropriate text field. The example is a little naive, but it will do for now to help you get something up and running, and you can then read up a bit and expand it.
The call site.register registers this index against the model MyModel so haystack can discover it.
You'll also need a file called search_sites.py (Name as per your settings) in your project directory to point to the index files you've just made. Adding the following will make it look through your apps and auto-discover any indexes you've registered.
import haystack haystack.autodiscover()
-22963142 0 Must return a response with cookie to set your cookie properly:
Route::post('cookieset', function() { $response = Response::make('Hello World'); return $response->withCookie(Cookie::make('sectionID', Input::get('sectionID'), 60*24);); });
-6939243 0 TFS Integration Platform: How to map users with the SVN adapter? I want to migrate sourcecode from SVN to TFS2010 using the TFS Integration Platform.
I am using the Codeplex Release from March 25th of the TFS Integration Platform.
The SVN Adapter basically works. I can get the sourcecode from the SVN repository into TFS, including the full history (all revisions from SVN).
However all the checkins into TFS are done as the user that is running the TFS Integration Platform Shell.
I was wondering how I can configure a mapping of SVN users to TFS users. My SVN users are not ActiveDirectory of configured as Windows users.
I would just like to specify an explicit mapping for each SVN user to an existing TFS user.
On the web I found several hints at using a <UserMappings> element or a <ValueMap name="UserMap"> or an <AliasMappings> ... but there seems no concrete example how to configure that with the SVN adapter. All my experiments are failing...
Is this supposed to work with the SVN adapter?
Could somebody give me a hint or a pointer how to configure this mapping?
-25433843 0If you are using:
<%= render 'form', locals: {record: @record} %> then, you will need to use variable record instead of @record in your _form.html.erb as:
<% unless record.nil? %> Description:
locals: {record: @record} means, @record's value will be accessible by using record in the partial being rendered.
I'm a completely new to shell scripting and bash. My question is how do I get awk to interpret a variable which contains linebreaks the same way as awk interpret the data from stdin?
Example:
fileData=`cat /path/to/file` echo $fileData | awk '{print $1}' The code above results in the following error message: awk: program limit exceeded: maximum number of fields size=32767 which obviously means that awk interprets all the lines in $fileData at the same time and not one line at a time.
How to make awk interpret one line at a time from a variable?
-17421790 0 How to replace EclipseLink 2.3.2 with EclipseLink 2.5 in WebLogic Server 12cI currrently try to run Docx4j in WebLogic Server 12c. WebLogic Server 12c comes with EclipseLink 2.3.2.
There is a similar Post describing the situation which unfortunately yield no answer.
Docx4j does not work with the JAXB (MOXy) implementation which is part of EclipseLink 2.3.2. I got Docx4j running standalone with EclipseLink 2.5. So I am very confident that using EclipseLink 2.5 with Weblogic Server 12c will solve the issue with Docx4j.
How can I replace the EclipseLink Vesion 2.3.2 the WebLogic Server 12c is running on with EclipseLink Version 2.5?
-18353167 0 App design to MVC patternThe answer on this question Swing: how to get container bind to JRadioButton? made me think of MVC in a simple app design. I describe the general idea of an app and my thoughts on MVC pattern for this case.
Small app description:
This app lets user to add simple records that consist of name and description. After pressing "add" button, they are added to the panel as two labels and radio button to let edit the record. User can save his list in a profile (serialize to xml, properties or somewhere else).
My thoughts on how to apply MVC here:
Model
Record with name and description fields
Profile with serialization mechanism
View
Controller
2 text boxes with labels and a button to add record
button to edit a record
At the moment there's no code samples (I'll provide them a little bit later). I don't want to hurry, I want to understand whether I go in a right MVC direction or something should be changed before implementation.
Updated
Code sample
*MainClass*: public class RecordsControl extends JFrame { private RecordsModel model; private RecordsController controller; private RecordsControlView view; public RecordsControl() { super("Records Control"); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); initMVC(); getContentPane().add(view); pack(); setMinimumSize(new Dimension(250, 500)); setLocationRelativeTo(null); setResizable(false); setVisible(true); } private void initMVC() { model = new RecordsModel(); view = new RecordsControlView(controller); controller = new RecordsController(model, view); } } *Model*: public class RecordsModel { //Record class has only two fields String::name and String::description private List<Record> RecordsList; public RecordsModel() { RecordsList = new ArrayList<Record>(); } public void addRecord(String name, String description) { RecordsList.add(new Record(name, description)); } public List<Record> getRecordsList() { return RecordsList; } } *View*: public class RecordsControlView extends JPanel { private final RecordsController controller; private JLabel nameLabel; private JLabel descrLabel; private JTextField nameField; private JTextField descrField; private JButton addButton; private JButton editButton; private JButton deleteButton; private JPanel recordsListPanel; public RecordsControlView(RecordsController controller) { super(); this.controller = controller; achievNameLabel = new JLabel("Name: "); achievDescrLabel = new JLabel("Description: "); achievNameField = new JTextField(15); achievDescrField = new JTextField(15); addButton = new JButton("Add"); initGUI(); initListeners(); } private void initListeners() { addButton.addActionListener(controller); } private void initGUI() { //Main Panel this.setLayout(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); //name panel //...BoxLayout label + panel //description panel //...BoxLayout label + panel //Records list Panel //...Vertical BoxLayout //Add widgets to GridBagLayout //Name panel constraints.gridx = 0; constraints.gridy = 0; constraints.insets = new Insets(5, 5, 2, 2); add(namePanel, constraints); //Description Panel constraints.gridx = 0; constraints.gridy = 1; constraints.insets = new Insets(0, 5, 5, 2); add(descrPanel, constraints); //Add button constraints.gridx = 1; constraints.gridy = 0; constraints.gridheight = 2; constraints.gridwidth = 1; constraints.insets = new Insets(5, 0, 5, 5); constraints.fill = GridBagConstraints.VERTICAL; add(addButton, constraints); //Records List panel constraints.gridx = 0; constraints.gridy = 2; constraints.gridwidth = GridBagConstraints.REMAINDER; constraints.gridheight = GridBagConstraints.REMAINDER; constraints.fill = GridBagConstraints.BOTH; constraints.insets = new Insets(0, 5, 5, 5); add(recordsListPanel, constraints); } public JButton getAddButton() { return addButton; } public void addRecord(JPanel record) { recordsListPanel.add(record); } } public class RecordsView extends JPanel { private static ButtonGroup radioButtons = new ButtonGroup(); private JRadioButton radioButton; private JLabel name; private JLabel description; public RecordsView() { super(); radioButton = new JRadioButton(); name = new JLabel(); description = new JLabel(); initGUI(); } private void initGUI() { radioButtons.add(radioButton); setLayout(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); constraints.gridx = 0; constraints.gridy = 0; add(radioButton, constraints); constraints.gridx = 1; constraints.gridy = 0; constraints.weightx = 1.0; constraints.fill = GridBagConstraints.HORIZONTAL; add(name, constraints); constraints.gridx = 1; constraints.gridy = 1; constraints.weightx = 1.0; constraints.fill = GridBagConstraints.HORIZONTAL; add(description, constraints); } *Controller*: public class RecordsController implements ActionListener{ private final RecordsModel model; private final RecordsControlView view; public RecordsController(RecordsModel model, RecordsControlView view) { this.model = model; this.view = view; } @Override public void actionPerformed(ActionEvent e) { if(e.getSource() == view.getAddButton()) { RecordsView record = new RecordsView(); view.add(record); view.updateUI(); } } }
-33821655 0 It seems that your TFS Build Service account has no required permission to access the signingKey.pfx on build agent machine. Make sure you have this file on build agent machine first.
Then follow below steps:
sn –i signingKey.pfx VS_KEY_EFCA4C5B6DFD4B4F(Ensure that you use the key name appearing in the error message)When prompted for a password type the password for the pfx file
Then rebuild it
Note: If you are not running Visual Studio as an Administrator try doing that as well.
More details you can reference the answer from Brandon Manchester Cannot import the keyfile 'blah.pfx' - error 'The keyfile may be password protected'
-21760325 0An important thing to notice: strcpy's behavior is undefined (see C99 7.23.2.3:2) when provided with overlapping source and destination. So what you're doing, no matter how the output looks, is basically not guaranteed to work unless your C implementation's documentation states otherwise.
Use memmove when moving data within a string.
You should also be very careful in how you declare your string. The code you provided is correct:
char string[] = "foo"; The string is an array of characters, initialized to contain four elements: 'f', 'o', 'o', '\0'.
But, very similar code would be incorrect:
char * string = "foo"; What this code does is initializes a char pointer to the address of a constant string literal "foo". A correct version would be:
const char * string = "foo"; If you tried to modify such a string, the compiler would rightly complain.
-5619794 0 In C++, is a struct also a class?Possible Duplicate:
C/C++ Struct vs Class
I know the technical differences between a struct and a class; and of course that question has been asked before.
Object-oriented programming relates objects and classes. In C++ taxonomy, is a struct also a class?
-2531620 0Click the Info button on your xib's main window, and set the Deployment Target to iPhone OS 3.0 or iPhone OS 3.1.
Edit: Images!

(NB: These are from the 10.5 version of IB, but IIRC the 10.6 version is the same or close to it.)
-35045984 0Flexbox can do that:
.chatbox { margin: 1em auto; width: 150px; height: 500px; border: 1px solid grey; display: flex; flex-direction: column-reverse; justify-content: flex-start; text-align: center; } .message { background: lightgreen; margin-bottom: .25em; padding: .25em 0 0 0; border-bottom: 2px solid green; } <div class="chatbox"> <div class="message">MESSAGE 1</div> <div class="message">MESSAGE 2</div> <div class="message">MESSAGE 3</div> <div class="message">MESSAGE 4</div> <div class="message">MESSAGE 5</div> <div class="message">MESSAGE 6</div> <div class="message">MESSAGE 7</div> <div class="message">MESSAGE 8</div> <div class="message">MESSAGE 9</div> <div class="message">MESSAGE 10</div> <div class="message">MESSAGE 11</div> <div class="message">MESSAGE 12</div> </div> $strBody = "Today is" .date("l"); Otherwise (when using +) it converted to int.
Array index start from 0.
I presume when you say it hides the right answer button is when the answer is "2", since by your giveHint function it will remove index 1 from answers array which is "2".
Change your giveHint removeAtIndex will do the trick.
func giveHint(sender: UIButton){ if self.answer != "1" { answers.removeAtIndex(0) Button1.alpha = 0 } else if self.answer != "2" { answers.removeAtIndex(1) Button2.alpha = 0 } else if self.answer != "3" { answers.removeAtIndex(2) Button3.alpha = 0 } else if self.answer != "4" { answers.removeAtIndex(3) Button4.alpha = 0 } }
-20741020 0 App Not Installed error I have created an unsigned apk for my nexus 7. When I try and install it, the device pops up with, "App Not Installed". In the Eclipse emulator everything works fine. I have tried to alter my target to 4.2,4.3,4.4. Again, all work in the emulator but not on the device, the device is running 4.3.
-34286567 0 How to send image file via Alamofire?I want to send an image to the server and I'm using this code:
Alamofire.upload( .POST, "https://api.mysite.com/image", multipartFormData: { multipartFormData in if let _ = image { if let imageData = UIImageJPEGRepresentation(image!, 1.0) { multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "file.png", mimeType: "image/png") } } }, encodingCompletion: { encodingResult in switch encodingResult { case .Success(let upload, _, _): upload.responseJSON { response in switch response.result { case .Success: debugPrint(response) case .Failure(let error): print(error) } } case .Failure(let encodingError): print(encodingError) } } ) but in response I get:
[Result]: SUCCESS: ( "", { file = { error = 1; name = "file.png"; size = 0; "tmp_name" = ""; type = ""; }; so my file is not sending to the server. What is the wrong in my code?
-21008833 0 build query to select data based on another tabletables 
sample data
walls
wall_id wall_name 1 wall_1 2 wall_2 6 wall_6 wall_categories
wall_id category_id 1 2 2 1 6 1 6 2 categories
category_id category_name 1 Wallpaper 2 Photography html
<a href="file.php?category=wallpaper">Wallpaper</a> <a href="file.php?category=photography">Photography</a> What I need to do is when the user click the Wallpaper link, I want the images with wallpaper as category to be displayed same with photography. I have built an initial query but it generates duplicate records as I'm using join, there must be something else that need to be added to make it work.
SELECT DISTINCT walls.wall_id, walls.wall_name, walls.wall_views, walls.upload_date, categories.category_name FROM categories INNER JOIN wall_categories ON wall_categories.category_id=categories.category_id INNER JOIN walls ON walls.wall_id=wall_categories.wall_id; or since the category_id is fixed, we can use walls and wall_categories table only. Then lets' say we can use the following html.
<a href="file.php?category=1">Wallpaper</a> <a href="file.php?category=2">Photography</a>
-32803472 0 Create a SIN number validator I am creating a C program which tests if a user has entered a valid SIN number. Here is what I have done so far:
#include <stdio.h> int main(void) { int num1; printf("Enter your SIN number: \n"); scanf("%d", &num1); } SIN number is a 9 digit long number. To see if it is valid, I want to multiply the SIN number like this:
add SIN number with 121 212 121. 123 456 789 121 212 121 How would I do this part in C programming language?
-35953266 0 how to toggle replies, show and hide replies. And by default they should be hidden.I have this commenting system that works fine issue is when I refresh the page, replies are not folded. I have to click button to fold them
So to be as clear as possible, if there's comment A, and then under that comment A I want to have "view all x replies" button that's folded. if that button is clicked all the replies need to be shown.
So here's what I did.
<div class="wholeReply"> <a href='#' class='replies'> {{comment.comment_count}} replies</a> <div class="got_replies"> <ul> {% for child in comment.get_children %} <li>{{ child.get_comment }} <small><a href="{% url 'userena_profile_detail' post.moderator.username %}">{{ child.user.user }}</a></small> </li> {% endfor %} </ul> </div> </div> <script> $('.replies').click(function(e){ e.preventDefault(); $(this).next(".got_replies").fadeToggle(); // $(".reply_comment").fadeToggle(); }) </script>
-24607298 0 You're not storing the actual image (binary data) into the database, but the tmp_name (string). Use file_get_contents(), like so:
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
-5944027 0 You don't, the user decided that she was tired of waiting and wanted to work with a responsive program. Review the fine print in SetForegroundWindow() for all the reasons that trying to find a workaround for this won't actually work. Make sure she can get back to the program when it is initialized, a taskbar button is key.
-21264714 0 Procedure to return first name when inputting last namecreate or replace procedure p_inout (v_emp_lname in varchar2(25)) as v_first_name varchar2(20); begin select first_name into v_first_name from employees where last_name=v_emp_lname; dbms_output.put_line(v_first_name); end; I am getting Error(2,25): PLS-00103: Encountered the symbol "(" when expecting one of the following: := . ) , @ % default character The symbol ":=" was substituted for "(" to continue.
-556091 0 OnReadyStateChange event in ActiveX controlsI wrote a Firefox plugin (only compatible with FF3 atm) that allows the hosting of ActiveX controls.
Before the flaming begins - this is not the main topic for this question and the plugin was designed with security in mind so it doesn't break my favorite browser. if you are interested, it's hosted at http://code.google.com/p/ff-activex-host/.
Now, I've noticed that in IE all ActiveX controls have an event called OnReadyStateChange available, however, not all ActiveX controls have that event listed in their TypeLib. As a result, my plugin cannot register handlers for this event for every ActiveX control.
Opening such controls with OleView, I can't find the OnReadyStateChange event either - leading me to believe that IE might be 'cheating' here to make it work. When OleView shows such a handler (as with the Shockwave ActiveX control), I have no troubles registering handlers for it.
An example of such a control is Microsoft's Terminal Services ActiveX. But it's not a problem limited to MS ActiveX controls.
I am not an expert on COM Objects, am I searching for the event in a wrong way or at the wrong place?
Right Now I think I'm doing it right, since OleView can't find it either, so...
Can I somehow 'cheat' the same way IE does and make this event available anyway?
-32025692 0Try this:
<?php if ($_POST['sub']) { $server = "localhost"; $username = "yourusernamehere"; $pass = "yourpasswordhere"; $db = "users"; // Create connection $mysqli = new mysqli($server, $username, $pass, $db); // Check connection if ($mysqli->connect_error) { die("Connection failed: " . $mysqli->connect_error); } echo "Connected successfully"; $uname = mysql_escape_string($_POST['username']) $mail = mysql_escape_string($_POST['email']); $sql = "INSERT INTO users (username, email) VALUES ('$uname', '$mail')"; $insert = $mysqli->query($sql); if ($insert){ echo "Success! Row ID: {$mysqli->insert_id}"; header("Location:main.php"); } else { die("Error: {$mysqli->errno} : {$mysqli->error}"); } $mysqli->close(); } ?> <!DOCTYPE html> <html> <body> <form action = "" method = "POST"> <label>Enter your Username:</label> <input type="text" name="username" required> <label>Enter your Email:</label> <input type="email" name="email" required > <input type="hidden" name = "check"> <input type="submit" name = "sub" value = "INSERT"> </form> </body> </html> -37023758 0 How to move HBase tables to HDFS in Parquet format?Your database name as it lookes on the third line is
'users'and so is the name of your table that you are trying toINSERT INTOinto"users'line 10. Are you sure your are not messing up there?
I have to build a tool which will process our data storage from HBase(HFiles) to HDFS in parquet format.
Please suggest one of the best way to move data from HBase tables to Parquet tables.
We have to move 400 million records from HBase to Parquet. How to achieve this and what is the fastest way to move data?
Thanks in advance.
Regards,
Pardeep Sharma.
-22544035 0 Microsoft Visual Studio 2013 Link Error 1104A while ago I attempted to make make a game using c++ and SDL. I am now taking a class that requires me to program in C++ and I would like to use VS as the IDE. I uninstalled VS 2012 and upgraded to 2013. I am able to compile c# code but when I make a c++ project I get the error
error LNK1104: cannot open file 'SDL.lib'
I went to the project properties -> Configuration Properties -> Linker -> input and made sure that SDL was not referenced there. My Additional Dependencies now has the value %(AdditionalDependencies). The rest of the options are blank. I also made sure that in VC++ Directories the Include Directories did not include anything related to SDL. Having done all of this I still get the same error. Is is somehow inheriting the SDL linker. The project only contains a hello world program which does not include any other libraries. Any help is appreciated.
-28351505 0I think that your problem is that you want to use $requests as a global variable. In your code it's not. You should pass it as a reference:
$mh = curl_multi_init(); $requests = array(); addSentimentHandle ( 'Hello', $requests ); addSentimentHandle ( 'Hello :)', $requests ); function addSentimentHandle($tweet, &$requests) { $url = makeURLForAPICall($tweet); array_push($requests, curl_init ($url)); print_r($requests); } note the '&' as a prefix for $requests in function declaration. Then php wont used it as a local variable in this function.
I recommend to you to use php as an object oriented language.
class myAwesomeTweeterClass{ protected $_requests; public function __construct(){ $this->_requests = array(); } public function addSentimentHandle($tweet) { $url = makeURLForAPICall($tweet); array_push($this->_requests, curl_init ($url)); } public function getRequests(){ return $this->_requests; } } $mh = curl_multi_init(); $obj = new myAwesomeTweeterClass(); $obj->addSentimentHandle ( 'Hello'); $obj->addSentimentHandle ( 'Hello :)'); print_r($obj->getRequests());
-14002092 0 Unable to connect XMPP server with ASmack in Android I have a fully working Chat Client that I made in Java. Now I'm looking forward to implement the same on my android device. I started off with importing the ASmack Library in my project and I'm checking at each phase to avoid errors. I'm stuck at the very first step though. My Activity is not able to find the class in ASmack Jar, hence I assume I'm unable to proceed.
My Simple code :
package com.test.mypro; import org.jivesoftware.smack.ConnectionConfiguration; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPException; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; public class TestProjectActivity extends Activity { private static final String LOG_TAG = "TESTER"; /** Called when the activity is first created. */ TextView tvHello; XMPPConnection connection; ConnectionConfiguration config; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tvHello = (TextView) findViewById(R.id.tvHello); Log.i(LOG_TAG, "I'm here"); config = new ConnectionConfiguration("prc.p1.im", 5222, "prc.p1.im"); connection = new XMPPConnection(config); try { connection.connect(); // tvHello.setText("Connected to XMPP server"); Log.i(LOG_TAG, "Successfully Connected"); } catch (XMPPException e) { // TODO Auto-generated catch block e.printStackTrace(); Log.e(LOG_TAG, "Not Connected"); } } } LogCat Logs:
12-22 15:58:16.319: E/dalvikvm(828): Could not find class 'org.jivesoftware.smack.ConnectionConfiguration', referenced from method com.test.mypro.TestProjectActivity.onCreate 12-22 15:58:16.339: W/dalvikvm(828): VFY: unable to resolve new-instance 26 (Lorg/jivesoftware/smack/ConnectionConfiguration;) in Lcom/test/mypro/TestProjectActivity; 12-22 15:58:16.339: D/dalvikvm(828): VFY: replacing opcode 0x22 at 0x0019 12-22 15:58:16.351: D/dalvikvm(828): VFY: dead code 0x001b-0047 in Lcom/test/mypro/TestProjectActivity;.onCreate (Landroid/os/Bundle;)V 12-22 15:58:16.509: I/TESTER(828): I'm here 12-22 15:58:16.519: D/AndroidRuntime(828): Shutting down VM 12-22 15:58:16.519: W/dalvikvm(828): threadid=1: thread exiting with uncaught exception (group=0x40015560) 12-22 15:58:16.561: E/AndroidRuntime(828): FATAL EXCEPTION: main 12-22 15:58:16.561: E/AndroidRuntime(828): java.lang.NoClassDefFoundError: org.jivesoftware.smack.ConnectionConfiguration 12-22 15:58:16.561: E/AndroidRuntime(828): at com.test.mypro.TestProjectActivity.onCreate(TestProjectActivity.java:24) 12-22 15:58:16.561: E/AndroidRuntime(828): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 12-22 15:58:16.561: E/AndroidRuntime(828): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611) 12-22 15:58:16.561: E/AndroidRuntime(828): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663) 12-22 15:58:16.561: E/AndroidRuntime(828): at android.app.ActivityThread.access$1500(ActivityThread.java:117) 12-22 15:58:16.561: E/AndroidRuntime(828): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931) 12-22 15:58:16.561: E/AndroidRuntime(828): at android.os.Handler.dispatchMessage(Handler.java:99) 12-22 15:58:16.561: E/AndroidRuntime(828): at android.os.Looper.loop(Looper.java:123) 12-22 15:58:16.561: E/AndroidRuntime(828): at android.app.ActivityThread.main(ActivityThread.java:3683) 12-22 15:58:16.561: E/AndroidRuntime(828): at java.lang.reflect.Method.invokeNative(Native Method) 12-22 15:58:16.561: E/AndroidRuntime(828): at java.lang.reflect.Method.invoke(Method.java:507) 12-22 15:58:16.561: E/AndroidRuntime(828): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 12-22 15:58:16.561: E/AndroidRuntime(828): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 12-22 15:58:16.561: E/AndroidRuntime(828): at dalvik.system.NativeStart.main(Native Method) Additional Info : I have asmack-android-7.jar library imported. My AVD is running 2.3.3 Android.
I assume owing to this I'm getting the fatal exception. What am I missing here? Your help would be appreciated. Thank you.
-37187338 0 Input path limit for Android ndk source fileIs there a known limit on the path for the Android ndk input files? I've run into an issue where the input path is over 155 characters the android g++ command fails to find the file.
The local path back down to my base directory is quite deep, in a few cases I have a full path back to a source file in the jni project making the path a bit long, though 155 doesn't seem like a very high limit.
LOCAL_PATH := $(call my-dir)/../../../../../../../../../..
Here is an example of a failure, at 155 characters:
/cygdrive/c/java/Android/android-ndk-r10d/toolchains/arm-linux-androideabi-4.8/prebuilt/windows-x86_64/bin/arm-linux-androideabi-g++ -c jni/VECodecG723/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/./././VECodecG723/VECodecG723.cpp arm-linux-androideabi-g++.exe: error: jni/VECodecG723/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/./././VECodecG723/VECodecG723.cpp: No such file or directory arm-linux-androideabi-g++.exe: fatal error: no input files And a success case, at 153 characters:
/cygdrive/c/java/Android/android-ndk-r10d/toolchains/arm-linux-androideabi-4.8/prebuilt/windows-x86_64/bin/arm-linux-androideabi-g++ -c jni/VECodecG723/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/././VECodecG723/VECodecG723.cpp jni/VECodecG723/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/././VECodecG723/VECodecG723.cpp:26:17: fatal error: jni.h: No such file or directory #include <jni.h> The repeating ../gen is just for this sample, the actual path contains 10 ../ and then the full path back to the file.
I've tried the paths with the regular g++ compiler and it does not fail because of the path length. I have also tried this in a Windows command shell with the android g++ and it has the same issue.
Is there anything I can do short of renaming my folders.
-34691358 0Put what you want to exclude inside a negative lookahead in front of the match. For example,
To match all punctuations apart from the question mark,
/(?!\?)[[:punct:]]/ To match all words apart from "go",
/(?!\bgo\b)\b\w+\b/ grep and find will use different regular expression engines. Notably, POSIX regular expressions (which find uses) don't include "\b" as a word boundary, so it is the same as "b". On OSX, for instance, these have the same result:
find . -regex '.*bar2.txt' -print
and
find . -regex '.*\bar2.txt' -print
Double check the manpage to make sure that -regex is doing what you think. For my find the regular expression must match the entire filename, e.g. this doesn't find any files:
find . -regex 'bar' -print
but this one does:
find . -regex '.*bar.*' -print
Try this:-
<RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <ImageView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:src="@drawable/clock_number"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Hello World!" /> </RelativeLayout>
-4528828 0 Your plugin should add a class or maybe a .data cache item to elements that have already been activated by the plugin. Then inside your plugin you can ignore an element if it has already been activated.
Also another way is just to select elements from the fragment returned by the ajax call.
$('.class').plugin(); $.post(url, function(response) { // add more .class elements. $(response).find('.class').plugin(); });
-10105544 0 Crossdomain issue when loading video thumbnails (Flash) I'm trying to display some Facebook video thumbnails in a Flash application, all of the video thumbnails i try to load seem to be hosted at https://fbcdn-vthumb-a.akamaihd.net.
However crossdomain.xml cannot be loaded (Access Denied). Is there some way around this? (other than loading the images through a proxy). Maybe an alternative url which can be used?
edit: This is a Facebook bug and has been reported
-21222137 0It simply replaces x with 1.0f, so:
NSNumber *n = FBOX(1.0f); becomes:
NSNumber *n = [NSNumber numberWithFloat:1.0f]; this is then presented to the compiler.
-23243249 0 How to play .mkv video in ASP.NET MVC using Microsoft.Web.Helpers.Video?THis is a Self explantory title! I have a asp.net mvc application where I display videos from youtube. Now we decided not to use youtube because of their ads and other... First I used
@Microsoft.Web.Helpers.Video.Flash(...) to display .swf videos. Can anyone tell me How to play .mkv videos in ASP.NET MVC using(or not using) Microsoft.Web.Helpers.Video helper ?
The only progress I have made on this question is the discovery that on the workstation I was using, the SUBST command was used to create drive D. That is to say, C and D are really the same physical drive.
SUBST does not seem to completely break Git though. I have the project on drive D and the git repo on a completely different directory on drive D and everything works.
username@host /d/ProjectName (branch) $ cat .git gitdir: d:\gitrepo\ProjectName.git So the best answer I have is a workaround, where I advise: In Windows there may be an issue:
1. If the repo and working dir are on different drives 2. If (1) is true and you use SUBST But whichever of those is the case, the work around is one or both of the following:
1. put everything on the same drive letter. It works even if that drive is a 'subst' drive. 2. Use the windows "d:\" notation in the .git file
-2329519 0 String literals are simply zero terminated array of chars in C++. There is no operator that allows you to add 2 arrays of chars in C++.
There is however a char array and std::string + operator.
Change to:
const std::string message = std::string("Hello") +", world" + exclam; In some languages like Python string literals are equivalent to variables of type strings. C++ is not such a language.
-35011563 0 code stuck when `global` is addedI have weird problem-
I have this function
function doSomething(par1, par2) global str; // more code on remark.. // im using str here end this function located inside nested while
function mainFunction global str; //im using str here while (i<500) while (j<500) doSomething(val1, val2); // some variables j = j+1; end j=1 i = i+1; end end when I ran the code, it get stuck (even that the whole code inside that function is remarked and only the global str is left). but when I remove the global str (empty function), only within the doSomething function, the code gets to the end and finishes correctly.
str is not complex database, its just regular string..
I don't quite know why it happens, or maybe im doing something wrong.
-14763233 0If there is a FOREIGN KEY constraint from activity to item (and assuming that user_id is in table activity), then your query is equivalent to:
SELECT COUNT(*), COUNT(DISTINCT user_id) FROM activity WHERE item_id = 3839 AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) ; which should be more efficient as it has to get data from only one table or just one index. An index on (item_id, created_at, user_id) would be useful.
I am using Phonegap and JQueryMobile to create a web application. I'm new to javascript and am having an issue.
My issue is with calling a function I have in a file named "testscript.js", the function is called testFunc. The testscript.js containts only this:
function testFunc() { console.log("Yes I work"); } Within my html page I have the following code:
<script> $('#pageListener').live('pageinit', function(event) { testFunc(); }); </script> The test function is found within my "testscript.js" which I am including with this line within the head tags:
<script src="testscript.js"></script> The error I get is a "testFunc is not defined".
I am assuming its some type of scope issue as I'm able to call other jquery functions such as:
alert("I work"); and I am able to call my functions by sticking them within script tags in the html elsewhere.
I've tried all sorts of ways of calling my function with no success, any help is appreciated!
-27827463 0On Windows at the command prompt run: gradlew referencePdf --stacktrace and that should tell you what happened. In my case, it was a heap size issue. I set an environment variable set GRADLE_OPTS="-Xmx1024m" then was able to build the pdf successfully.
it's an array, not a string, so just give it the array of points:
... var points = []; $(this).children("input").each(function(index) { points[index] = $(this).val(); }); var plot1 = $.jqplot('chart1',[points]); updated fiddle: http://jsfiddle.net/fdKRw/4/
-533040 0The two forms are equivalent.
The recommended style is to use the braces for one line blocks and use the "do"-"end" for multiline blocks.
Edit: Austin Ziegler pointed out (in the comment below) that the two forms have difference precedence levels: Curly braces have higher precedence. Therefore, when calling a method without parenthesis a block enclosed in {} will bind to the last argument instead of the calling method.
The following example was suggested by Austin:
def foo yield end puts foo { "hello" } puts foo do "hello" end The first "puts" prints "hello": foo gets called returning "hello" which is the argument to puts.
The second bails with an error:
in `foo': no block given Since in this case the do-end block binds to the puts method.
Thanks again to Austin for clearing this up.
-37561298 0Okey after some research I found the answer. All you need is to ask sessionFactoryBuilder to generate update scripts for your database and execute than with JdbcTemplate.
LocalSessionFactoryBuilder sessionFactory = new LocalSessionFactoryBuilder(dataSource); sessionFactory.scanPackages("su"); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); try{ List<SchemaUpdateScript> scripts = sessionFactory.generateSchemaUpdateScriptList(new PostgreSQL9Dialect(), new DatabaseMetadata(dataSource.getConnection(), new PostgreSQL9Dialect(), sessionFactory)); log.info("Schema update scripts["+scripts.size()+"]"); for (SchemaUpdateScript script:scripts ) { log.info(script.getScript()); jdbcTemplate.execute(script.getScript()); } }catch (Exception e){ log.error("error updating schema",e); }
-14511449 0 Understanding Core Data Queries(searching data for a unique attribute) Since I am coming from those programmers who have used sqlite extensively, perhaps I am just having a hard time grasping how Core Data manages to-many relationships.
For my game I have a simple database schema on paper.
Entity: Level - this will be the table that has all information about each game level Attributes: levelNumber(String), simply the level number : levelTime(String), the amount of time you have to finish the level(this time will vary with the different levels) : levelContent(String), a list of items for that level(and that level only) separated by commas : levelMapping(String), how the content is layed out(specific for a unique level) So basically in core data i want to set up the database so i can say in my fetchRequest:
Give me the levelTime, levelContent and levelMapping for Level 1.(or whatever level i want)
How would i set up my relationships so that i can make this type of fetchRequest? Also I already have all the data ready and know what it is in advance. Is there any way to populate the entity and its attributes within XCode?
-1749330 0I'm trying to do something similar. It seems like everyone saying 'you should only have a foreign key one way' has maybe misunderstood what you're trying do.
It's a shame the limit_choices_to={"myparent": "self"} you wanted to do doesn't work... that would have been clean and simple. Unfortunately the 'self' doesn't get evaluated and goes through as a plain string.
I thought maybe I could do:
class MyModel(models.Model): def _get_self_pk(self): return self.pk favourite = modles.ForeignKey(limit_choices_to={'myparent__pk':_get_self_pk}) But alas that gives an error because the function doesn't get passed a self arg :(
It seems like the only way is to put the logic into all the forms that use this model (ie pass a queryset in to the choices for your formfield). Which is easily done, but it'd be more DRY to have this at the model level. Your overriding the save method of the model seems a good way to prevent invalid choices getting through.
Update
See my later answer for another way http://stackoverflow.com/a/3753916/202168
In most cases, you could have one RDS instance that all 3 ec2 instances connect to. If you have a very relational demanding database application, you can look into database replication.
-30447654 0You have to set up a root layout for your activity, which is holding the fragment in your xml code. Here is an example with a LinearLayout as a root layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <fragment android:id="@+id/map" android:layout_width="match_parent" android:layout_height="match_parent" android:name="com.google.android.gms.maps.MapFragment"/> </LinearLayout>
-23573074 0 Can I load all shipping methods automatically on the shopping cart page without selecting a country first? Can I load all my shipping methods automatically on the shopping cart page without prior to selecting a country?
By Magento default, you have to select your country where you want to ship your order to. Then you have to hit the button 'Get a quote' for the 'Estimate Shipping and Tax'. But I want to skip this step by showing all my shipping methods automatically as soon as you are on this page.
Is it possible?
-37610094 0You could use:
echo "<pre>"; var_dump($array); echo "</pre>"; This way you will get a nice preformatted result of var_dump.
-30595483 0you missed this part i think
conn = mysql.connector.MySQLConnection(host='localhost',port='8051', database='example', user='root', password='tiger') cursor = conn.cursor() if conn.is_connected(): print('Connected to MySQL database') cursor.execute(""" SELECT * FROM album """) # fetch all of the rows from the query data = cursor.fetchall () # print the rows for row in data : print row[1]
-19916912 0 Did You also consider a non-recursive solution like presented here? http://stackoverflow.com/a/929418/2979680
-29166824 0 $interval issue, ends unexpectedlyI am new to angularjs so this is probably simple. I have this as my main app entry point:
<div ng-app="mainApp"> <div ng-view></div> </div> Routed as such:
$routeProvider .when('/general', { templateUrl: '/Rewards/SelfService_General', controller: 'GeneralController' }) .when('/resources', { templateUrl: '/Rewards/SelfService_Resources', controller: 'ResourcesController' }) .otherwise({ redirectTo: '/general' }); My resources controller is as such:
appRoot.controller('ResourcesController', ['$scope', '$interval', '$http', function ($scope, $interval, $http) { $scope.GetResources = function GetResources() { var requestData = { AccessKey: "", Culture: "" }; $http.post('http://myapi.com/etc', requestData) .success(function (data, status, headers, config) { $scope.ViewName = status; alert('success'); }) .error(function (data, status, headers, config) { $scope.ViewName = status; alert('error'); }); }; $interval($scope.GetResources(), 5000); }]); On loading the page, the GetResources function is immediately called and as expected, hits the error function returning a 401 status. What surprises me is that no further calls to GetResources are made. Why is the interval ended?
-142503 0Great Question! If I'm not mistaken I don't think debugging is possible inside of SQL Management Studio anymore (as it was back in the SQL Server 2000, Enterprise Studio days).
Happy Debugging!
-40964811 0Firstly, I agree with the previous answer that you should be using the strict equality operator. Secondly, you are using incorrect syntax - where you have data-bind should be ko, i.e.:
<!-- ko if: header.current_collection.url_type === 'stories' --> <p>text</p> <!-- /ko --> You can find the knockout if binding docs here
-20970512 0 Junit for spring securityI've used the spring security http element to enforce security, in the securityContext.xml. I am able to successful secure my web app. I want to write a junit for the same. Will I be able to write it.
-6596940 0This is because image.Pointer() is a smart pointer object, a wrapper around the read pointer to your data. You must pass image.Pointer().GetPointer() to fftw.
I am working on fixing someone's Android app. It was originally made for 2.1 and I am trying to get it work to 4.0+. Unfortunately the person who made the app is not around so I am stuck with his code.
The app implements custom sliders, a horizontal and vertical. I got the vertical slider fixed, but I cannot get the horizontal slider to work. It is not calling onDraw(): When the view loads, onDraw() gets called and I see both of my sliders initialized, then when I move my horizontal slider it moves and calls onDraw() once, but never again will it call it, unlike the vertical slider which does call it.
Here is the code:
public class PanSeekBar extends RelativeLayout { private RelativeLayout layout1; public ImageView track; public ImageView thumb; public boolean initialized = false; public int thumbDownPosX = 0; public int thumbDownPosY = 0; public int thumbLeft = 0; public int thumbTop = 0; public int thumbRight = 0; public int thumbBottom = 0; private int max = 100; public boolean touched = false; public PanSeekBar(Context context) { super(context); initialize(context); // TODO Auto-generated constructor stub }// End of PanSeekBar Constructor private void initialize(Context context) { Log.d("initialize (PanSeekBar)", "initialize"); setWillNotDraw(false); LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view1 = inflater.inflate(R.layout.pan_seekbar, this); layout1 = (RelativeLayout) view1.findViewById(R.id.ps_layout1); track = (ImageView) layout1.findViewById(R.id.ps_track); thumb = (ImageView) layout1.findViewById(R.id.ps_thumb); thumb.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { initialized = true; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: Log.d("onTouch (PanSeekBar)", "Action Down"); thumbDownPosX = (int) event.getX(); thumbDownPosY = (int) event.getY(); thumbLeft = thumb.getLeft(); thumbTop = thumb.getTop(); thumbRight = thumb.getRight(); thumbBottom = thumb.getBottom(); touched = true; break; case MotionEvent.ACTION_MOVE: // Log.d("onTouch (PanSeekBar)", "Action Move"); int left = (int) (thumb.getLeft() + event.getX() - thumbDownPosX); if (left < 0) { left = 0; Log.d("onTouch (PanSeekBar)", "left < 0: " + left); } else if (left >= track.getWidth() - thumb.getWidth()) { left = track.getWidth() - thumb.getWidth(); Log.d("onTouch (PanSeekBar)", "left >= track.getWidth(): " + left); } int top = thumb.getTop(); int right = left + thumb.getWidth(); int bottom = top + thumb.getHeight(); thumbLeft = left; thumbTop = top; thumbRight = right; thumbBottom = bottom; Log.d("onTouch (PanSeekBar)", "Action Move -- thumb layout: " + thumbLeft + ", " + thumbTop + ", " + thumbRight + ", " + thumbBottom); layout1.invalidate(); // thumb.invalidate(); break; case MotionEvent.ACTION_UP: Log.d("onTouch (PanSeekBar)", "Action Up"); touched = false; break; }// End of switch return true; }// End of onTouch }); }// End of initialize @Override protected void onDraw(Canvas canvas) { Log.d("onDraw (PanSeekBar)", "onDraw"); super.onDraw(canvas); if (initialized) { thumb.layout(thumbLeft, thumbTop, thumbRight, thumbBottom); Log.d("onDraw (PanSeekBar)", "thumb layout: " + thumbLeft + ", " + thumbTop + ", " + thumbRight + ", " + thumbBottom); } }// End of onDraw }// End of PanSeekBar Here is the code for the vertical slider that does work:
public class MySeekBar extends RelativeLayout { private RelativeLayout layout1; public ImageView track; public ImageView thumb; private MyToast toast; private MyToast toast2; private MyToast toast3; private int globalMaxValue; private int globalProgress; private boolean initialized = false; public int thumbDownPosX = 0; public int thumbDownPosY = 0; public int thumbLeft = 0; public int thumbTop = 0; public int thumbRight = 0; public int thumbBottom = 0; private int globalSetProgress = 0; private int globalConfigType = 1; // Margin top in custom_seekbar.xml private int marginTop = 20; public boolean touched = false; public MySeekBar(Context context) { super(context); // TODO Auto-generated constructor stub initialize(context); }// End of MySeekBar public void initialize(Context context) { Log.d("initialize (MySeekBar)", "initialize"); setWillNotDraw(false); LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view1 = inflater.inflate(R.layout.custom_seekbar, this); layout1 = (RelativeLayout) view1.findViewById(R.id.al_cs_layout1); track = (ImageView) layout1.findViewById(R.id.cs_track); thumb = (ImageView) layout1.findViewById(R.id.cs_thumb); // Gets marginTop MarginLayoutParams params = (MarginLayoutParams) track .getLayoutParams(); Log.d("initialize (MySeekBar)", "current margintop = " + marginTop); marginTop = params.topMargin; Log.d("initialize (MySeekBar)", "new margintop = " + marginTop); // int marginTopPixelSize = params.topMargin; // Log.d("initialize (MySeekBar)","debug = "+marginTopPixelSize); // Jared // When creating MyToast, setting width causes issues. toast = new MyToast(context); toast.setText(""); toast.setBackgroundColor(Color.LTGRAY); toast.setTextColor(Color.BLACK); toast.setPadding(1, 1, 1, 1); toast.setVisibility(View.INVISIBLE); toast.setTextSize(10f); // toast.setWidth(40); toast2 = new MyToast(context); toast2.setTextSize(12f); toast2.setTextColor(Color.rgb(192, 255, 3)); // toast2.setWidth(40); toast2.setPadding(10, 1, 1, 1); // toast2.setBackgroundColor(Color.BLACK); toast2.setVisibility(View.INVISIBLE); toast3 = new MyToast(context); toast3.setText("CH"); toast3.setTextSize(15f); toast3.setTextColor(Color.rgb(192, 255, 3)); // toast3.setWidth(40); toast3.setPadding(1, 1, 1, 1); layout1.addView(toast); layout1.addView(toast2); layout1.addView(toast3); thumb.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { initialized = true; // 0=down 1=up 2=move // Log.d("onTouch (MySeekBar)", // Integer.toString(event.getAction())); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: Log.d("onTouch (MySeekBar)", "Action Down"); thumbDownPosX = (int) event.getX(); thumbDownPosY = (int) event.getY(); // Position of thumb touched. Irrelevant to scale // Log.d("onTouch (NewSeekBar)","thumbDownPosX "+thumbDownPosX+" thumbDownPosY "+thumbDownPosY); thumbLeft = thumb.getLeft(); thumbTop = thumb.getTop(); thumbRight = thumb.getRight(); thumbBottom = thumb.getBottom(); touched = true; toast2.setVisibility(View.INVISIBLE); toast3.setVisibility(View.INVISIBLE); toast.setVisibility(View.VISIBLE); // Location/size of the thumb button // Log.d("onTouch (NewSeekBar)","thumbLeft "+thumbLeft+" thumbRight "+thumbRight+" thumbTop "+thumbTop+" thumbBottom "+thumbBottom); break; case MotionEvent.ACTION_MOVE: // Log.d("onTouch (MySeekBar)", "Action Move"); int thumbHeight = thumb.getHeight(); int thumbWidth = thumb.getWidth(); int trackWidth = track.getWidth(); int trackHeight = track.getHeight(); // Location/size of the thumb button and track // Log.d("onTouch (NewSeekBar)","thumbHeight "+thumbHeight+" thumbWidth "+thumbWidth+" trackWidth "+trackWidth+" trackHeight "+trackHeight); int top = (int) (thumb.getTop() + event.getY() - thumbDownPosY); Log.d("onTouch (NewSeekBar)", "top " + top); // Top border if (top < marginTop) { top = marginTop; Log.d("onTouch (NewSeekBar)", "top < marginTop " + top); } else if (top >= trackHeight - thumbHeight + marginTop) { top = trackHeight - thumbHeight + marginTop; Log.d("onTouch (NewSeekBar)", "top >= trackHeight " + top); } thumbLeft = thumb.getLeft(); ; thumbTop = top; thumbRight = thumbLeft + thumbWidth; thumbBottom = top + thumbHeight; // Log.d("onTouch (MySeekBar)", // "thumbTop: "+thumbTop+" thumbBottom: "+thumbBottom); int value = getProgress(); Log.d("onTouch (NewSeekBar)", "getProgress(): " + value); // setdBText(value); // Log.d("onTouch (MySeekBar)", "value: "+value); setProgress(value); // toast.setText(String.valueOf(temp)); // toast2.setText(String.valueOf(temp)); layout1.invalidate(); break; case MotionEvent.ACTION_UP: Log.d("onTouch (MySeekBar)", "Action Up"); toast.setVisibility(View.INVISIBLE); toast2.setVisibility(View.VISIBLE); toast3.setVisibility(View.VISIBLE); touched = false; break; }// End of switch return true; }// End of onTouch }); }// End of initialize @Override protected void onDraw(Canvas canvas) { Log.d("onDraw (MySeekBar)", "onDraw"); super.onDraw(canvas); if (initialized) { thumb.layout(thumbLeft, thumbTop, thumbRight, thumbBottom); Log.d("onDraw (MySeekBar)", "thumb layout: " + thumbLeft + ", " + thumbTop + ", " + thumbRight + ", " + thumbBottom); int top = thumbTop - marginTop; int left = thumbLeft + 4; // toast.layout(left, top, left + toast.getWidth(), top + // toast.getHeight()); top = thumbTop + thumb.getHeight() / 2 - toast2.getHeight() / 2 + 1; left = thumbLeft; toast2.layout(left, top, left + toast2.getWidth(), top + toast2.getHeight()); } }// End of onDraw The XML:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:id="@+id/test_layout"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" > <com.networksound.Mixer3.NewSeekBar android:id="@+id/newSeekBar1" android:layout_width="wrap_content" android:layout_height="wrap_content" > </com.networksound.Mixer3.NewSeekBar> <com.networksound.Mixer3.NewSeekBar android:id="@+id/newSeekBar2" android:layout_width="wrap_content" android:layout_height="wrap_content" > </com.networksound.Mixer3.NewSeekBar> <com.networksound.Mixer3.MySeekBar android:id="@+id/mySeekBar1" android:layout_width="wrap_content" android:layout_height="wrap_content" > </com.networksound.Mixer3.MySeekBar> <com.networksound.Mixer3.MySeekBar android:id="@+id/mySeekBar2" android:layout_width="wrap_content" android:layout_height="wrap_content" > </com.networksound.Mixer3.MySeekBar> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <com.networksound.Mixer3.PanSeekBar android:id="@+id/panSeekBar1" android:layout_width="match_parent" android:layout_height="wrap_content" > </com.networksound.Mixer3.PanSeekBar> <com.networksound.Mixer3.PanSeekBar android:id="@+id/panSeekBar2" android:layout_width="wrap_content" android:layout_height="wrap_content" > </com.networksound.Mixer3.PanSeekBar> </LinearLayout> </LinearLayout>
-1860273 0 var app = $('#ApplicationID')[0] or
var app = $('#ApplicationID').get(0) should do the same thing as
var app = document.getElementById('ApplicationID')
-18350480 0 This seems the most we can do to get the original IP address of the client
String ipAddress = request.getHeader("X-FORWARDED-FOR"); if (ipAddress == null) { ipAddress = request.getRemoteAddr(); }
-8982416 0 How to publish Actions to Facebook Graph API with parameters in call URL To begin, Ive spent several hours looking for an answer and have come CLOSE but havent found a full answer.
So Im trying to publish actions using Facebook's Graph API and want to send parameters in the URL when initially calling it with the Facebook Javascript SDK.
Here is a call that WORKS:
function postNewAction() { passString = '&object=http://mysite.com/appnamespace/object.php'; FB.api('/me/APP_NAMESPACE:ACTION' + passString,'post', function(response) { if (!response || response.error) { alert(response.error.message); } else { alert('Post was successful! Action ID: ' + response.id); } } ); } With object.php looking like so:
<head xmlns:enemysearch="http://apps.facebook.com/APP_NAMESPACE/ns#"> <meta property="fb:app_id" content="APP_ID" /> <meta property="og:type" content="APP_NAMESPACE:object" /> <meta property="og:title" content="some title" /> <meta property="og:description" content="some description"/> <meta property="og:locale" content="en_US" /> <meta property="og:url" content="http://www.mysite.com/appnamespace/object.php"/> </head> So obviously the above will post some sort of action to Facebook that will be the same every time object.php is called.
This is not ideal for my purposes.
So I took a look at this thread and it helped but as you will see, doesnt answer everything.
So if I change object.php to include dynamically generated meta tags by using content from either GET or POST and use the Object Debugger with a matching URL format to the one provided in og:url, the debugger shows everything as working as I would expect with now warnings. Here is what the dynamically generated object.php looks like:
<?php if(count($_GET) > 0) { $userName = (int)$_GET['userName']; } else { $userName = (int)$_POST['userName']; } ?> <head xmlns:enemysearch="http://apps.facebook.com/APP_NAMESPACE/ns#"> <meta property="fb:app_id" content="APP_ID" /> <meta property="og:type" content="APP_NAMESPACE:object" /> <meta property="og:title" content=" <?php echo $userName; ?>" /> <meta property="og:description" content="Click to view more from <?php echo $userName; ?>"/> <meta property="og:locale" content="en_US" /> <meta property="og:url" content="http://mysite.com/appnamespace/object.php?userName=<?php echo $userName; ?>"/> </head> SO, what I need to know is how to send url parameters in the initial call. If I use the debugger and enter something to the effect of http://mysite.com/appnamespace/object.php?userName=Brad everything works fine and the meta tags return content with that name inside of them. However if I try to pass the same url in the Javascript Call, it returns an error saying that my meta property og:type needs to be 'APP_NAMESPACE:object' (which as you see above, is what I have) instead of 'website' (which as you can see above, is something I am not using). Here is what that broken call would look like:
function postNewAction(userName) { passString = '&object=http://mysite.com/appnamespace/object.php?userName=' + userName; FB.api('/me/APP_NAMESPACE:ACTION' + passString,'post', function(response) { if (!response || response.error) { alert(response.error.message); } else { alert('Post was successful! Action ID: ' + response.id); } } ); } To be clear, the userName variable is only for example.
Any thoughts?
-16680099 0Looks like you are missing a few jar's.
http://poi.apache.org/overview.html
You need:
poi-version-yyyymmdd.jar commons-logging.jar commons-codec.jar log4j.jar poi-ooxml-schemas-version-yyyymmdd.jar xmlbeans.jar stax-api-1.0.1.jar dom4j.jar
-8579209 0 Just quit iTunes, and disconnect - reconnect your device. Was having this issue, this manipulation solved it for me (on a Snow Leopard OSX).
-39456914 0You can fix this by uninstalling M2Crypto via pip, then installing the package python-m2crypto, and then to make sure install M2Crypto again
pip uninstall M2Crypto apt-get install python-m2crypto pip install M2Crypto This solved for me
-6330658 0 how can I replace blank value with zero in MS-AcessI have below query in Ms-Access but I want to replace Blank value with zero but I can't get proper answer. Is there any way to replace blank value in zero.
(SELECT SUM(IIF(Review.TotalPrincipalPayments,0,Review.TotalPrincipalPayments))+ SUM(IIF(Review.TotalInterestPayments,0,Review.TotalInterestPayments )) FROM tblReviewScalars as Review INNER JOIN tblReportVectors AS Report ON(Review.LoanID=Report.LoanID) WHERE Report.AP_Indicator="A" AND Report.CashFlowDate=#6/5/2011# AND Review.AsofDate=#6/5/2011# AND ( Review.CreditRating =ReviewMain.CreditRating)) AS [Cash Collected During the Period],
-8465846 0 Using datatype different Property Editor I have a class with an Integer Property which I want to change over a PropertyGrid. BUT: I don't want to use the Integer InputBox but a Dropdown List with an Enum as content. How could I do this?
-23122518 0You can use $[:] to match a literal.
Both of these would work:
$("#animation1, #animation2, #animation3").click(function() { // existing code }); or
function animate() { //existing code } $("#animation1").click(animate);
-26924886 0 Caramel how to register handlebars helper? I'm using Jaggery.js writing a web app and using caramel as the MVC framework. Caramel uses Handlebars as the render engine so that we can use any built in helpers provided by handlebars, such as {{#each}}, {{#if}}, etc.
But how can I write my custom helpers and register in caramel, so caramel can use it render in the template ?
Is there any samples regarding this ?
Thanks in advance!
-32535190 0Absurd over-generalization:
Every Traversable instance supports a horrible hack implementing reverse. There may be a cleaner or more efficient way to do this; I'm not sure.
module Rev where import Data.Traversable import Data.Foldable import Control.Monad.Trans.State.Strict import Prelude hiding (foldl) fill :: Traversable t => t b -> [a] -> t a fill = evalState . traverse go where go _ = do xs <- get put (drop 1 xs) return (head xs) reverseT :: Traversable t => t a -> t a reverseT xs = fill xs $ foldl (flip (:)) [] xs reverseAll :: (Functor f, Traversable t) => f (t a) -> f (t a) reverseAll = fmap reverseT
-10263001 0 jquery form validation using groups I have an order form, one part of the form is the address. It contains Company, Street-Address, ZIP, Town, Country with a simple jquery form validation with every field required, and ZIP validated for number. Now what I want is to group them and only have one field showing "valid address" on success, or "address wrong" on error.
This is a part of my js code:
$("#pageform").validate( { messages: { company_from: addressError, //addressError is a JS var for the error message street_from: addressError, zip_from: addressError, town_from: addressError, country_from: addressError }, groups: { from: "company_from street_from zip_from town_from country_from" }, errorPlacement: function(error, element) { if (element.attr("name") == "company_from" || element.attr("name") == "street_from" || element.attr("name") == "zip_from" || element.attr("name") == "town_from" || element.attr("name") == "country_from" ) { $("#error_from").append(error); } }, success: function(label) { var attribute = $(label[0]).attr("for"); $(".err-ok-" + attribute + " .ok").css("display", "block").css("visibility", "visible"); } } ); This is a part of the corresponding HTML code:
<input type="text" name="company_from" id="company_from" class="required default input-s8" maxlength="255" /> <input type="text" name="street_from" id="street_from" class="required default input-s8" maxlength="255" /> <input type="text" name="zip_from" id="zip_from" class="required digits default input-s8" maxlength="5" onblur="checkCalculation()" /> <input type="text" name="town_from" id="town_from" class="required default input-s8" maxlength="255" /> <!-- and a select list for the country --> You do not need to take a closer look on how I show the error and so on, my problem is, that I do not know when to show the error label and when the success label. When I enter a letter for the ZIP code, my errorPlacement function and the success function is called (and the errorPlacement first), so I guess it's always calling the success if there is at least one field correct.
Please ask if there are any questions, and I am pretty sure there are... :-)
-22523186 0Trying changing the height to high number and see if that make a difference. I have created demo project for changing and reverting the height. Hope this helps.
https://github.com/rshankras/StackOverflowUIView
-33814145 0Does this do it:
UPDATE tbl SET defaultHours = 5 WHERE ts >= CURRENT_DATE() - INTERVAL 1 MONTH AND ts < CURRENT_DATE() - INTERVAL 1 MONTH + INTERVAL 1 DAY ?
-18511614 0You could write an interface NullCheckable
public interface NullCheckable { boolean areAllPropertiesNull(); } Then each class you want to be able to check implements this interface with the appropriate method e.g.
public class Class1 implements NullCheckable { private Object property1; public Object getProperty1() { return property1; } @Override public boolean areAllPropertiesNull() { return property1 == null; } }
-30062585 0 I found the quickest solution was to create a sql database with different tables for each type( Vehicles, Lookups etc.). When I just loaded all the data in and queried with a bunch of joins it took over a minute. But by creating foreign key references, indexes and adding primary keys to the table I got it down to less than a second. So I create the query from my c# Code and get back an object that contains all the information I need from each table.
-37702259 0Can it be simply because call to rate_limit_status.json also counts? What if you do
client.search("baeza") client.search("baeza") client.search("baeza") puts Twitter::REST::Request.new(client, :get, 'https://api.twitter.com/1.1/application/rate_limit_status.json', resources: "search").perform Will it return 176?
Update - call to rate_limit_status should not affect limits, but would be interesting to see the outcome of the suggested calls anyway.
Update 2
Gem fetches only first page by default, no matter of results count. Getting next page(s) is under your control. See here - fetch_next_page is private method, called by "each" method of enumerator here - so if you start iterating over search results and pass through all first page results. When you just made a request (called search) - it only fetches first page (one query).
Also, gem sets count parameter for API search request to 100 (max allowed) if not specified by default - here for constant and here for setting it
-19292250 0The $id item is contained in an ID item. Try:
$id = $item['ID']['$id']; Edit: I am not sure why you have the nested loops. This should be enough:
foreach ($json as $key1 => $item) { $id = $item['ID']['$id']; echo gmdate("d-m-Y H:i", strtotime('+2 hours', $item['datum'])) . ' ' . $item['titel'] . ' met ID: '.$id.'<br/>'; }
-4320985 0 To fetch records based on TIME only:
WHERE TIME(FROM_UNIXTIME(your_column)) BETWEEN '01:15:00' AND '01:15:59' Regards
-23191488 0You didn't put it in Form use input hidden to post it
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <input type="number" name="vuelto"><br> <input type="hidden" name="cobro" value="<?php echo $cobro; ?>"> <input type="submit" name="submit" value="Submit Form"><br> </form> That's how you can pass cobro variable value which will be available in $_POST['cobro']
-7250184 0It turns out using floats results in rather inaccurate results on iOS. I've had much better success using doubles instead.
-37661285 0i have found out that the div container which contains the background image has only size : 100%, so maybe if i change the size of the container, but i want that the container is responsive too ... hmm anyone a idea ?
here pictures where the container is with width: 100% and withoutenter image description here
-33596622 0 java.lang.AbstractMethodError: com.mysql.jdbc.PreparedStatement.setBlob(ILjava/io/InputStream;)VI'm trying to set a BLOB in MySQL DB as below:
PreparedStatement ps=con.prepareStatement("insert into image values(?,?,?,?,?)"); ps.setString(1,firstname); ps.setString(2,lastname); ps.setString(3,address); ps.setString(4,phone); if(is!=null) { ps.setBlob(5,is); } int i=ps.executeUpdate(); The line ps.setBlob(5,is) throws the below exception:
java.lang.AbstractMethodError: com.mysql.jdbc.PreparedStatement.setBlob(ILjava/io/InputStream;)V
How it this caused and how can I solve it?
-39576785 0 Using IF EXISTS with a CTEI want to check if a CTE table has record or null. But I always get error message 'Incorrect syntax near the keyword 'IF'' for the SQL below. Now there is no matching record in ADMISSION_OUTSIDE TABLE. The result of the SQl should print 'NOT OK'. Thanks,
WITH ADMISSION_OUTSIDE AS ( ..... ..... ) IF EXISTS (SELECT * FROM ADMISSION_OUTSIDE) PRINT 'OK' ELSE PRINT 'NOT OK'
-23959623 0 Make the first function call the next one and add this to your HTML :
<input> type=button onclick="validateForm(); return false;" </input> Putting 'return false' will prevent redirection and will give time for your function to execute.
function validateForm(){ var email = document.forms["form"]["Email"].value; if(email == null || email == ""){ alert("Email must be filled out"); return false; } else redirect(); } Additionally, I'd recommend to abstain from putting any code in your HTML. It is considered a "bad practice". However, if you still want to put your code, it'll be more appropriate to put it in the form as an "onsubmit" action:
<form onsubmit="validateForm()"> If you want the function to execute when the submit button is clicked, you can just add an event listener in your script and an id to your button, like this:
var button = document.getElementById("submit"); button.onclick = function validateForm() { /*same code as above..*/ }; Hope it helps!
-32152223 0You can convert those byte array into string.
@Override public void failure(RetrofitError error) { String body = new String(error.getResponse().getBody()); System.out.println(body); }
-22786300 0 Give limited access to android app using Phonegap I have created an android app using phonegap. I want to run the app to limit its usage to only 5 times means user can open this app only for 5 times after that user will not be able to open it instead it will show a message.
How can i do this ?
-4184920 0 git cherry-pick -x: link in details instead of in summaryGiven a commit with the message "foo", i.e. with only a summary part, I do git cherry-pick -x the_commit. The result is a new commit with message
fooNow that's not good, because it is a two-line summary, which seems like a bug in git.
(cherry picked from commit eb42a6475d2c2e4fff7a1b626ce6e27eec21e886)
But how can I make git make the comment look like below without editing the comment manually?
foo-26779700 0
(cherry picked from commit eb42a6475d2c2e4fff7a1b626ce6e27eec21e886)
Make MyClass Parcelable. See example below.
public class MyClass implements Parcelable { private int mData; public int describeContents() { return 0; } public void writeToParcel(Parcel out, int flags) { out.writeInt(mData); } public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() { public MyParcelable createFromParcel(Parcel in) { return new MyParcelable(in); } public MyParcelable[] newArray(int size) { return new MyParcelable[size]; } }; private MyParcelable(Parcel in) { mData = in.readInt(); } } // Send it using ArrayList<MyClass> list; intent.putParcelableArrayListExtra("list", list);
-36689974 0 for (int i = 0; i < PersonalIdentityNumber.Count && i < PostNr.Count; i++) The best would be to create an object with all properties and create an array of these objects. Some times one of the properties can be null.
-7144816 0try Stopwatch
-30404756 1 How to pass OpenCV image to Tesseract in python?Given Python code invoking Tesseract`s C API and using ctypes library, in the Option #1 image is being loaded by Tesseract and it works fine! The problem is in the Option #2, when I try to pass image loaded by OpenCV the Tesseract returns garbage:
from ctypes import * import cv2 class API(Structure): _fields_ = [] lang = "eng" ts = cdll.LoadLibrary("c:/Tesseract-OCR/libtesseract302.dll") ts.TessBaseAPICreate.restype = POINTER(API) api = ts.TessBaseAPICreate() rc = ts.TessBaseAPIInit3(api, 'c:/Tesseract-OCR/', lang) ##### Option #1 out = ts.TessBaseAPIProcessPages(api, 'c:/Tesseract-OCR/doc/eurotext.tif', None, 0) print 'Option #1 => ' + string_at(out) ##### Option #2 #TESS_API void TESS_CALL TessBaseAPISetImage(TessBaseAPI* handle, const unsigned char* imagedata, int width, int height, # int bytes_per_pixel, int bytes_per_line); im = cv2.imread('c:/Temp/Downloads/test-slim/eurotext.jpg', cv2.COLOR_BGR2GRAY) c_ubyte_p = POINTER(c_ubyte) ##ts.TessBaseAPISetImage.argtypes = [POINTER(API), c_ubyte_p, c_int, c_int, c_int, c_int] ts.TessBaseAPISetImage(api, im.ctypes.data_as(c_ubyte_p), 800, 1024, 3, 800 * 3) out = ts.TessBaseAPIGetUTF8Text(api) print 'Option #2 => ' + string_at(out) and output is as follows:
Option #1 => The (quick) [brown] {fox} jumps! Over the $43,456.78 #90 dog & duck/goose, as 12.5% of E-mail from aspammer@website.com is spam. Der ,,schnelle� braune Fuchs springt �ber den faulen Hund. Le renard brun «rapide» saute par-dessus le chien paresseux. La volpe marrone rapida salta sopra il cane pigro. El zorro marrén répido salta sobre el perro perezoso. A raposa marrom rzipida salta sobre o c�o preguicoso.
Option #2 => 7?:5:*:>\—‘- ;2—;i3E:?:;i3".i: ii‘; 3;’ f-ié%:::’::;?:=«’:: =£<:7‘i§5.< :—'\—;:=é:’—..=.:a,';2’:3‘:3_3:l.':—‘:—:£€:-_’:§3;;%§%ai5~«:é::3%ia»€E:
Remarks:
Any ideas how to pass OpenCV image (which is numpy.ndarray) to Tesseract? Any help would be useful.
-22920020 0 Dojo ToggleButton Check Icon doesn't updateI am defining a toggle button in HTML and then updating it's checked state in JavaScript based on another toggle button.
Toggle Button: <input type="checkbox" dojoType="dijit.form.ToggleButton" iconClass="dijitCheckBoxIcon" label="Assigned Work" id="AssignedWork" >
When the app runs I want this toggle button to be un-checked.
I can successfully call the checked property like this:
Registry.byId("AssignedWork").checked = true;
However my toggle button's icon isn't updating to indicate the "Check". When my mouse cursor hovers over the toggle button the button refreshes and shows the check mark. Is there a way to get the check icon to turn on with the .checked property?
-34571556 0I solved this problem with this gem https://github.com/ralovets/valid_url
-3914280 0 Is there a way to make Netbeans file uploads not fail on a single error?Is there a way to make Netbeans's FTP uploads less error sensitive(reconnect and retry on error)?
It is simply unable to handle large amounts of files. If I upload 1000 files and there is some sort of failure at the 400th file, it will fail for the rest of the files, and it will not record the files that failed. So I will have to upload ALL the files again, even the ones that uploaded successfully on the previous attempt, but it will fail agan again and again.
-20535653 0 Resuse of Async task code in my various fileI want to create an class file for Async task operation and from creating the object of that class file i want to access these method of async task with no of different class files with different parameters.
Methods of Async task include:-
OnPreExecute()-Want to start progress dialog same for each class.
doInbackground()-Want to perform background operation(like getting data from server) means passing parameter different for each class.
onPostExecute()-Dismiss the progress dialog and update the UI differnt for each class.
Nw i m writing the async task in my every class as inner class like following:-
class loaddata extends AsyncTask<String, String, String> { @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(AddNewLineitem.this); pDialog.setMessage("Loading Data. Please wait..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { } }); pDialog.show(); } @Override protected String doInBackground(String... params) { try { List<NameValuePair> params1 = new ArrayList<NameValuePair>(); JSONObject json = jparser.makeHttpRequest(url_foralldropdowns, "GET", params1); compoment = json.getJSONArray(COMPONENT_CODE); for (int i = 1; i < compoment.length(); i++) { JSONObject c = compoment.getJSONObject(i); String code = c.getString(CODE); list_compoment.add(code); } } catch (Exception e) { e.printStackTrace(); } return null; } protected void onPostExecute(String file_url) { loadSpinnerData(); pDialog.dismiss(); } } And JSON parser class is as follows:-
public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } // function get json from url // by making HTTP POST or GET mehtod public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) { // Making HTTP request try { // check for request method if (method == "POST") { // request method is POST // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } else if (method == "GET") { // request method is GET DefaultHttpClient httpClient = new DefaultHttpClient(); String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } } And in oncreate() i call this and it works fine:-
new loaddata().execute(); Please Help yourself..Thanks in advance
-31148509 0Those are macros declarations.
Whenever you have lowByte(0x1234) in your code, it will be replaced with the right part of the macro, substituting arguments with their values, that is ((uint8_t) ((0x1234) & 0xff)).
This step is performed by the preprocessor prior to compilation.
-22944451 0You can always render some widgets in places specific to your layout using
{{ form_widget(delete_form.yourWidgetName) }} and then let Symfony complete the form with
{{ form_rest(delete_form) }}
-9611595 0 Why is += valid temporaries in standard library? When I attempt to compile the following on ideone:
class X { public: friend X& operator+=(X& x, const X& y); }; X& operator+=(X& x, const X& y) { return x; } int main() { X() += X(); } As expected, this throws a compile error, because you can't pass a temporary to a non const reference.
However, the following compiles successfully on ideone:
std::string() += std::string(); Shouldn't this error like my example above?
Edit:
If std::string() defines += as a member operation, why does it do this when such usage allows the left hand side to be a temporary? Why not define it as I have above and avoid the reference to temporary issues?
You could use sf::SoundBuffer with loadFromSamples (see the documentation).
The representation of a sound in memory is basically a large array of integers that gives the amplitude of the signal at a given time. You can provide your own array to a sf::SoundBuffer with the correct parameters, and that would give you your programmatically generated sound.
For manipulation of sound, volume etc I can't help you though, you'll have to search for the maths behind signal processing and such.
-21671606 0Like this. without the text()
$(".post-btn").html("<img src='../images/loader.gif' />");
-20941128 0 How to feed a custom ImageSource to Image in XAML One way to set an ImageSource for Image in XAML is like this:
<Image Width="75" Height="75"> <Image.Source> <BitmapImage UriSource={Binding Uri} DecodePixelWidth="75" DecodePixelHeight="75" /> <Image.Source> </Image> This code contains a nice optimization, since a potentially large bitmap will be decoded to 75x75 pixels.
I'd like to be able to replace BitmapImage with my custom class like this:
<Image Width="75" Height="75"> <Image.Source> <custom:PictureBitmap Picture={Binding Picture} Width="75" Height="75" /> <Image.Source> </Image> My application implements the Picture class, which maps to a database table. Picture class has everything I need to create an instance of BitmapImage. So PictureBitmap is essentially an adapter for the BitmapImage.
Here is how I started:
public class PictureBitmap : BitmapSource { // TODO: create Picture Dependency Property // TODO: create a BitmapImage from Picture // TODO: implement abstract methods by delegating calls to BitmapImage } Although BitmapSource is abstract, the API reference doesn't explain how to implement it.
Does anyone know how to feed a custom object to Image.Source?
My app supports Windows Phone Mango (7.5) and up.
Thanks!
-39157382 0I've written spoiler BBCodes for forums before; the concept is essentially the same, so flip them and you get:
<span> <div onclick="var s=this.parentNode.querySelector('button');s.style.display=s.style.display==''?'none':''"> <!-- put stuff here --> </div> <button type="button" style="display:none"><!-- put other stuff here --></button> </span>
-19345405 0 A jdbc statement is one single sql instruction.
Here you try to run multiple sql instructions in one statement. You must split your sql on ; and create an execute one statement for each instruction.
From official doc:
-39399353 0A Statement is an interface that represents a SQL statement.
Call the function and save the result in a variable:
$result = GetProductsByCategory($categoryID); then inside the function:
$productsResult = $conn->query($sql); return $productsResult; then your while loop should use this returned result (i.e., $result):
while ($row = $result->fetch_assoc()) { ... }
-35717158 0 I would recommend this
#element { display: table; /* IE8+ and all other modern browsers */ }
-19394325 0 Observations,
Count_List() should count each element on list, your version only counts starting at the second item on the list. And it should always return an int,
int Count_List(Library *Head) { int count = 0; Library *Tmp = Head; if(!Tmp) return(count); while(Tmp != NULL) { count++; Tmp = Tmp->next; } return(count); } Inside Read_File() you call Create_List(Entry,Head), but your function signature for Create_List(Head,Entry); which do you intend? Probably (Head,Entry). Use fgets and sscanf to Read_File,
Library * Read_File(FILE *fp) { Library *Head, *Entry; Head = Entry = NULL; char genre[100], band[100], album[100]; float rating; char line[100]; while(fgets(line,sizeof(line),fp) { sscanf(line,"%s %s %s %f", genre, band, album, &rating); Entry = Create_Album(genre, band, album, rating); Head = Create_List(Head,Entry); } return Head; } Looking at Create_List(), you seem to be implementing the List as a stack (push Entry onto head of list),
Library * Create_List(Library *Head, Library *Entry) { if(!Head) return Entry; Entry->next = Head; return Entry; } Create_Album() needs to check for successful malloc before assigning values to member variables,
Library *Entry=NULL; if( !(Entry=(Library*)malloc(sizeof(Library))) ) { printf("error creating album\n");fflush(stdout); return Entry; } Speaking of Library struct, you declare the members genre, band, album as pointers, but you need space to copy memory, example,
typedef struct library { char genre[50]; char band[50]; char album[50]; float rating; struct library *next; }Library; My suggestion would be to build constructor and destructor functions LibraryNew, LibraryDel.
Check for (argc<2) arguments (your message says not enough, instead of need 2,
if(argc < 2) { printf("Not enough arguments.\n"); return 0; } And that fixes the biggest problems,
./library music.x 2 line:Rock Antrax Party 1.2 Rock,Antrax,Party,1.200000 Rock,Antrax,Party,1.200000 added: Rock,Antrax,Party,1.200000 Rock Antrax Party 1.20 Rock Antrax Party 1.20 Which genre would you like to delete?
-23339553 0 //try this way, hope this will help you... String value = "5571.329849243164"; Toast.makeText(MyActivity.this,""+Math.round(Double.parseDouble(value)),Toast.LENGTH_SHORT).show();
-12559954 0 With Java 7, it's as simple as:
final String EoL = System.getProperty("line.separator"); List<String> lines = Files.readAllLines(Paths.get(fileName), Charset.defaultCharset()); StringBuilder sb = new StringBuilder(); for (String line : lines) { sb.append(line).append(EoL); } final String content = sb.toString(); However, it does havea few minor caveats (like handling files that does not fit into the memory).
I would suggest taking a look on corresponding section in the official Java tutorial (that's also the case if you have a prior Java).
As others pointed out, you might find sime 3rd party libraries useful (like Apache commons I/O or Guava).
-15271743 0Try :
NSMutableArray *first=[NSMutableArray arrayWithArray:@[@"1",@"2",@"3",@"4",@"5",@"6"]]; NSMutableArray *second=[NSMutableArray arrayWithArray:@[@"2",@"4",@"6",@"8",@"0",@"12"]]; for (id obj in second) { if (![first containsObject:obj]) { [first addObject:obj]; } } NSLog(@"%@",first); EDIT:
NSMutableArray *first=[NSMutableArray arrayWithArray:@[@"1",@"2",@"3",@"4",@"5",@"6"]]; NSMutableArray *second=[NSMutableArray arrayWithArray:@[@"2",@"4",@"6",@"8",@"0",@"12"]]; NSMutableOrderedSet *firstSet=[NSMutableOrderedSet orderedSetWithArray:first]; NSOrderedSet *secondSet=[NSOrderedSet orderedSetWithArray:second]; [firstSet unionOrderedSet:secondSet]; first=[[firstSet array] mutableCopy]; NSLog(@"%@",first); *Credit goes to Mark Kryzhanouski
-14555399 0 How do I handle the timezones for every Chat messageI am creating a web chat application using ASP.NET. I have got the chat system to work as messages are sent and relayed back to the clients. But there was something I noticed but never thought it would be a problem. I am from England and the chat application is sitting on servers in America and noticed when the message displayed the time, the times were situated in American time zones. How would I go about setting the timezones that will correspond to the user's timezone.
-35956306 0Add a parentheses after the stored procedure name, with an equal amount of question marks to match the amount of parameters you wish you fill in.
Eg.
{call MyProc(?,?,?)}
-35901074 0 Here is a working version with some changes from your original code. As pointed out in the other answer, there are a few errors in your code. In addition, I changed textOutput to htmlOutput. In server.R, I put all code inside the observeEvent environment.
In general, your method in your R script needs to return something suitable for process in server.R. For example, in this case, it returns a string, which server.R renders as text, and ui.R in turn renders as HTML.
Any variable/data that is accessible in server.R (including any files that it source) can be displayed in the ui. What you need is (1) a suitable render method to render this data in server.R (2) a suitable output container to hold the output display in ui.R
ui.R
library(shiny) shinyUI(fluidPage( headerPanel("Inputting from Interface to Script"), sidebarPanel( #'a' input numericInput(inputId = "a", label = h4("Enter a:"), value = 3), numericInput(inputId = "b", label = h4("Enter b:"), value = 4), actionButton(inputId = "input_action", label = "Show Inputs")), mainPanel( h2("Input Elements"), htmlOutput("td")), # use dataTableOuput to display the result of renderDataTable. Just like the render methods, there are many output methods available for different kind of outputs. See Shiny documentation. dataTableOutput("table") )) server.R
library(shiny) source("mathops.R") shinyServer(function(input, output) { observeEvent(input$input_action, { a = input$a b = input$b output$td <- renderText({ mathops(a,b) }) }) # Use renderDataTable to convert mat2 to a displayable object. There are many other render methods for different kind of data and output, you can find them in Shiny documentation output$table <- renderDataTable(data.frame(mat2)) }) mathops.R
mathops <- function(a,b) { return(paste0("Addition of two number is: ", a+b, br(), "Multiplication of two number is: ", a*b)) } mat1 <- matrix(sample(1:16), ncol=4) mat2 <- matrix(sample(1:25), ncol=5)
-40688288 0 So after two days of research I cant find a proper solution to this issue i managed to bypass it by setting the cell frame in layoutAttributesForElementsInRect like this:
UICollectionViewCell* cell = [self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:[attributesForElementsInRect indexOfObject:attributes] inSection:0]]; if (!CGRectEqualToRect(cell.frame, refAttributes.frame)) cell.frame = refAttributes.frame; this is the complete function
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect { NSArray* attributesForElementsInRect = [super layoutAttributesForElementsInRect:rect]; NSMutableArray* newAttributesForElementsInRect = [[NSMutableArray alloc] init]; // use a value to keep track of left margin CGFloat leftMargin = 0.0; for (id attributes in attributesForElementsInRect) { UICollectionViewLayoutAttributes* refAttributes = attributes; // assign value if next row if (refAttributes.frame.origin.x == self.sectionInset.left) { leftMargin = self.sectionInset.left; } else { // set x position of attributes to current margin CGRect newLeftAlignedFrame = refAttributes.frame; newLeftAlignedFrame.origin.x = leftMargin; refAttributes.frame = newLeftAlignedFrame; } // calculate new value for current margin leftMargin += refAttributes.frame.size.width + 8; [newAttributesForElementsInRect addObject:refAttributes]; UICollectionViewCell* cell = [self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:[attributesForElementsInRect indexOfObject:attributes] inSection:0]]; if (!CGRectEqualToRect(cell.frame, refAttributes.frame)) cell.frame = refAttributes.frame; } } Hope this will help somebody or someone have a better solution
-24465190 0 NSDictionary loading a NSURL with URLByResolvingBookmarkDataI'm trying right now the Bookmark Data solution and I retraive a NSURL but it doen't work.The NSURL is correctly formatted but when i use it to create a dictionary or a string these are nil. The code I'm using is this:
- (NSData *)bookmarkFromURL:(NSURL *)url { NSError *error = nil; NSData *bookmark = [url bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope includingResourceValuesForKeys:NULL relativeToURL:NULL error:&error]; if (error) { NSLog(@"Error creating bookmark for URL (%@): %@", url, error); [NSApp presentError:error]; } return bookmark; } - (NSURL *)urlFromBookmark:(NSData *)bookmark { NSURL *url = [NSURL URLByResolvingBookmarkData:bookmark options:NSURLBookmarkResolutionWithSecurityScope relativeToURL:NULL bookmarkDataIsStale:NO error:NULL]; return url; }
-38353975 0 Would you be okay using something like this? It also helps to have more views on Youtube.
#laptop-panel { position: relative; padding-top: 25px; padding-bottom: 67.5%; height: 0; } #laptop-panel iframe { box-sizing: border-box; background: url(http://176.32.230.43/testdigitalmarketingmentor.co.uk/wp-content/uploads/2016/07/laptop-1000x728-trans.png) center center no-repeat; background-size: contain; padding: 11.7% 17.9% 15.4%; position: absolute; top: 0; left: 0; width: 100%; height: 100%; } <div id="laptop-panel"> <iframe src="https://www.youtube.com/embed/BhEWkcyXYwg?rel=0&controls=0&showinfo=0" frameborder="0" allowfullscreen></iframe> </div> Happy coding!
-36351677 0Ok I don't know for your error but you're handling exception the wrong way. Here is how you should do it (not to mention the SQL injection here) :
Try ' Your code here Catch e as Exception MsgBox.show(e.Message, "An Error occured") End Try NB : I post this here because it's too lon g for a comment...
-362296 0Edited after reading Frans Bouma's answer, since my answer has been accepted and therefore moved to the top. Thanks, Frans.
GUIDs do make a good unique value, however due to their complex nature they're not really human-readable, which can make support difficult. If you're going to use GUIDs you might want to consider doing some performance analysis on bulk data operations before you make your choice. Take into account that if your primary key is "clustered" then GUIDs are not appropriate.
This is because a clustered index causes the rows to be physically re-ordered in the table on inserts/updates. Since GUIDs are random, every insert would require actual rows in the table to be moved to make way for the new row.
Personally I like to have two "keys" on my data:
1) Primary key
Unique, numeric values with a clustered primary key. This is my system's internal ID for each row, and is used to uniquely identify a row and in foreign keys.
Identity can cause trouble if you're using database replication (SQL Server will add a "rowguid" column automatically for merge-replicated tables) because the identity seed is maintained per server instance, and you'd get duplicates.
2) External Key/External ID/Business ID
Often it is also preferable to have the additional concept of an "external ID". This is often a character field with a unique constraint (possibly including another column e.g. customer identifier).
This would be the value used by external interfaces and would be exposed to customers (who do not recognise your internal values). This "business ID" allows customers to refer to your data using values that mean something to them.
-39191502 0 php links added to codeThis code is from view-source in Chrome:
<div class='pedSpouse'>Relation med <a class='familylink' file='157' pers='24351162'><strong>KARL EMRIK Jakobsson</strong> f. 1897</div></div><div> <img id='pedMore' src='cmn/prg/pics/hpil.png'></div></div></div> In inspect the img is embedded within a copy of the previous a tag:
<div><a class='familylink' file='157' pers='24351162'><img id='pedMore' src='cmn/prg/pics/hpil.png'></div> The same thing occurs in two other places. With other data the code is as expected.
Same thing happens in Edge. I have no idea where the extra code comes from.
-20955706 0 JCL ICEMAN how many sort files are needed?I am working with JCL and there is what is called an ICEMAN which is which is invoked when the IBM SORT utility DFSORT is used. DFSORT can be used to SORT, COPY or MERGE files, amongst other things. In the example below there the output is from a SORT. My question is how many sortwork (//SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,30)) files are needed. They seem to me to always vary in number when I see them in JCL. Is there a formula for this to figure the size of how many SORTWKnns are needed?
JCL Code:
//STEP5 EXEC PGM=ICEMAN,COND=(4,LT) //SYSOUT DD SYSOUT=1 //SYSIN DD DSN=CDP.PARMLIB(cardnumberhere),DISP=SHR //SORTIN DD DSN=filename,DISP=SHR //SORTOUT DD DSN=filename,DISP=(OLD,KEEP), // DCB=(LRECL=5000,RECFM=FB), // SPACE=(CYL,30) //SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,30) //SORTWK02 DD UNIT=SYSDA,SPACE=(CYL,30) //SORTWK03 DD UNIT=SYSDA,SPACE=(CYL,30) //SORTWK04 DD UNIT=SYSDA,SPACE=(CYL,30)
-38000800 0 NodeJS, Passport & Passport-Local So I'm running into an issue authenticating using a local strategy. If I pass invalid credentials or anything unsuccessful, I get the appropriate error. However, if they authentication is successful, then I'm presented with a 404 error.
I've dug around, and the best idea I ran across was dropping the session storage (which is where it seems to be happening, while serializing the user). Anyone encounter an issue like this?
Here's some of the code, if you need any other sections of code, let me know I'll gladly provide it.
My Passport configuration:
var passport = require('passport'), User = require('mongoose').model('User'); module.exports = function () { passport.serializeUser(function (user, done) { done(null, user.id); }); passport.deserializeUser(function (id, done) { User.findOne({ _id: id }, '-password -salt -__v', function (err, user) { done(err, user); }); }); require('./strategies/local')(); }; My Local Strategy configuration:
var passport = require('passport'), LocalStrategy = require('passport-local').Strategy, User = require('mongoose').model('User'); module.exports = function () { passport.use(new LocalStrategy({ usernameField: 'email' }, function (email, password, done) { User.findOne({email: email}, function (err, user) { if (err) { return done(err); } if(!user || !user.active || !user.authenticate(password)) { return done(null, false, { message: 'Authentication Failed'}); } return done(null, user); }); })); }; All other methods work, I can query the DB to find the user, I have stepped through matching the hashed password with the provided password, it all seems to happen fine and I get a user at the end of the LocalStrategy (I make it to the final done(null, user). In the serializeUser() done(null, user.id) something happens. I've tried stepping through it, but what I end up getting into seems fairly obfuscated (or I'm too dumb to understand it) so I can't tell what's actually happening.
You can't directly add c, c++ or any other natively compiled code into a J2EE application. You need first to create a JNI wrapper over these libraries and then add them to the Java application.
-41058819 0 Photography or Continue EngineeringI'am a student of mechanical engineering,2 year in diploma.After 2 year I realize I'am not interested in engineering I love to capture nature photo I want to became photographer should I leave diploma and start photography course
-6413593 0None of those are even remotely good ideas, although the first one is passable with some modifications. reinterpret_cast doesn't work the way you think it does, and I'm not sure what exactly you're trying to achieve with placement new. Store a smart pointer of some sort in the first one to avoid the obvious issues with lifetime, and the first option isn't bad.
There is a fourth option: just store the data in a struct, and provide whatever encapsulated access you desire.
struct data { data(int i_) : i(i_) { } int i; }; struct s { s(int i_) : i(i_) { } data i; }; Rereading your question, it appears as though maybe your intent is for this struct to be an internal detail of some larger object. In that case, the lifetime issues with the first solution are likely taken care of, so storing a raw pointer is less of a bad idea. Absent additional details, though, I still recommend the fourth option.
-14474378 0It is bad practice to use null as id for your question I would use something like this
select * from post p1 where not exists (select 1 from comment c1 where c1.post_id = p1.id) union select * from post p2 where exists (select 1 from comment c1 where c1.post_id = p1.id and c2.user_id <> 124)
-5837033 0 Your logic seams correct to me. But I wonder about a possible problem with registering for a UIKeyboardWillHideNotification every time your viewWillAppear. Try to register only once in viewDidLoad and unsubscribe in dealloc. I am thinking that maybe when you register again after you dismiss the modal view the Notification Center sends you an old notification. If you register once for a notification you will not get it more then it is posted.
I'm thinking that since window.location is a host object, it does not obey "native" JS object semantics, and that's why you're having problems doing the same thing for location as you did with foo.
http://jibbering.com/faq/#nativeObject
-34280807 0 My executable ruby gems don't work as expectedI followed this tutorial http://guides.rubygems.org/make-your-own-gem to figure out how to create ruby gems but I'm having trouble figuring out how to create an executable.
I originally thought I was making a mistake in my own code but the actual gem created with the tutorial itself doesn't seem to work as I expected. So I'll base my question around the actual gem from the tutorial itself.
If you bundle the exact gem from the tutorial (the gem is named hola) into a rails application and try to use the executable command hola, all you get are error messages:
$ rails hola spanish # => Error: Command 'hola' not recognized $ ruby hola spanish # => ruby: No such file or directory -- hola (LoadError) $ hola spanish # => -bash: hola: command not found Even if I attempt to execute the command this way it doesn't seem to work:
$ ruby -Ilib ./bin/hola spanish # => ruby: No such file or directory -- ./bin/hola (LoadError) The only time this seems to execute anything is when I'm inside the actual gem directory recreated by hand in the tutorial and type this:
$ ruby -Ilib ./bin/hola spanish # => hola mundo But this is useless because the whole point of creating an executable is to be able to execute it within an actual project not the gem directory (ie: someone downloading your gem and being able to use it with a single executable keyword, like rake routes which then does something).
Can I bundle the hola gem from this official rubygems.org tutorial and use it as an executable in the way I was expecting to execute it, like this:
$ hola spanish # => hola mundo If this is possible, how is it done?
-16978547 0There are a few of things I can see to improve this
== true's its basically comparing a boolean against a booleanI believe instead of the j variable you can just increment i but I've not tested this
if (FoundMatch) return true; recently i have read some about pure virtual function concept in c++ and i wonder, given following code:
class First { public: virtual void init() = 0; protected: bool initialized; }; class Second : public First { public: void init() { ((*someting*) ? (initialized=true) : (initialized=false)); }; if creator of First class wanted to ensure the implementation of init() MUST set initialized variable either true or false how can they do that? Is there an option to enforce implementation of pure virtual function to set any variable inherited from base class?
If you are using Chrome, you should use the "Timeline" to record the memory usage. Launch the timeline, then wait for the page to refresh a few times, and then stop the timeline and have a look at the results. If you see the line keeping increasing, that means your objects in memory (or the DOM nodes) are never released and garbage collected.
I have never used document.open/write myself so I do not know if that can cause issues with garbage collection, but I suspect it does.
If your detect clearly a memory lak using the Timeline, then open the "Profiles" tab and take a Heat snapshot before and after a page reload, then use "comparison" to see what have changed and how much bigger your memory impact is. If for instance your old compiled code (or obejct references) is still there, plus the new one, then it explains your leak.
-13300071 0You should not place the outlet in the Application Delegate. Your app should contain a root view controller (created automatically if you're using a single view application template), which should handle anything related to the application's initial view. Once you have one, open the storyboard in the editor. Open an assistant editor using the buttons along the top, and use the drop-down menu at the top of the assistant editor to open up the header file of the controller. Select the scroll view, and control-drag from it into the controller's interface. Xcode will prompt you to make an outlet, allowing you to change the name. Let's use scrollView for the name. Select weak for the memory management, since it's already being retained by its superview. Xcode should automatically synthesize accessors, and now you can access the property using self.scrollView from within the controller's instance methods. Alternatively, you can select the scroll view and set its tag in the attributes inspector to any unique number, like 4. Then, you can use [self.view viewWithTag:4] to get a reference to it.
I have an EditText area that is not showing due to the keyboard covering it when the focus is on the EditText area. What I want to do is use a button to call an activity that will display a editable text area that overlays the main display and returns the value to the main activity which stores it in a separate class variable.
I added the activity to the main manifest xml.
I added an onClickListener to a button.
Here is some code:
TextEntryActivity class:
public class TextEntryActivity extends Activity{ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.text_entry); EditText edit = (EditText)findViewById(R.id.editable); getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, WindowManager.LayoutParams.FLAG_BLUR_BEHIND); } }
I have a separate XML file for the layout of the blurr.
Originally I had an onClickListerner for an onSave button that stored all the info:
private View.OnClickListener onSave = new View.OnClickListener() { @Override public void onClick(View v) { Log.d(DEB_TAG, "INSIDE ONCLICK"); mCurrent = new Restaurant(); mCurrent.setName(mName.getText().toString()); mCurrent.setAddr(mAddr.getText().toString()); mCurrent.setDate(mDateDisplay.getText().toString()); mCurrent.setNotes(mNotes.getText().toString()); switch (mTypes.getCheckedRadioButtonId()){ case R.id.fast_food: mCurrent.setType("fast_food"); break;......... The new activity is to provide a different view to add a "note"
Does this make sense? I am fairly new to this and know what I want to do in my head, but describing it can be a challenge.
-26790364 0In C++, there is no type "string". Try to use container class std::string with <string> header.
change .profileList to this:
.profileList { display: inline-block; width: 50%; vertical-align:top; } when you use inline-block, you need to give it the desired vertical align, since the default is baseline
Using matplotlib to export to TIFF will use PIL anyway. As far as I know, matplotlib has native support only for PNG, and uses PIL to convert to other file formats. So when you are using matplotlib to export to TIFF, you can use PIL immediately.
-8196392 0the checkbox isen't centerd it has just a width of 200px because you set the width of all input elements to 200px.
so thats why you should specify your input which you wana be 200px width: input[type="text"]
Example: http://jsfiddle.net/sY9Fa/1/
-6852493 0Manu,
You can use VBScript templates (thought it is a good idea to start moving off this platform anyway) in your CMS backend and 64-bit on the front end, if your front end is .NET or Java.
What you cannot do is use COM on the Front-end (even if being called from .NET) and be on 64 bit, since the Tridion COM-based linking API is 32 bit only.
The .NET linking libraries and the Java linking libraries are 32 and 64 bit compatible, but not the COM libraries.
Hope this helps
N
-19123554 0Go to config.php and replace localhost in :
$CFG->wwwroot = 'http://localhost'; With your server's external IP.
-32197731 0 Is it possible define one-to-many relation in Sql Server and just define and use one side of this relation in entity code firstIf I defined one-to-many relation foreign-key constraints in Sql Server, Is it possible just define and use it in code-first class definitions in one side? For example suppose I have Library and Book classes. Each Library can has many books but each book belong to one library.
public class Book { public Book() { } public int BookId { get; set; } public string BookName { get; set; } public virtual Library Library { get; set; } } public class Library { public Library() { } public int LibraryId { get; set; } public virtual ICollection<Book> Books { get; set; } } If I want always just use this relation from Book side,Can I don't define below line in Library class definition?
public virtual ICollection<Book> Books { get; set; }
-31419952 1 Adding 2 data frame in python pandas I want to combine 2 seperate data frame of the following shape in Python Pandas:
Df1= A B 1 1 2 2 3 4 3 5 6 Df2 = C D 1 a b 2 c d 3 e f I want to have as follows:
df = A B C D 1 1 2 a b 2 3 4 c d 3 5 6 e f I am using the following code:
dat = df1.join(df2) But problem is that, In my actual data frame there are more than 2 Million rows and for that it takes too long time and consumes huge memory.
Is there any way to do it faster and memory efficient?
Thank you in advance for helping.
-656674 0 How efficient are IFrames?If I built a page that consisted of IFrames on the order of hundreds, would this be incredibly slow, or would it behave similar to having a hundred divs?
The reason I ask is I'm looking for a nice recursive way to build a web page, where I can load sub-elements of a page as if they were complete pages of their own, with their own urls.
Thoughts? Opinions? Am I totally crazy to even be thinking it?
Edit: I just realized this would probably absolutely shred the network connection because it would have to make separate requests for each embedded frame, wouldn't it? And everything I've learned on making web pages more efficient to load is to reduce the number of http requests it needs to make.
-15759373 0 static libzip with Visual Studio 2012I am trying to build a little application using libzip library. I downloaded and compiled libzip with assistance of this article:
libzip with Visual Studio 2010
The problem is that it compiles libs dynamically, requiring both zlib.dll and zip.dll to be present. I want to compile the application completely statically, so no additional dlls will be required. does someone know how I can do that?
Thanks!
-16478908 0Its very simple,
Suppose your Boolean field name is active,
create a method named status like
def status self.active ? "Yes" : "No" end Use the status as a normal field in active admin show or index.
-35313034 0Logic depends as per your need and current DB structure. some possible solution could be
-If your path is fix, just store image name. and while creating full path join +
-If path is no fixed and storing path in DB, you can create one column more column and store unique id(any integer or alpanumeric as per logic but unique value) and use that unique value to replace path
I looked up in several places and concluded that one option for fixing this issue was to call this action only from a hyperlink and include target="_self". I can still add a ng-click attribute on the hyperlink and call code in my angular controller. This is not quite what I wanted to do because I wanted to make the call from my angular controller instead of from the hyperlink, but it will work.
The code I used is as follows:
using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm" })) { @Html.AntiForgeryToken() <ul data-ng-controller="accountController as acctCtrl"> <li><a data-ng-click="acctCtrl.logout()" href="javascript:document.getElementById('logoutForm').submit()" target="_self">Log off</a></li> </ul> }
-2806121 0 I had the package name wrong. I got it to work
-31677972 0 How to use Group By with AND in java codesTrying to get values from my table but having problem with my snytaxes
there is wrong type with "Group By" usage with "AND" any help will be apriciated
"SELECT " + C_CINSIYET + " FROM " + TABLE_COMPANYS + " WHERE " + C_MARKA + " = '" + companyMarka.getComp_marka() + "'" + " AND " + C_FIRMA + " = '" + companyMarka.getComp_name() + "' GROUP BY " + C_CINSIYET + "AND"+C_FIRMA;
-819008 0 Looks like there is no solution to this problem. The bug is aknowleged by microsoft, but its still not fixed in SSRS2008.
From the KB article (http://support.microsoft.com/kb/938943)
This behavior occurs because the Subreport control has an implicit KeepTogether property. By design, the KeepTogether property tries to keep content of a subreport on one page. Because of this behavior, the report engine creates blank space on the main report if the subreport does not fit on the same page as the main report. Then, the report engine creates the subreport on a new page.
The work around that they list is essentially 'don't use subreports'
-23545835 0This is how you inject current context as contributor parameter.
kernel.Bind<IAuthorizationService>() .To<AuthorizationService>() .WithConstructorArgument("context", x => HttpContext.Current.Request);
-12438329 0 If you're load-balancing, you're going to want the additional license to be the for the same platform as your existing license, because the point of load-balancers is to divide the work between multiple identical systems.
If you don't already have dependence on other Magento Enterprise Edition features, I would recommend against getting an Enterprise license if you are considering load-balancing. Because of the way Magento is licensed, you would require an additional Enterprise Edition license for each installation of Magento, and that includes each instance behind a load-balancer.
If you are considering expanding your infrastructure to include multiple instances of Magento, it is probably best to contact a Magento sales rep, as they will have more-specific information about licensing restrictions, and may be able to negotiate a package which suits your specific needs.
-27808752 0Working example here: http://jsfiddle.net/0vts5291/
HTML
<section id=main> <!--populate with images from array--> <p id="photos" class="product_display"> </section> JS
var imageArray = new Array(); imageArray[0]="images/coffee_prod_1.png"; imageArray[1]="images/coffee_prod_2.png"; imageArray[2]="images/coffee_prod_3.png"; imageArray[3]="images/coffee_prod_4.png"; imageArray[4]="images/coffee_prod_5.png"; imageArray[5]="images/coffee_prod_6.png"; imageArray[6]="images/coffee_prod_7.png"; //price array for products var priceArray = ["€11.90", "€12.90", "€13.90", "€14.90", "€15.90", "€16.90", "€17.90"]; function getImage() { var container = document.getElementById("photos"); for (var i = 0; i < imageArray.length; ++i) { var img = new Image(); img.src = imageArray[i]; img.className = "product_details"; img.name = priceArray[i]; img.title = priceArray[i]; container.appendChild(img); } } getImage();
-16063214 0 crystal reports - datetime group header does not show time, only date. need to display date AND time I have a crystal report that has a group that references a DATETIME column generated by a SQL Server stored procedure.
When I right-click and Format the Group, the Format Editor displays a sample of the field's output, like so:
Monday, March 01, 1999 1:23:45PM
However, when I preview the report, it only shows as such:
Monday, March 01, 1999
I need it to display/sort by the time, as well. Once again, the DB column it points to is of type DATETIME.
I am running CR 11.5 and SQL Server 2008R2.
Any help would be appreciated.
-1345050 0re.sub(r'^-+|-+$', lambda m: ' '*len(m.group()), '---ab---c-def--') Explanation: the pattern matches 1 or more leading or trailing dashes; the substitution is best performed by a callable, which receives each match object -- so m.group() is the matched substring -- and returns the string that must replace it (as many spaces as there were characters in said substring, in this case).
-12403797 0 IIS ARR (edge) cache (reverse proxy) - Upstream connection timeout issueI am looking to use the IIS Application Request Routing as a reverse proxy cache. I've looked at several different options and come to the conclusion that it fits my needs the best. However, I've run into a sort of a dead end and could really use some input from someone who has more experience with the ARR module.
I have the following setup:
The use case is such that the edge servers will receive byte range requests and as it serves the content to the end user it will cache it (first 60 sec in memory cache, then write it to the RAM disk). So far everything is working correctly but when the next end user starts requesting the same byte ranges (that are now in the cache) I'm starting so see some weird behaviour between the IIS edges and the nginx origins: Upon the first byte range request (by the second end user) the IIS server opens a connection to the nginx origin which it does not use because it already has the requested segments in the cache. Since the connection isn't being used it's eventually closed by nginx due to a timeout (60 seconds). In the mean time the second end user is still requesting segments of the file that are in the cache. Then, and this is where the issue occurs, the second end user gets to a point in the file which is not in the cache. The behaviour I would expect from IIS here (being that keep-alive is disabled) is that it would open up a new connection to the origin and start fetching the part of the file that isn't in the cache. The behaviour I'm seeing however is that IIS tries to reuse the same connection it opened up in the beginning of the request (without realizing that it's been dropped by the origin). I've used the "Failed request tracing" to verify this as well and the result of that is that the IIS doesn't get an expected reply from the origin (since the connection no longer exists) and then, in turn, returns a 502.3 to the end user.
I've verified that increasing the connection timeout on the origins will "solve" the problem, but that is not really a viable solution as I would basically have to set an infinite timeout which may cause a whole new set of problems on the origin side. Is there any way of controlling how IIS handles this upstream connection (i.e. force it to open a new connection when it actually needs data from the origin, or to have it realize that the origin closed the connection)?
-9093419 0 Accessing a variable from a file through a file that is required in said first fileI have an osCommerce-shop where I need to access a variable from inside an included php-file. For the sake of simplicity here is a short example of what I am talking about without anything related to osCommerce:
The file inside.php shows a picture and is only displayed on the homepage by being somehow required in index.php. Depending on what language has been selected it should show either picture 1 or 2. Currently only the first picture is displayed because I have no way of knowing which one should be used. Normally there is a $language_id variable which I can check if it is either 1 (english) or 2 (german). Unfortunately $language_id in inside.php is empty (or at least it looks like it) so I need a way to access the variable from index.php. Is there a way to do this without passing this variable or something like that? (Since it is a osCommerce-shop I am not sure how I could to that)
I hope what I tried to explain is somewhat understandable, if not, please ask and I'll try to clarify.
-15617144 0You either want to use union all or cross join. Use union all to get the results in two rows. Use cross join to get the results in two columns on the same row.
Here is an example for the cross join:
select sumcep, sumcepout from (SELECT SUM(tutar) as sumcep FROM cepbank WHERE tarih >= DATE(NOW()) ) t cross join (SELECT SUM(tutar) as sumcepout FROM cepbank_out WHERE tarih >= DATE(NOW()) ) t2
-11581124 0 Is there any downside to specifying a very long font stack? This is what I have:
body { font-family: Frutiger, "Frutiger Linotype", "Frutiger LT Std", Univers, Calibri, "Myriad Pro", Myriad, "DejaVu Sans Condensed", "Liberation Sans", "Nimbus Sans L", "Helvetica Neue", Helvetica, Arial, sans-serif; } That's a whopping 14 fonts! Does using long font stacks like this one have a significant effect on page load time or performance, or is it always a good idea to include as many fonts as needed?
-2740769 0The mongodb-csharp driver is about to make a huge push regarding support for typedcollections which will include full Linq support. I think you'll find that it is easy to work.
The other 2 projects are also steaming ahead. If you want .NET 4.0 support, simple-mongodb would be your best bet.
NoRM has a whole bunch of committers who are all great coders, so no problem with it except it doesn't have an official release.
-20820647 0if you executing this query from your SSMS it means this other server is a linked server. then it should be no different to execute it from SSRS.
Yes it is right you can only add one server to your data source of your dataset whether its a shared data source or embedded.
But for instance if you have a data source pointing to say Server A when you executing queries which will be pulling data from Server A and also from server B you will Use fully Qualified name for the Objects from server B and two part name from server A.
something like this ...
SELECT * FROM Schema.Table_Name A INNER JOIN [ServerNameB].DataBase.Schema.TableName B ON A.ColumnA = B.ColumnA obviously ServerB has to be a Linked Server.
I got this styles for my Android app:
<resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> <item name="android:windowBackground">@color/background_new</item> <item name="android:textColorPrimary">@color/colorAccent</item> <item name="android:textColorHint">@color/colorAccentHint</item> <!-- Customize your theme here. --> </style> <style name="MyToolBar" parent="Widget.AppCompat.ActionBar"> <!-- Support library compatibility --> <item name="android:textColorPrimary">@color/colorAccent</item> <item name="android:textColorSecondary">@color/colorAccent</item> <item name="colorControlNormal">@color/colorAccent</item> </style> <!-- Custom searchView may be used or not--> <style name="SearchViewStyle" parent="Widget.AppCompat.SearchView"> <!-- Gets rid of the search icon --> <item name="searchIcon">@null</item> <!-- Gets rid of the "underline" in the text --> <item name="queryBackground">@null</item> <!-- Gets rid of the search icon when the SearchView is expanded --> <item name="searchHintIcon">@null</item> <!-- The hint text that appears when the user has not typed anything --> <!--<item name="closeIcon">@null</item> --> </style> <style name="MyCustomTabLayout" parent="Widget.Design.TabLayout"> <item name="tabTextAppearance">@style/MyCustomTabText</item> </style> <style name="MyCustomTabText" parent="TextAppearance.Design.Tab"> <item name="android:textSize">12sp</item> </style> <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" /> <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" /> <style name="NavDrawerTextStyle" parent="Base.TextAppearance.AppCompat"> <item name="android:textSize">12sp</item> </style> <style name="MyCheckBox" parent="Theme.AppCompat.Light.NoActionBar"> <item name="colorControlNormal">@color/colorPrimaryTransparent</item> <item name="colorControlActivated">@color/colorAccent</item> </style> <style name="AppCompatAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert"> <item name="colorAccent">@color/colorAccent</item> <item name="android:textColorPrimary">@color/colorAccent</item> <item name="android:background">@color/background1</item> <item name="android:buttonStyle">@style/MyApp.BorderlessButton</item> </style> <style name="MyApp.BorderlessButton" parent="@style/Widget.AppCompat.Button.Borderless"> <item name="android:textSize">12sp</item> </style> <style name="MyRadioButton" parent="Theme.AppCompat.Light"> <item name="colorControlNormal">@color/colorAccent</item> <item name="colorControlActivated">@color/colorAccent</item> </style> Normally i have transparent background on Toolbar of NavigationDrawler menu items click.
But sometimes theme in my app changes to Holo theme , and i can figure it out when its happens , so when i press menu items in Toolbar or in NavigationDrawler their background become blue, like in Holo theme
Where i have mistake and why its happens?
-24612585 0There isn't a built-in feature to do just that, but there's something similar in ReSharper 8 - you can copy the XML-Doc ID to the clipboard, e.g. for:
namespace ConsoleApplication1 { class Program { static void Main(string[] args) { } } } Placing the caret on Main and then selecting this menu:

Will copy M:ConsoleApplication1.Program.Main(System.String[]) to the clipboard.
Hope that (somewhat) helps...
-38215852 0Use LANDINGPAGE field in the setExpressCheckout call to specify the default user interface, either Login for account login payments, or Billing for credit card form page.
Be noted that this field will not always work since the checkout layout has been redesigned, you may try with the redirection URL in this format to display the selected page:
Login checkout page (by default): https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-XXXXXXXXXX
Credit card form page: https://www.paypal.com/webapps/xoonboarding?token=EC-XXXXXXXXXX
*token=EC Token returned by setExpressCheckout call
Well, focus on this:
not re.match("c", "cat") Here re.match("c", "cat") will return the "location of the object in memory", as you said. That's something not False.
So now, not re.match("c", "cat") will result in:
not not False
which results to:
False
Of course, this kind of thinking can be applied to logical conditions too, like a condition of an if statement.
-22206267 0 How do I store an auth key in iOS/Objective-C?I'm working on an app that uses an auth key to validate the login session for many methods (like getFriends, for example). I'll be calling these methods in different view controllers to the one which manages logging in, so I need a way to store the auth_key which is returned upon login.
Should I use a global variable? Also how is this best done? Is this what the "keychain" is for? Could you provide some resources for learning how to use the keychain?
I'm a first year student so please don't assume much experience.
-2192810 0Eclipse has a VIM plugin. Eclipse runs on OS X
Also, I think the Komodo IDEs and editors have VIM bindings, but I have little experience with them. Apparently, they also run on OS X.
http://docs.activestate.com/komodo/4.4/vikeybind.html
-433153 0If you're willing to go all Unix-centric, Cygwin comes with a version of cron that can be run as a service on Windows. Then, you could use a common crontab file across your platforms. See http://www.noah.org/ssh/cygwin-crond.html.
I created the following one line solution avoiding multiple grep commands.
mysql -e "show databases;" | grep -Ev "Database|DatabaseToExclude1|DatabaseToExclude2" | xargs mysqldump --databases >mysql_dump_filename.sql The -E in grep enables extended regex support which allowed to provide different matches separated by the pipe symbol "|". More options can be added to the mysqldump command. But only before the "--databases" parameter.
Little side note, i like to define the filename for the dump like this ...
... >mysql_dump_$(hostname)_$(date +%Y-%m-%d_%H-%M).sql This will automatically ad the host name, date and time to the filename. :)
-33700249 0 Firebase Normalized Collection and Scroll not workingfirst the code
var baseRef = new $databaseFactory(); var childRegistration = baseRef.child("registrations/"); var childStudents = baseRef.child("students/"); $scope.scrollRef = new Firebase.util.Scroll(childRegistration,'registerDate'); var normRegisteredStudens = new Firebase.util.NormalizedCollection( [childStudents, "student"], [$scope.scrollRef, "registration"] ).select( "student.id", "student.avatarImg", "registration.registerDate", "registration.entryMethod" ).ref(); $scope.lastRegisteredStudents = $firebaseObject( normRegisteredStudens ); $scope.loadRegisteredStudents = function() { $scope.scrollRef.scroll.next(1); }; data structure
"registrations" : { "STD32159500" : { "entryMethod" : "web", "registerDate" : 1447425200913 }, "STD32159501" : { "entryMethod" : "web", "registerDate" : 1447430433895 } "students" : { "STD32159500" : { "avatarImg" : "students/default-avatar-male.png", "id" : "STD32159500", }, "STD32159501" : { "avatarImg" : "students/default-avatar-female.png", "id" : "STD32159501", } there is no error but i still no getting one by one registration value with the function "loadRegisteredStudents", instead of that, i get all results.
i get this on load web
STD32159500: avatarImg: "students/default-avatar-male.png" entryMethod: "web" id: "STD32159500" registerDate: 1447425200913 STD32159501: avatarImg: "students/default-avatar-female.png" entryMethod: "web" id: "STD32159501" registerDate: 1447430433895
-38879272 0 this code works, you need to Stringify your json object using JSON.stringify , and use the methode write of the object request to send the sample json object
, http = require('http') , bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); var sample = JSON.stringify({ "callback": "http://www.example.com/callback" , "total": 3 , "urls": [{ "url": "http://www.domain.com/index1.html" }, { "url": "http://www.domain.com/index2.html" }, { "url": "http://www.domain.com/index3.html" } ] }); var options = { hostname: 'localhost' , port: 80 , path: '/test/a' , method: 'POST' , headers: { 'Content-Type': 'application/json' , 'Content-Length': sample.length } }; app.get('/', function (req, res) { var r = http.request(options, (response) => { console.log(`STATUS: ${response.statusCode}`); console.log(`HEADERS: ${JSON.stringify(response.headers)}`); response.setEncoding('utf8'); response.on('data', (chunk) => { console.log(`BODY: ${chunk}`); }); response.on('end', () => { console.log('No more data in response.'); }); }); r.on('error', (e) => { console.log(`problem with request: ${e.message}`); }); r.write(sample); r.end(); res.send('ok'); }); a link for more details about http.request nodejs.org http.request(options[, callback])
-2723695 0 showing an image until content is loadedi am doing a jquery back end search of data from a DB table..until i fetch the data from the table...how do i show am image like every where its shown like searching or something like tht
I have a small doubt..My project has grown big. every where .change function is used. can i write a global code like when ever change function is called..show the image until the data is loaded???
-11443305 0If I understood correctly the purpose is to create an array with 10 "Apples" and another one with 5 "Balls"
$array = array ( array ("Apple", 10), array("Ball", 5) ); $newarray = array(); foreach($array as $key => $val){ $tmparray = null; for($i = 1; $i <= $val[1]; $i++){ $tmparray[$i] = $val[0]; } $newarray[] = $tmparray; } print_r($newarray); output:
Array ( [0] => Array ( [1] => Apple [2] => Apple [3] => Apple [4] => Apple [5] => Apple [6] => Apple [7] => Apple [8] => Apple [9] => Apple [10] => Apple ) [1] => Array ( [1] => Ball [2] => Ball [3] => Ball [4] => Ball [5] => Ball ) )
-21831268 0 This can be done with ismember:
[lia,lib]=ismember(A,A(1,:)) h=hist(lib(lib>0),1:size(A,2))
-22802293 0 hi i have done many thing in xmpp from (http://xmpp.org/xmpp-protocols/xmpp-extensions/) tutorial you can get example from bellow github links you can get many help from that
(demo links: ) https://github.com/sesharim/ios-jabber-client
https://github.com/funkyboy/Building-a-Jabber-client-for-iOS
(xmmp Project demo Link:)
https://github.com/chrisballinger/ChatSecure-iOS
i hope it will help full you..
you can get how to fetch old messages and user list and other detail from that above demo programs.
-21902019 0 Undefined index: string in (...)I need to switch on E_ALL and get the in the title mentioned warning, when I am exploding the $_GET string:
$input = explode( '/', $_GET['string'] ); Where does that come from? Is it the missing 3rd parameter (limit) for explode ? I want all entries.
Cheers
-1796617 0My compiler has wistringstream -- this is all it is:
typedef basic_istringstream<wchar_t> wistringstream;
Keep your code in a named function say - changeSize and call it in document.ready and window.resize as below:
function changeSize(){ var fontSize = parseInt($("#container").width()/4)+"px"; $("#container span").css('font-size', fontSize); } $(document).ready(function() { changeSize(); $(window).resize(changeSize); }); or just once in document.ready() as below:
$(document).ready(function() { $(window).resize(changeSize).trigger('resize'); });
-40489254 0 So, i'm finished with build.
Using Alex Gotev build and modify config.conf, prepare-build-system and build for needed configuration and latest pjsip source. Also i had to use latest libyuv from googlesource and NDK r10e.
I'm working on a University assignment, and I have to store elements in an array of the "Comparable" type. Eg:
protected Comparable storage[]; The elements that will be stored in this array are going to be either all integers, or all strings, but they're obviously created with the "Comparable" type as opposed to being created as int, or String.
What I'm having problems doing is comparing these values. At any given point, say the array is filled with "Comparable" elements that are actually integers, how can I compare them? I get that I have to use the compareTo() method, but what would the implementation look like? I've looked at the Java document online, and it has simply confused me even more.
Just to summarize, at any given point, the array might have "Comparable" type elements that are actually all integers, or all the elements will be Strings that were also made with the "Comparable" type. There's no mixing and matching of the integer and Strings in the array, it's just one or the other. I want to know how I would make the compareTo() method so that I can easily compare two elements in the array, or any two "Comparable" elements for that matter, and return say a 1, -1, or 0 if one is greater/less than the other
Would appreciate any help. I'm completely lost.
-2870546 0I agree with Gumbo, but here's how you can do it:
1.. Get the rewriterule to work in httpd.conf
As is clearly stated in the manual:
By default, mod_rewrite configuration settings from the main server context are not inherited by virtual hosts. To make the main server settings apply to virtual hosts, you must place the following directives in each section:
RewriteEngine On RewriteOptions Inherit
2.. Detect if HTTPS is on, and if it is and the is is a secure page, rewrite to ...
This can be done by looking at %{HTTP_HOST}:
RewriteCond %{HTTPS} !=on RewriteRule /jquery\.min\.js$ https://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js [NC,R=permanent] RewriteCond %{HTTPS} =on RewriteRule /jquery\.min\.js$ http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js [NC,R=permanent] You should also escape the dots and teh RewriteCond you use is unnecessary; you can do it in the RewriteRule.
3.. Each individual domain will still have it's own custom mod-rewrite rules. Which rules take precedence - global or per-domain? Do they combine? Is it ok if I have the "RewriteEngine On" directive in the global httpd.conf and then again in the vhost.conf?
It will be prepended to the virtual host's mod_rewrite configuration.
-10821762 0 Using GDB for debugging netlink communicationI have a multi-threaded application that communicates with a kernel module using netlink sockets. One of the threads in user mode application works as a server and kernel module works as a client. Roughly the kernel code is as follows:
timeout = 3500; netlink_unicast(); wait: __set_current_state(TASK_INTERRUPTIBLE); timeout = schedule_timeout(timeout); __set_current_state(TASK_RUNNING); if (!timeout) { printk(KERN_ERR "No response received\n"); return -1; } if (message_status != UPDATED) { printk(KERN_ERR "Somebody woke us up before we got a reply. Time left %d\n", timeout); __set_current_state(TASK_INTERRUPTIBLE); goto wait; } The message_status variable is updated in the netlink callback when the user mode application replies to this message. So basically the idea is to send a message and then wait at max timeout jiffies for the reply.
Now, using gdb, if I add a break point in any function that is called by netlink server thread in user mode, the break point is never hit and the kernel log is flooded with messages like
Somebody woke us up before we got a reply. Time left 3499
Somebody woke us up before we got a reply. Time left 3499
Somebody woke us up before we got a reply. Time left 3499
Somebody woke us up before we got a reply. Time left 3499
..
..
Somebody woke us up before we got a reply. Time left 3498
Until I finally get
No response received
What is causing the kernel thread to wake up from the timeout and how should I debug the user mode code?
PS: I am using 2.6.32-71.el6.x86_64 on RHEL 6.0
-32744717 0 How can I modify this to have a Google-like paging?My controller class contains
var Paged = new PaginatedList<Products>(SideBar, page ?? 0, pageSize); if (Request.IsAjaxRequest()) { return PartialView("~/Views/Shared/_Grid.cshtml", Paged); } return View(Paged); the PaginatedList is
public class PaginatedList<T> : List<T> { public int PageIndex { get; private set; } public int PageSize { get; private set; } public int TotalCount { get; private set; } public int TotalPages { get; private set; } public PaginatedList(IQueryable<T> source, int pageIndex, int pageSize) { PageIndex = pageIndex; PageSize = pageSize; TotalCount = source.Count(); TotalPages = (int)Math.Ceiling(TotalCount / (double)PageSize); this.AddRange(source.Skip(PageIndex * PageSize).Take(PageSize)); } public bool HasPreviousPage { get { return (PageIndex > 0); } } public bool HasNextPage { get { return (PageIndex + 1 < TotalPages); } } } And my view is
<div class="pagination-container"> <nav class="pagination"> <ul> @for (int i = 0; i < Model.TotalPages; i++) { <li><a href="@Url.Action("Index", "Home", new { page = i})" class="@(i == Model.PageIndex ? "current-page" : "")">@(i + 1)</a></li> } </ul> </nav> <nav class="pagination-next-prev"> <ul> @if (Model.HasPreviousPage) { <li><a href="@Url.Action("Index", "Home", new { page = (Model.PageIndex - 1) })" class="prev"></a></li> } @if (Model.HasNextPage) { <li><a href="@Url.Action("Index", "Home", new { page = (Model.PageIndex + 1) })" class="next"></a></li> } </ul> </nav> <div> Page @(Model.PageIndex + 1) of @Model.TotalPages </div> </div> One problem with the view above, is that it creates numeric pages equal to the page sizes within model. If the model has 6 pages the result is
What will happen if i have 100 Model.Pages ?
-22432515 0You can put ftplugin directory with filetype-specific settings inside .vim directory
.vim └── ftplugin └── ruby.vim └── markdown.vim And keep your settings there. The are applied when file with corresponding filetype is opened.
Also, you might need to have filetype detection(if not detected properly). You can put this to your .vimrc
autocmd BufNewFile,BufRead *.markdown,*.md,*.mdown,*.mkd,*.mkdn set ft=markdown Or, put it into ftdetect directory
.vim └── ftdetect └── markdown.vim
-9787934 0 Firewall blocking/unblocking a port I have an app installed on a server with windows 2008 R2 OS and hosted it on port 8080 (used apache tomcat for this).. I'm able to access the app through the URL..
Now, the problem is that I'm unable to access the URL (I mean app) from any other LAN connected machines.
After some exploration, I turned off the firewall of that server and I was able to access the app from other LAN connected machines..
I came to know the problem i.e Firewall is blocking that port 8080..
I can turn off the firewall, but it is not recommended right.. my requirement is to turn on the firewall and make this app accessible from any other LAN connected machine... I think I need to make that port open/something like that, but I don't have any idea regarding this.. no network admin is available as of now, so had to do it myself :( Kindly help me regarding this...
Thanks in advance!! :)
PS: I cannot download/install any other software's on that server, please suggest some way which can happen via command prompt/some settings to access that port from other LAN connected machines
-26777778 0 UIAlertView invokes the telephoneSee this GIF

And this is the code
-(void)goGuestInfo { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[@"label.change" localize] message:@"d" delegate:self cancelButtonTitle:[@"label.cancel" localize] otherButtonTitles:[@"label.name" localize], [@"label.email" localize], [@"label.phone" localize], nil]; [alertView show]; } #pragma mark - Alertview delegate -(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex { switch (buttonIndex) { case 0: break; case 1: [self performSegueWithIdentifier:HotelBookingGuestEditNameSegue sender:nil]; break; case 2: [self performSegueWithIdentifier:HotelBookingGuestEditEmailSegue sender:nil]; break; case 3: [self performSegueWithIdentifier:HotelBookingGuestEditPhoneSegue sender:nil]; break; default: break; } } It only does it when I press "name" (i.e. case 1:).
I have never experienced this before and I've used alertviews many many times. Am i missing something obvious? After I go back to the app it will do the segues as it should.
-9135181 0an activity is not finished / destroyed on back pressed.
Use
@Override public void onBackPressed() { finish(); }
-23519427 0 I finally found a solution.
the command vdir -lib $lib -prop dpnd $entity returns you something like this:
data: ENTITY E1 # Depends on: P ieee std_logic_unsigned RYmj:=TK`k=k>D@Cz`zoB3 # Depends on: P ieee std_logic_arith 4`Y?g_lldn;7UL9IiJck01 # Depends on: P std textio 5>J:;AW>W1[[dW0I6EN1Q0 # Depends on: P ieee std_logic_1164 5=aWaoGZSMWIct0i^f`XF1 # ARCHITECTURE BODY rtl # Depends on: E L2 E2 3B3>6RbjY07ohgTgj<M4r0 # Depends on: E L3 E3 5?a[d8Ikz7>zWX`U97gNE2 # Depends on: P ieee std_logic_unsigned RYMj;=TK`k=k>C@Cz`zoB3 # Depends on: P ieee std_logic_arith 7`F?g_lkdn;7UL9IiJck01 # Depends on: P std textio 5>J:;AW>w0[[dW0I6EN1Q0 # Depends on: P ieee std_logic_1164 5=aWboGZSMlIcH0i^f`XF1 # Depends on: E work E1 ;4e7E?eQ@DHPeB>5WUDQK3 P stands for package and E for Entity. So you can use regular expressions (like me in the extracting function) to extract the data you want.
proc get_dependency_list_of_entity { lib entity } { set vdir_data [ vdir -lib $lib -prop dpnd $entity ] set match [extracting $vdir_data "^ *Depends on: (.+)"] ... } ... } As I mentioned already in the question: There are ways to get the library of an entity with vdir and also with write report -tcl
It's so easy, just call DataTable.ReadXml
-2576426 0On the irony side, I am currently updating the SCSF documentation for ClickOnce deployment for .NET 4.0, and now I know exactly what the problem it.
First, you want to publish to a disk location, not directly to the webserver. So do that, and then copy the dll's you want to add to the deployment into the version folder with the application manifest (.manifest). Rename them yourself -- just add .deploy on the end.
Bring up MageUI and open the application manifest in that folder, then uncheck the box that says "add .deploy to the file names". Click "populate".
Then remove the deployment manifest from the list; it's called something like appname.application. You don't want it to be included in the manifest's list of files.
Now you can save and sign the application manifest. Then without exiting mageUI, open the deployment manifest that is in the root folder (NOT the one in the version folder). Click on "Application Reference", then click Select Manifest. Dig down to the application manifest in the version folder that you just signed and select it. Then just save and sign the deployment manifest. It puts a relative path in there, so if you modify the .application file in the version folder, it won't work right when deployed.
Now take that .application file from the root folder and copy it into the version folder (replacing the one that's there) so you have the right copy for that version in case you need it later.
Now copy the whole shebang out to the webserver. it should work.
-846650 0When doing remote development, I use screen which provides multiple virtual remote terminals available at the press of a couple of keys. This is indispensable for me. Not only does it provide virtual terminals, but your session is preserved on the server if your connection drops for any reason.
See the GNU Screen Survival Guide question for more information about getting started with screen.
I usually have one terminal open for source control operations, one for editing, one for compiling (I just have to switch to it and hit UpArrow+Enter), and one for debugging. Depending on the environment and application I'm working on, I may have more or fewer than this, but that's the general layout.
-28834992 0 setOnClickFillInIntent Error HandlingI have made an appWidget with a collection view. And in order to handle a click event on each view of the collection view, I used 'setPendingIntentTemplate' and 'setOnClickFillInIntent'. It is working fine in a normal case. It opens up the target activity by sending the intent upon click. But if an invalid uri (it is just not a valid uri for the target activity, but in syntax, it is a valid uri.) is injected to the intent for it, the widget just simply doesn't handle the click event. It doesn't throw any exception or return any error.
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(link); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); view.setOnClickFillInIntent(R.id.image, intent); Is there any way to catch this error (the click event is not being handled due to the intent with an invalid uri)? - So that, I can switch to different code to handle the situation.
-32541629 0You could do it either inside the controller itself:
public function update(Request $request) { // Get the current users IP address and add it to the request $request->merge(['ip_address' => $_SERVER['REMOTE_ADDR']]); // Validate the IP address contained inside the request $this->validate($request, [ 'ip_address' => 'required|ip' ]); } The $request->merge() method will allow you to add items to the form request, and then you can just make a simple validate request on the IP only.
Alternatively, you could move all this to it's own Request class and inject that into the method.
-36097636 0Answer can be found in the documentation for Proxy class: https://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Proxy.html
An invocation of the hashCode, equals, or toString methods declared in java.lang.Object on a proxy instance will be encoded and dispatched to the invocation handler's invoke method in the same manner as interface method invocations are encoded and dispatched, as described above. The declaring class of the Method object passed to invoke will be java.lang.Object. Other public methods of a proxy instance inherited from java.lang.Object are not overridden by a proxy class, so invocations of those methods behave like they do for instances of java.lang.Object.
Also, I think it has something to do with the fact that the toString() method has a default definition:
public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); } While getClass() (and wait(), notify() etc.) are defined as:
public final native Class<?> getClass(); So, to differentiate between which methods will not be proxied you can look fo presence of final native in the method definition.
However I would still expect the compiler to have enough information to compile the above piece of code.
No it doesn't. Because you didn't gave the compiler enough information.
You are using a raw type Wrapper in your code, in which case, all the generic type information is not available to the compiler. So, the compiler sees ArrayList<Wrapper> as just ArrayList, and that is why when you iterate over it, you'll get back Object type values and not Wrapper type.
See JLS § 4.8 - Raw Types for more details:
The type of a constructor (§8.8), instance method (§8.4, §9.4), or non-static field (§8.3) M of a raw type C that is not inherited from its superclasses or superinterfaces is the raw type that corresponds to the erasure of its type in the generic declaration corresponding to C.
Also See:
-32834646 0You can use NOT EXISTS to exclude holidays:
SELECT * FROM time_dimension ti WHERE NOT EXISTS(SELECT 1 FROM tbl_holidays WHERE startdate = ti.db_date) AND day_name IN ('Monday','Tuesday','Wednesday','Thursday','Friday');
-6064943 0 Nuget package not adding reference on custom package I created a nuspec file:
<?xml version="1.0"?> <package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"> <metadata> <id>MyPackage.dll</id> <version>3.5</version> <authors>Me</authors> <owners>Me</owners> <requireLicenseAcceptance>false</requireLicenseAcceptance> <description>The description</description> <tags>tag1</tags> </metadata> </package> In a directory with the file strucutre
- MyPackage
- Assemblies
- MyPackage.dll
- MyPackage.nuspec
I created my package using nuget.exe pack myPackage.nuspec and placed it in my local sources. I can find and install it from visual studio at which point
What am I missing?
-24027604 0Use the xhr.status property of the jqXHR.
$('form').ajaxSubmit({ success: function(res, sta, xhr, $form) { $('#result-code').text(xhr.status); $('#result-content').html(res); }, error: function(xhr) { $('#result-code').text(xhr.status); } });
-17021394 0 You can use a span element inside parapragh elements so it would look like this:
<p class="top_dr_profle"> <span class="my_doc_pic"> <img src="images/profile_img.png" /> </span> </p>
-30952715 0 Reto Koradi already mentioned copy semantics. Another thing to keep in mind is that OpenGL allows context sharing, i.e. some objects are shared between the OpenGL contexts and deleting in one context deletes it from all contexts. Objects transcending shared contexts are
among the objects not transcending shared contexts are
I have a set of Colander SchemaNodes used with Pyramid/Cornice in an API. For some querystring args, a range is passed (ie time=X-Y means a time range from X to Y where X and Y are integers representing epochs). I currently validate this with a RegEx() validator to ensure an epoch or epoch range is passed in:
class TimeOrRange(SchemaNode): schema_type = String location = "querystring" description = 'Time (or range) in epochs: ssssssssss(-ssssssssss)' validator = Regex("^[0-9]{10}\-{0,1}[0-9]{0,10}$") I then use this in a MappingSchema which is then tied to my Cornice view with @view(schema=TimedThingGet):
class TimedThingGet(MappingSchema): time = TimeOrRange(missing=drop) What I would like to do is update the return value in my TimeOrRange SchemaNode code so time in TimedThingGet is a tuple of time ranges. In other words, if time=X-Y is passed in to a TimedThingGet instance, then time=(x, y) is returned in the validated data. Similarly, if only X is passed in, then I want Y to be set to the epoch of now().
It looks like set_value() is the way to go, and here's where the problem get's some extra credit:
set_value get called before or after validation?set_value have access to the validator such that a RegEx validator which creates regex groups could then be used to set my tuple: time=(validated.match.group[1], validated.match.group[2])?First of all, for capabilities, if it's a fixed list of capabilities you're working with, you're probably better off with having a number of booleans on the roles table, e.g. can_create_projects, can_create_users, etc., which encode the abilities of each role.
Then your CanCan Ability class might have something like the following,
class Ability include CanCan::Ability def initialize(user) can(:create, Project) do |project| user.roles.any?(&:can_create_projects) end end end
-4643006 0 I have a method that adds model state to temp data. I then have a method in my base controller that checks temp data for any errors. If it has them, it adds them back to ModelState.
-26455699 0It should be a tab with the content "Testing", but the tab is empty.
What you are seeing is not that the tab is empty, but instead no tab is selected. Since you removed all existing tabs, no remaining tab can keep the selection. So when the underlying collection is changed again to add another tab, that tab does not get selected automatically. If you click on the tab though to select it, the content is still there. You can actually see this by the way the tab header looks when it’s not selected.
Further note, that all your Tabs instances share the single TestText list you created in your MainWindow. So when you change the content in any tab, you are automatically changing the content in all tabs that exist, or will exist in the future, since all instances always get the same ObservableList instance passed.
In my case what solved the problem was the folowing:
USE [master] GO CREATE DATABASE [AdventureWorks2008R2] ON ( FILENAME = 'C:\Program Files\Microsfot SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\AdventureWors2008R2_Data.mdf') FOR ATTACH_REBUILD_LOG
-11146235 0 Well, your migration obviously did not complete successfully, based on the traceback. So I would focus on figuring out why it failed, rather than working around things like the broken RAMCache which are likely a result of the migration not having run.
The traceback indicates that it broke while trying to abort the transaction...so you'll probably need to do some debugging to determine what caused it to try to abort, since that's not indicated in the logs you pasted.
-38087735 0You have to define obj.
Write something like:
var obj = document.getElementById(pCent);
At the top of load_Sim
i had download facebook skd import it in my eclipse add v4 jar file and change complier to 1.6 but yet it give me error in class FacebookAppLinkResolver
import bolts.AppLink; import bolts.AppLinkResolver; import bolts.Continuation; import bolts.Task;
above are not import
$StupidArray = "Boys, are, not, smiling, at, all,"; if (!$db->query(" SET @msg = ''; SET @Stringarray = '\' $StupidArray '\'; " ) || !$db->query(" CALL StupidProcedure (@Stringarray, @msg)") ) { echo "CALL to StupidProcedure failed:".print_r($db->errorInfo()); } else { $res = $db->query("SELECT @msg as _p_out"); $row = $res->fetch(); print_r($row['_p_out']); } I have this mysql stored procedure that should loop through an arbitrary array of strings.
CREATE PROCEDURE StupidProcedure (INOUT Stringarray VARCHAR(100), IN msg VARCHAR (100) ) BEGIN /*Table loop variable*/ DECLARE indx INT; DECLARE len INT; DECLARE valu INT; SET @indx = 0; SET @len = 0; WHILE LOCATE(',', @Stringarray , @indx + 1) > 0 DO SET @len = LOCATE(',', @Stringarray , @indx + 1) - @indx; SET @valu = SUBSTRING(@Stringarray , @indx, @len); SELECT CONCAT(@msg, @valu) INTO msg; /* For Debugging purpose*/ SET @indx = LOCATE(',', @Stringarray , @indx + @len) + 1; /*increment loop*/ END WHILE; END Now, I needed to be sure that concatenated @msg has received all data in @Stringarray after the loop. Using php, I simply did this:
$StupidArray = "Boys, are, not, smiling, at, all,"; if (!$db->query(" SET @msg = ''; SET @Stringarray = '\' $StupidArray '\'; " )) { echo "CALL to StupidProcedure failed:".print_r($db->errorInfo()); } else { $res = $db->query("SELECT @msg as _p_out"); $row = $res->fetch(); print_r($row['_p_out']); } What I got in return was all, the last is $StupidArray. What am I doing wrong? OR is it my loop that is failing?
How can I verify if dll was wrote in .net? I'm using code as below:
Assembly assembly = null; try { foreach (string fileName in Directory.GetFiles(Environment.CurrentDirectory.ToString(), "*.dll", SearchOption.TopDirectoryOnly)) { try { assembly = Assembly.LoadFrom(fileName); Console.WriteLine(fileName); } catch (Exception ex) { ... } finally { ... } } } catch (ReflectionTypeLoadException ex) { .. } When I want to load assembly = Assembly.LoadFrom(fileName) non-.net dll, an exception will appear:
Could not load file or assembly 'file:///...' or one of its dependencies. The module was expected to contain an assembly manifest.
I want to use verify in if-else clause. Can you help me?
-15219799 0 Saved State progressbar status and button click event in android listviewi have listview.in row item progressbar ,2 button and one image view when i click download button then downloading process start but when i scroll up down then application crash and how to save state in listview row item when i scroll up down?my code below:::
public class TestHopeDownload extends Activity { private ListView lstView; private ImageAdapter imageAdapter; private Handler handler = new Handler(); ArrayList<Url_Dto> list = new ArrayList<Url_Dto>(); File download; public static final int DIALOG_DOWNLOAD_THUMBNAIL_PROGRESS = 0; String strDownloaDuRL; ArrayList<HashMap<String, Object>> MyArrList = new ArrayList<HashMap<String, Object>>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_hope_download); new LoadContentFromServer().execute(); } public void ShowThumbnailData() { // ListView and imageAdapter lstView = (ListView) findViewById(R.id.listView1); lstView.setClipToPadding(false); list = DBAdpter.getUrl_Detail(); imageAdapter = new ImageAdapter(getApplicationContext()); lstView.setAdapter(imageAdapter); } public void startDownload(final int position) { Runnable runnable = new Runnable() { int Status = 0; public void run() { // String urlDownload = list.get(position).url_video; String urlDownload = MyArrList.get(position) .get("VideoPathThum").toString(); Log.v("log_tag", "urlDownload ::: " + urlDownload); int count = 0; try { URL url = new URL(urlDownload); URLConnection conexion = url.openConnection(); conexion.connect(); int lenghtOfFile = conexion.getContentLength(); Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile); InputStream input = new BufferedInputStream( url.openStream()); // Get File Name from URL String fileName = urlDownload.substring( urlDownload.lastIndexOf('/') + 1, urlDownload.length()); download = new File( Environment.getExternalStorageDirectory() + "/download/"); if (!download.exists()) { download.mkdir(); } strDownloaDuRL = download + "/" + fileName; OutputStream output = new FileOutputStream(strDownloaDuRL); byte data[] = new byte[1024]; long total = 0; while ((count = input.read(data)) != -1) { total += count; Status = (int) ((total * 100) / lenghtOfFile); output.write(data, 0, count); // Update ProgressBar handler.post(new Runnable() { public void run() { updateStatus(position, Status); } }); } output.flush(); output.close(); input.close(); } catch (Exception e) { } } }; new Thread(runnable).start(); } private void updateStatus(int index, int Status) { View v = lstView.getChildAt(index - lstView.getFirstVisiblePosition()); // Update ProgressBar ProgressBar progress = (ProgressBar) v.findViewById(R.id.progressBar); progress.setProgress(Status); // Update Text to ColStatus TextView txtStatus = (TextView) v.findViewById(R.id.ColStatus); txtStatus.setPadding(10, 0, 0, 0); txtStatus.setText("Load : " + String.valueOf(Status) + "%"); // Enabled Button View if (Status >= 100) { Button btnView = (Button) v.findViewById(R.id.btnView); btnView.setTextColor(Color.RED); btnView.setEnabled(true); } } class LoadContentFromServer extends AsyncTask<Object, Integer, Object> { protected void onPreExecute() { super.onPreExecute(); } @Override protected Object doInBackground(Object... params) { HashMap<String, Object> map; String url = "***** url******"; String result = ""; InputStream is = null; ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); // http post try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } try { BufferedReader reader = new BufferedReader( new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result = sb.toString(); } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } try { JSONObject json_obj = new JSONObject(result); JSONArray j_Arr_fn = json_obj.getJSONArray("children"); for (int i = 0; i < j_Arr_fn.length(); i++) { JSONObject json_objs = j_Arr_fn.getJSONObject(i); Url_Dto proDto = new Url_Dto(); proDto.url_video = json_objs.getString("videoUrl"); map = new HashMap<String, Object>(); map.put("VideoPathThum", proDto.url_video); MyArrList.add(map); } } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } return null; } @Override protected void onPostExecute(Object result) { ShowThumbnailData(); } } class ImageAdapter extends BaseAdapter { private Context mContext; public ImageAdapter(Context context) { mContext = context; } public int getCount() { return MyArrList.size(); } public Object getItem(int position) { return MyArrList.get(position); } public long getItemId(int position) { return position; } public View getView(final int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub LayoutInflater inflater = (LayoutInflater) mContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE); if (convertView == null) { convertView = inflater.inflate(R.layout.activity_column, null); } // ColImage ImageView imageView = (ImageView) convertView .findViewById(R.id.ColImgPath); imageView.getLayoutParams().height = 110; imageView.getLayoutParams().width = 110; imageView.setPadding(10, 10, 10, 10); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); try { imageView.setImageResource(list.get(position).images[position]); } catch (Exception e) { // When Error imageView.setImageResource(android.R.drawable.ic_menu_report_image); } // ColStatus TextView txtStatus = (TextView) convertView .findViewById(R.id.ColStatus); txtStatus.setPadding(10, 0, 0, 0); txtStatus.setText("..."); // btnDownload final Button btnDownload = (Button) convertView .findViewById(R.id.btnDownload); btnDownload.setTextColor(Color.RED); btnDownload.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Download btnDownload.setEnabled(false); btnDownload.setTextColor(Color.GRAY); startDownload(position); pbs.setDl(1); } }); // btnView Button btnView = (Button) convertView.findViewById(R.id.btnView); btnView.setEnabled(false); btnView.setTextColor(Color.GRAY); btnView.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { ViewVideoDelete(position); } }); // progressBar ProgressBar progress = (ProgressBar) convertView .findViewById(R.id.progressBar); progress.setPadding(10, 0, 0, 0); return convertView; } } public void ViewVideoDelete(int position) { String urlDownload = MyArrList.get(position).get("VideoPathThum") .toString(); String fileName = urlDownload.substring( urlDownload.lastIndexOf('/') + 1, urlDownload.length()); download = new File(Environment.getExternalStorageDirectory() + "/download/"); String strPath = download + "/" + fileName; Log.v("log_tag", "fileNameDElete :: " + strPath); File delete = new File(strPath); delete.delete(); } } then i click download button then i scroll up down then application crash .my error in below::
03-05 14:39:15.301: E/AndroidRuntime(4481): FATAL EXCEPTION: main 03-05 14:39:15.301: E/AndroidRuntime(4481): java.lang.NullPointerException 03-05 14:39:15.301: E/AndroidRuntime(4481): at com.example.testhopedownload.TestHopeDownload.updateStatus(TestHopeDownload.java:142) 03-05 14:39:15.301: E/AndroidRuntime(4481): at com.example.testhopedownload.TestHopeDownload.access$1(TestHopeDownload.java:137) 03-05 14:39:15.301: E/AndroidRuntime(4481): at com.example.testhopedownload.TestHopeDownload$1$1.run(TestHopeDownload.java:119) 03-05 14:39:15.301: E/AndroidRuntime(4481): at android.os.Handler.handleCallback(Handler.java:587) 03-05 14:39:15.301: E/AndroidRuntime(4481): at android.os.Handler.dispatchMessage(Handler.java:92) 03-05 14:39:15.301: E/AndroidRuntime(4481): at android.os.Looper.loop(Looper.java:130) 03-05 14:39:15.301: E/AndroidRuntime(4481): at android.app.ActivityThread.main(ActivityThread.java:3683) 03-05 14:39:15.301: E/AndroidRuntime(4481): at java.lang.reflect.Method.invokeNative(Native Method) 03-05 14:39:15.301: E/AndroidRuntime(4481): at java.lang.reflect.Method.invoke(Method.java:507) 03-05 14:39:15.301: E/AndroidRuntime(4481): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 03-05 14:39:15.301: E/AndroidRuntime(4481): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 03-05 14:39:15.301: E/AndroidRuntime(4481): at dalvik.system.NativeStart.main(Native Method)
-27880645 0 Normal function in Extbase controller Is it possible to write a normal function in the controller?
I want to clean up my code a bit, so I want to write some methods for repeated code segments, but I don't want to create a special class.
How is it possible to do this?
If I do a normal
private function xyz () {} I got a function not found error.
The tricky bit is getting both related records at one time:
delete a1 from a a1 where ( a1.pub_cde = 'RTF' and exists ( select 'x' from a a2 where a2.ctm_nbr = a1.ctm_nbr and a2.pub_cde = 'CTR' and a2.itg = 2 * a1.itg ) ) or ( a1.pub_cde = 'CTR' and exists ( select 'x' from a a2 where a2.ctm_nbr = a1.ctm_nbr and a2.pub_cde = 'RTF' and a2.itg * 2 = a1.itg ) );
-5698592 0 You're probably getting that error because you are calling the theme file directly
OR
because you aren't incuding the header and footer of the page.
Easy Solve:
Make sure the page loads as wanted. If you dont want to include the header and all that junk, you can load a fragment with jQuery doing something like this:
.load('wp-content/themes/theme/reloadhomeposts.php #postWrapper', function() { $(this).removeClass('loading') });
-23793046 0 Pixelate images when hovering over parent div using javascript Searching around for ways to do this, I found a couple good explanations out there, and ended up combining them. I had everything working fine when I was just doing the hover effect when mousing over the image itself, but when trying to make it work when hovering over the "profile" div seems to have caused some problems. Currently, it will sometimes also be pixelated when not over the div, so it remains somewhere between the mouseover and mouseout states.
In the HTML, I'm creating a filterable directory of people using isotope that contains a bunch of blocks like this:
<div class="item profile p-1 undergrad research"> <div class="profile-image"> <img src="img.jpg"> </div> <div class="profile-text"> <h1>Name</h1> <h2>Position</h2> <p> Email:email@gmail.com<br> Phone: 123.345.6567<br> Office: 2818 </p> </div> </div> I'm using javascript to handle the pixelation stuff right now, but to be honest I'm a lot more familiar and comfortable with Jquery, so this has been a struggle and learning experience. Below is the whole code, but I'll explain what I changed that started my issues.
Originally, "items" in setup was taking .profile-image objects, and I changed that to .profile objects so I could use the ".profile" div as the object with the mouseover event listener. At this point I introduced "block", which i switched the event listeners to from "element".
// Most of the structure taken from Noel Delgado // @pixelia_me => http://codepen.io/noeldelgado/pen/FmEBh // The actual pixelation taken from Ken Fyrstenberg Nilsen // http://jsfiddle.net/AbdiasSoftware/QznT7/ // http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/ /* ** ======================================================================= ** Animation ** ======================================================================= */ var lastTime = 0; var vendors = ['webkit', 'moz']; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function(){callback(currTime + timeToCall);}, timeToCall); lastTime = currTime + timeToCall; return id; }; if (!window.cancelAnimationFrame) window.cancelAnimationFrame = function(id) { clearTimeout(id); }; /* ** ======================================================================= ** Pixelation ** ======================================================================= */ /*============================="Setup"===============================*/ var PIXELATION = 36,//The value when hovering. Lower numbers are more pixelated, while 100 is not at all speed = 4,//How quickly it animates. play = false;//Is the animation "playing"? var items = document.querySelectorAll('.profile'),//The parent of everything. _objs = [];//Array that will be filled with our images /*===================Images Object "Class Constructor"=====================*/ var Images = function( block, element, image, canvas, context ) { this.block = block; this.element = element; this.image = image; this.canvas = canvas; this.context = context; this.pixelation = 100; } //Called by Array.prototype.slice Images.prototype.bindLoad = function() { var obj = this; this.image.onload = function() { obj.reportLoad.call(obj); }; if ( this.image.complete ) { this.image.onload(); } } //Called by Images.prototype.bindLoad Images.prototype.reportLoad = function() { var obj = this; size = (play ? v : 100) * 0.01, w = this.width * size; h = this.height * size; this.imageWidth = this.canvas.width = this.image.width; this.imageHeight = this.canvas.height = this.image.height; this.context.drawImage(this.image, 0, 0, w, h); this.context.drawImage(this.image, 0, 0, w, h, 0, 0, this.element.width, this.element.height); //Turn off image smoothing so we get the pixelated effect this.context.mozImageSmoothingEnabled = false; this.context.webkitImageSmoothingEnabled = false; this.context.imageSmoothingEnabled = false; this.block.addEventListener('mouseover', function() { obj.mouseOver(); }, false); this.block.addEventListener('mouseout', function() { obj.mouseOut(); }, false); } /*=====================Images Object MouseOver Function======================*/ Images.prototype.mouseOver = function() { var obj = this, play = true; cancelAnimationFrame( obj.idUndraw ); var draw = function() { if ( obj.pixelation <= PIXELATION ) { play = false; cancelAnimationFrame( obj.idDraw ); obj.pixelation = PIXELATION; } else { obj.pixelate( obj.imageWidth, obj.imageHeight, 0, 0 ); obj.idDraw = requestAnimationFrame( draw, obj.context ); } }; obj.idDraw = requestAnimationFrame( draw, obj.context ); } /*====================Images Object MouseOut Function==================*/ Images.prototype.mouseOut = function() { var obj = this, play = true; cancelAnimationFrame( obj.idDraw ); var undraw = function() { if ( obj.pixelation > 98 ) { //New Code play = false;//New Code cancelAnimationFrame( obj.idUndraw ); obj.pixelation = 98; } else { obj.depixelate( obj.imageWidth, obj.imageHeight, 0, 0 ); obj.idUndraw = requestAnimationFrame( undraw, obj.context ); } }; obj.idUndraw = requestAnimationFrame( undraw, obj.context ); } /*=================Images Object Pixelation Calculation===================*/ //Called by Images.prototype.pixelate & depixelate Images.prototype.setPixels = function() { size = this.pixelation * 0.01; w = this.image.width * size; h = this.image.height * size; this.context.drawImage(this.image, 0, 0, w, h); this.context.drawImage(this.canvas, 0, 0, w, h, 0, 0, this.canvas.width, this.canvas.height); } /*====================Images Object Pixelation Methods=====================*/ //Called by Images.prototype.mouseOver Images.prototype.pixelate = function() { this.pixelation -= speed; this.setPixels(); } //Called by Images.prototype.mouseOut (Line 113) Images.prototype.depixelate = function() { this.pixelation += speed; this.setPixels(); } /*=============================Create Array of images=====================*/ //It all seems to start here. Don't really know how this gets called //though unfortunately... Array.prototype.slice.call(items, 0).forEach(function(el, i) { var block = el, element = el.querySelector('.profile-image'), image = element.querySelector('img'), canvas = document.createElement('canvas'), context = canvas.getContext('2d'); element.appendChild( canvas ); _objs.push( new Images( block, element, image, canvas, context ) ); _objs[i].bindLoad(); });
-14568430 0 Caching large objects in NoSQL stores is generally not a good idea, because it is expensive in term of memory and network bandwidth. I don't think NoSQL solutions shine when it comes to storing large objects. Redis, memcached, and most other key/value stores are clearly not designed for this.
If you want to store large objects in NoSQL products, you need to cut them in small pieces, and store the pieces as independent objects. This is the approach retained by 10gen for gridfs (which is part of the standard MongoDB distribution):
See http://docs.mongodb.org/manual/applications/gridfs/
To store large objects, I would rather look at distributed filesystems such as:
These systems are scalable, highly available, and provide both file and object interfaces (you probably need an object interface). You can also refer to the following SO question to choose a distributed filesystem.
Best distributed filesystem for commodity linux storage farm
Up to you to implement a cache on top of these scalable storage solutions.
-40428530 0Sorry, no built-in support for volumes. Feel free to raise an issue here: https://github.com/spring-cloud/spring-cloud-deployer-kubernetes/issues
-14252678 0 Backbone.js per attribute rendering (multiple small views vs multiple templates per view )I have a model and a view. The view displays attributes of a model and allows the user to manipulate these attributes. The problem is that when an attribute is modified it re-renders the whole view which causes a lot of problems for me.
Example blur event on a text input saves the new input to an attribute and thus fires render. Which means that if the user clicked from that text input straight to a button on the same view that event will never fire as the first event that fires will be blur causing the whole view to re-render and thus losing the button click event.
I have two ideas:
I seem to prefer the 2. option. What do you think? What are the best practices? Is there any better way to handle this?
-21674245 0You can store a reference to the previously opened paragraph and hide it before displaying a new one. This has the advantage of being quicker if you have lots of paragraphs.
// My function to open and close the p tag var para = null var evtDelegation = function(evt){ var target = evtUtility.getTarget(evt); if(target.nodeName.toLowerCase() === 'h1'){ if(para !== null) { para.style.display = 'none'; } para = evtUtility.nextSiblings(target); para.style.display = 'block'; }; }; evtUtility.addEvent(document, 'click', evtDelegation);
-29311392 0 Here is the list of valid timezones:
http://en.wikipedia.org/wiki/List_of_tz_database_time_zones
You can use
TIME_ZONE = 'Europe/Istanbul' for UTC+02:00
-36652205 0 Take let variable out of temporal dead zoneSee this code:
<script> let {foo} = null; // TypeError </script> <script> // Here I want to assign some some value to foo </script> The first script attempts to let-declare foo via a destructuring assignment. However, null can't be destructured, so the assignment throws a TypeError.
The problem is that then the foo variable is declared but uninitialized, so if in the 2nd script I attempt to reference foo, it throws:
foo = 123; // ReferenceError: can't access lexical declaration `foo' before initialization And let variables can't be redeclared:
let foo = 123; // SyntaxError: redeclaration of let foo Is there any way to take it out of the TDZ, so that I can assign values and read them?
-1491245 0I doubt that's actually a hash. It looks like base64 to me, which is an encoding. It's a slight technicality, but encoding's can be reversed easily, hash's can't.
EDIT: Running it through a base64 decoder, it's binary data (if it is infact a base64 encoded string). I believe it is though, the '=' on the end is a giveaway, and the rest of the string conforms to base64 too.
-6025444 0As a matter of fact there is. Just return a partial view.
public ActionResult AjaxStuff() { // do whatever var model = ...; return PartialView(model); }
-32583779 0 .p_pic-1 { background-image: url(http://www.templatemo.com/templates/templatemo_406_flex/images/member1.jpg); width: 122px; height: 122px; -webkit-border-radius: 50%; -moz-border-radius: 50%; border-radius: 50%; display:block; margin: 0 auto; } .p_pic-2 { background-image: url(http://www.templatemo.com/templates/templatemo_406_flex/images/member1.jpg); width: 122px; height: 122px; -webkit-border-radius: 50%; -moz-border-radius: 50%; border-radius: 50%; display:block; margin: 0 auto; } .p_pic-3 { background-image: url(http://www.templatemo.com/templates/templatemo_406_flex/images/member1.jpg); width: 122px; height: 122px; -webkit-border-radius: 50%; -moz-border-radius: 50%; border-radius: 50%; display:block; margin: 0 auto; } .p_pic-4 { background-image: url(http://www.templatemo.com/templates/templatemo_406_flex/images/member1.jpg); width: 122px; height: 122px; -webkit-border-radius: 50%; -moz-border-radius: 50%; border-radius: 50%; display:block; margin: 0 auto; } .p-1 { float:left; width:220px; height: 100%; background: #a1a1a1; } .p-2 { float: left; width:220px; height: 100%; margin-left: 20px; background: #a1a1a1; } .p-3{ float:left; width:220px; height: 100%; margin-left: 20px; background: #a1a1a1; } .p-4 { float: left; width:220px; height: 100%; margin-left: 20px; background: #a1a1a1; } .p-pics { width: 940px; text-align:center; margin: 70px auto 0 auto; overflow: auto; } .p-name { display: block; float:left; width:100%; font-weight: bold; color: #333; font-size: 16px; } .p-description { font-weight: normal; color: #666; font-size: 16px; text-align: center; float:left; margin-top: 0; } .p_wrap { width: 100%; text-align:center; } <div class="p-pics"> <div class="p-container"> <h2 class="pa_h2">Head Text</h2> <div class="p-1"> <a class="p_pic-1" href="index.html"></a> <div class="p_wrap"> <h4 class="p-name">Some Text</h4> <p class="p-description">This is just a description, just a text, some text.</p> </div> </div> <div class="p-2"> <a class="p_pic-2" href="index.html"></a> <div class="p_wrap"> <h4 class="p-name">Some Text</h4> <p class="p-description">This is just a description, just a text, some text, text text text.</p> </div> </div> <div class="p-3"> <a class="p_pic-3" href="index.html"></a> <div class="p_wrap"> <h4 class="p-name">Some Text</h4> <p class="p-description">This is just a description, just a text, some text, text text text. Some very-very long text. Just a text, yeah. </div> </div> <div class="p-4"> <a class="p_pic-4" href="index.html"></a> <div class="p_wrap"> <h4 class="p-name">Some Text</h4> <p class="p-description">This is just a description, just a text, some text, text text text.</p> </div> </div> </div> </div> Try this, it was working fine....https://jsfiddle.net/maheswaran/eo25p0od/
-5095992 0The follows will give you the amount in $matches[2], and the currency symbol or alpha representation will always be in $matches[1] or $matches[3]
$values = array("$5.00", "€1.23", "£1,323.45", "1.23USD"); foreach($values as $val) { preg_match("/([^0-9.,]*)([0-9.,]*)([^0-9.,]*)/", $val, $matches); print_r($matches); }
-10955497 0 Adding my solution as answer, per halfer's advice: Solved this one, because I was passing the content to Zend_Pdf as a string, i should have been using Zend_Pdf::parse($new_pdf);, as it very likely says in the manual. (oops)
Further; I solved pretty much ALL of my problems with digitally signing PDFs of various versions and form constituents by moving to TCPDF, as several of the articles here suggest. A similar caveat was met with TCPDF though, when using strings, ensure that you are using TCPDF's 'writeHTMLCell' instead of 'writeHTML'. And watch for PHPs 'magic_quotes', errant whitespace, encoding, and goblins.
-12379760 0 class used differently on different occasions in csswhy do we sometimes use syntax like
.oneclass .someotherclass { } and sometimes
.oneclass.someotherclass { } notice in the second one there is no space between oneclass and someotherclass
-27267677 0Answer given by Arion is looking perfect to me. You can modify to this as per below to achieve your exact requirement
SELECT batch_id,run_count,start_date,end_date FROM ( SELECT ROW_NUMBER() OVER(PARTITION BY batch_id ORDER BY run_count DESC) AS RowNbr, batch_log.* FROM batch_log ) as batch WHERE batch.RowNbr=1
-9803907 0 According to K&R,
A.8.4 Enumeration
...
The identifiers in an enumerator list are declared as constants of type int, and may appear wherever constants are required. If no enumerations with = appear, then the values of the corresponding constants begin at 0 and increase by 1 as the declaration is read from left to right. An enumerator with = gives the associated identifier the value specified; subsequent identifiers continue the progression from the assigned value
So mes_foo=5, mes_bar=6 and mes_joe=7. You don't need to do anything at compile time to know these values. Their values are fixed.
Please go through the following code and help me out. The data from the url is getting parsed but I am unable to populate in to the list view.
public class HomeFragment extends Fragment { View rootView = null; private ListView myListView; private String[] strListView; private String[] categ; private TextView catName; private CustomAdapter myAdapter; private DownloadJson downloadJson; private int i; private AsyncTask task; private Thread thread; public HomeFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.fragment_home, container, false); myListView = (ListView) rootView.findViewById(R.id.listview); new DownloadJson().execute(); // Inflate the layout for this fragment return rootView; } This is the callCustomAdapter Function:
public void callCustomAdaper( Context context) { myAdapter = new CustomAdapter(context); myListView.setAdapter(myAdapter); myListView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Log.v("Module Item Trigger", "Module item was triggerted"); /* Fragment customMapFragmentMapFragment = new MessagesFragment(); FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.container, customMapFragmentMapFragment) .addToBackStack(null) .commit();*/ } }); } This class is json parser:
class DownloadJson extends AsyncTask { Activity context; ListView myListView; private ProgressDialog dialog = new ProgressDialog(getActivity()); public DownloadJson(Activity context, ListView myListView) { this.myListView = myListView; this.context = context; } public DownloadJson() { } @Override protected void onPreExecute() { this.dialog.setMessage("Please wait"); this.dialog.show(); } @Override protected void onCancelled() { super.onCancelled(); } @Override protected Object doInBackground(Object[] params) { String result = null; InputStream isr = null; String imageId = null; String ip = "http://ganarajsshetti.tk/mobileapp/selectjson.php/"; try { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(ip); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); isr = httpEntity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http Connection" + e.toString()); } // converting response to string try { BufferedReader br = new BufferedReader(new InputStreamReader(isr)); StringBuilder sb = new StringBuilder(); String line = null; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } isr.close(); result = sb.toString(); } catch (Exception e) { Log.e("log_tag", "Error in Converting Data" + e.toString()); } // parse JSON data try { JSONArray jsonArray = new JSONArray(result); strListView = new String[jsonArray.length()]; for (int i = 0; i < jsonArray.length(); i++) { JSONArray json_data = jsonArray.getJSONArray(i); for (int j =0; j< json_data.length();j++) { strListView[i] = json_data.getString(j); System.out.println("--------------" + json_data.getString(0)); } Log.e("ACK_tag", "DATA" + strListView[i]); } } catch (Exception e) { Log.e("log_tag", "Error in parsing Data" + e.toString()); } return null; } @Override protected void onPostExecute(Object o) { // ArrayAdapter objAdapter = new ArrayAdapter<String>(context,R.layout.list_item,R.id.Category,strListView); if (dialog.isShowing()) { dialog.dismiss(); } callCustomAdaper(context); } } This is my customAdapter which extends base adapter:
public class CustomAdapter extends BaseAdapter { private Context context; public CustomAdapter(Context context) { this.context = context; } @Override public int getCount() { return strListView.length; } @Override public Object getItem(int i) { return strListView[i]; } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View convertview, ViewGroup viewGroup) { View row= null; if(convertview == null) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); row = inflater.inflate(R.layout.list_item, viewGroup, false); } else{ row= convertview; } catName=(TextView) row.findViewById(R.id.Category); catName.setText(categ[i]); return row; } public String[] getValues() { return strListView; } } These are my Xml files:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="info.androidhive.materialdesign.activity.HomeFragment"> <ListView android:id="@+id/listview" android:layout_width="wrap_content" android:layout_height="wrap_content"> </ListView> </RelativeLayout> This is other xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="10dp" android:paddingLeft="10dp" android:paddingRight="10dp"> <TextView android:id="@+id/Category" android:layout_width="50dp" android:layout_height="50dp" android:gravity="center_horizontal" android:textStyle="bold"/> </LinearLayout> And this was the error that I am getting:
-26357362 0 Extracting string patternjava.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference at info.androidhive.materialdesign.activity.HomeFragment$CustomAdapter.getView(HomeFragment.java:248)
I have a file that looks like this:
chr1 156706559 rs8658 A C,G 370.29 PASS AC=1,1;AF=0.500,0.500;AN=2;DB;DP=19;Dels=0.00;FS=0.000;HaplotypeScore=0.0000;MLEAC=1,1;MLEAF=0.500,0.500;MQ=56.74;MQ0=0;POSITIVE_TRAIN_SITE;QD=19.49;VQSLOD=6.27;culprit=FS;EFF=3_prime_UTR_variant(MODIFIER||123|c.*123A>C|RRNAD1|protein_coding|CODING|NM_001142560.1|7) GT:AD:DP:GQ:PL 1/2:0,7,12:19:99:503,293,272,210,0,183 chr10 22839463 rs10047326 C A,T 202.29 PASS AC=1,1;AF=0.500,0.500;AN=2;DB;DP=10;Dels=0.00;FS=0.000;HaplotypeScore=0.0000;MLEAC=1,1;MLEAF=0.500,0.500;MQ=60.00;MQ0=0;POSITIVE_TRAIN_SITE;QD=20.23;VQSLOD=10.48;culprit=FS;EFF=intron_variant(MODIFIER|||c.792+125G>T|PIP4K2A|protein_coding|CODING|NM_005028.4|7) GT:AD:DP:GQ:PL 1/2:0,6,4:10:99:317,127,109,190,0,178 chr10 75673731 rs2227566 C G,T 735.29 PASS AC=1,1;AF=0.500,0.500;AN=2;DB;DP=33;Dels=0.00;FS=0.000;HaplotypeScore=0.0000;MLEAC=1,1;MLEAF=0.500,0.500;MQ=55.90;MQ0=0;QD=22.28;VQSLOD=6.01;culprit=FS;EFF=splice_region_variant(LOW|||c.630C>G|PLAU|protein_coding|CODING|NM_001145031.1|6) GT:AD:DP:GQ:PL 1/2:0,8,25:33:99:913,734,710,179,0,110 chr12 54805753 rs1922254 G C,T 404.66 PASS AC=1,1;AF=0.500,0.500;AN=2;DB;DP=18;Dels=0.00;FS=0.000;HaplotypeScore=0.0000;MLEAC=1,1;MLEAF=0.500,0.500;MQ=55.34;MQ0=0;QD=22.48;VQSLOD=5.61;culprit=FS;EFF=splice_region_variant(LOW|||c.219C>G|ITGA5|protein_coding|CODING|NM_002205.2|1) GT:AD:DP:GQ:PL 1/2:0,4,14:18:67:540,434,422,106,0,67 chr15 50150903 rs7497350 C A,T 3655.29 PASS AC=1,1;AF=0.500,0.500;AN=2;DB;DP=140;Dels=0.00;FS=0.000;HaplotypeScore=1.8136;MLEAC=1,1;MLEAF=0.500,0.500;MQ=60.00;MQ0=0;POSITIVE_TRAIN_SITE;QD=26.11;VQSLOD=10.96;culprit=FS;EFF=3_prime_UTR_variant(MODIFIER||1488|c.*1488G>T|ATP8B4|protein_coding|CODING|NM_024837.3|28) GT:AD:DP:GQ:PL 1/2:0,62,78:140:99:4121,2349,2187,1772,0,1553 chr16 11678403 rs8054918 T C,G 283.29 PASS AC=1,1;AF=0.500,0.500;AN=2;DB;DP=18;Dels=0.00;FS=0.000;HaplotypeScore=0.0000;MLEAC=1,1;MLEAF=0.500,0.500;MQ=60.00;MQ0=0;QD=15.74;VQSLOD=10.55;culprit=FS;EFF=intron_variant(MODIFIER|||c.-6+1599A>G|LITAF|protein_coding|CODING|NM_004862.3|1) GT:AD:DP:GQ:PL 1/2:0,9,9:18:99:407,181,160,226,0,208 chr16 78503259 rs2738676 G A,C 166.31 PASS AC=1,1;AF=0.500,0.500;AN=2;DB;DP=9;Dels=0.00;FS=0.000;HaplotypeScore=0.0000;MLEAC=1,1;MLEAF=0.500,0.500;MQ=60.00;MQ0=0;QD=18.48;VQSLOD=10.91;culprit=QD;EFF=intron_variant(MODIFIER|||c.717+36610G>A|WWOX|protein_coding|CODING|NM_001291997.1|7) GT:AD:DP:GQ:PL 1/2:0,3,6:9:80:279,181,172,98,0,80 chr17 4205297 rs1866174 C A,T 189.29 PASS AC=1,1;AF=0.500,0.500;AN=2;DB;DP=12;Dels=0.00;FS=0.000;HaplotypeScore=0.0000;MLEAC=1,1;MLEAF=0.500,0.500;MQ=47.61;MQ0=0;POSITIVE_TRAIN_SITE;QD=15.77;VQSLOD=3.80;culprit=MQ;EFF=intron_variant(MODIFIER|||c.149+5019G>T|UBE2G1|protein_coding|CODING|NM_003342.4|2) GT:AD:DP:GQ:PL 1/2:0,5,7:12:87:307,202,187,105,0,87 Would like to extract "EFF= ....." from each line, in the above example the output desired is
EFF=3_prime_UTR_variant EFF=intron_variant EFF=splice_region_variant the above output is for first three lines.
What I have tried.
grep -no 'EFF="[^"]*"' file.txt It doesn't work.
Kindly help
-20165275 0See the documentation of Math.log : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log
For further help you should ask your math teacher or someone who knows about algorithms ;-P
maybe you should see the part: ((b*c-a*d)/(c*c)*(Math.log(Math.abs(c*Xp+d)))) Maye you want to have the braces done like (x/(z*y)) or ((x*y)/z).
var arraySearch = function (subArray,array ) { var i = -1; return subArray.every(function (v) { if(i != -1) { i++; return (array.indexOf(v) === i) } i = array.indexOf(v); return i >= 0; }); }; var arr = [1,3,4,5,9]; console.log(arraySearch([4,5],arr))
-10815126 0 How to make black background and red color for drawing? I have been developing the application for drawing. I have following code for main activity:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); Display display = getWindow().getWindowManager().getDefaultDisplay(); mMainView = new MyView(this, display.getWidth(), display.getHeight()); setContentView(mMainView); mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setDither(true); mPaint.setColor(0xFFFF0000); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeJoin(Paint.Join.ROUND); mPaint.setStrokeCap(Paint.Cap.ROUND); mPaint.setStrokeWidth(12); mEmboss = new EmbossMaskFilter(new float[] { 1, 1, 1 }, 0.4f, 6, 3.5f); mBlur = new BlurMaskFilter(8, BlurMaskFilter.Blur.NORMAL); } And code for my custom view for drawing:
public class MyView extends View { private static final float TOUCH_TOLERANCE = 4; private static final float MINP = 0.25f; private static final float MAXP = 0.75f; private Bitmap mBitmap; private Canvas mCanvas; private Path mPath; private Paint mBitmapPaint; private float mX, mY; public MyView(Context context, int width, int height) { super(context); this.setDrawingCacheEnabled(true); mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); mCanvas = new Canvas(mBitmap); mPath = new Path(); mBitmapPaint = new Paint(Paint.DITHER_FLAG); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); } @Override protected void onDraw(Canvas canvas) { canvas.drawColor(0xFF000000); canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint); canvas.drawPath(mPath, mPaint); } public void clearView() { mBitmap.eraseColor(Color.TRANSPARENT); } public Bitmap getState() { return mBitmap; } private void touchStart(float x, float y) { mPath.reset(); mPath.moveTo(x, y); mX = x; mY = y; } private void touchMove(float x, float y) { float dx = Math.abs(x - mX); float dy = Math.abs(y - mY); if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) { mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2); mX = x; mY = y; } } private void touchUp() { mPath.lineTo(mX, mY); // commit the path to our offscreen mCanvas.drawPath(mPath, mPaint); // kill this so we don't double draw mPath.reset(); } @Override public boolean onTouchEvent(MotionEvent event) { float x = event.getX(); float y = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: touchStart(x, y); invalidate(); break; case MotionEvent.ACTION_MOVE: touchMove(x, y); invalidate(); break; case MotionEvent.ACTION_UP: touchUp(); invalidate(); break; } return true; } } So, because if I try to save resulted bitmap as jpeg file using bitmap compress then all is good, but if I try to save as png file I will get file with transparent background (white) and red picture. I need that I can save using JPEG/PNG with black background and red picture. Code for saving is good, don't worry. Thank you.
-34956492 0 using pusher npm in reactnative appI'm trying to get a basic reactnative app with chat feature going. Found a pusher npm on https://www.npmjs.com/package/pusher
Did install the module to the project with:
npm install pusher --save As soon as I add to a react component following line of code
var Pusher = require('pusher'); the xcode project stops compiling with following stack trace:
bundle: Created ReactPackager uncaught error Error: UnableToResolveError: Unable to resolve module crypto from /Users/dmitry/hacks/tentags/TenTags/node_modules/request/lib/helpers.js: Invalid directory /Users/node_modules/crypto at ResolutionRequest.js:356:15 at tryCallOne (/Users/dmitry/hacks/tentags/TenTags/node_modules/promise/lib/core.js:37:12) at /Users/dmitry/hacks/tentags/TenTags/node_modules/promise/lib/core.js:123:15 at flush (/Users/dmitry/hacks/tentags/TenTags/node_modules/asap/raw.js:50:29) at nextTickCallbackWith0Args (node.js:452:9) at process._tickCallback (node.js:381:13) See logs /var/folders/gq/zxnwqjwd75d_2rhgbzzc_0n00000gn/T/react-packager.log at SocketClient._handleMessage (SocketClient.js:139:23) at BunserBuf.<anonymous> (SocketClient.js:53:42) at emitOne (events.js:77:13) at BunserBuf.emit (events.js:169:7) at BunserBuf.process (/Users/dmitry/hacks/tentags/TenTags/node_modules/bser/index.js:289:10) at /Users/dmitry/hacks/tentags/TenTags/node_modules/bser/index.js:244:12 at nextTickCallbackWith0Args (node.js:452:9) at process._tickCallback (node.js:381:13) Command /bin/sh failed with exit code 1 What am I doing wrong? Is pusher npm only meant to work in react.js web apps? Can I not use pusher npm as is in ractnative app? I know, maybe naive questions, but I'm very new to reactnative and the whole JS, Node, npm business.
-40222894 0To overcome the "ERROR: query has no destination for result data" error you don't need dynamic SQL.
You can select into a variable directly:
select parentid into parent from account where childid = child_id; But you can simplify your function by using a recursive CTE and a SQL function. That will perform a lot better especially with a large number of levels:
create or replace function build_mp(child_id text) returns text[] language sql as $$ with recursive all_levels (childid, parentid, level) as ( select childid, parentid, 1 from account where childid = child_id union all select c.childid, c.parentid, p.level + 1 from account c join all_levels p on p.parentid = c.childid ) select array_agg(childid order by level) from all_levels; $$;
-1821049 0 JSON encoding problem in IE6 and IE7 Can someone tell me how to change this getJSON request to a .ajax call so I can set the contentType option?
$.getJSON('json/showreel.json', function(data) { //get total number of JSON objects and generate random numder var total = data.length; var randnum = Math.floor(Math.random()*total) //Loop through each of the JSON objects to check if matches random number $.each(data, function(entryIndex, entry) { if(entryIndex === randnum){ var info = '<div class="entry" style="color:' + entry['colour'] + '">'; info += entry['title'] + '<br />'; info += '<a href="' + entry['link_url'] + '">' + entry['website'] + '</a>'; info += '</div>'; $('#head-contact,#head-contact a').css('color',entry['colour']); //create new image object to preload image var img = new Image(); //once image has loaded execute this code $(img).load(function () { //$(this).css('display', 'none'); // .hide() doesn't work in Safari when the element isn't on the DOM already $(this).hide(); $('#showreel').removeClass('loading').append(this); $(this).fadeIn(3000); }).error(function () { // notify the user that the image could not be loaded }).attr('src', entry['image_src']); } $('#info').append(info); }); }); Many thanks, C
-14626552 0This is called "hoisting" SlowVariabele out of the loop.
The compiler can do it only if it can prove that the value of SlowVariabele is the same every time, and that evaluating SlowVariabele has no side-effects.
So for example consider the following code (I assume for the sake of example that accessing through a pointer is "slow" for some reason):
void foo1(int *SlowVariabele, int *result) { for (int i = 0; i < *SlowVariabele; ++i) { --*result; } } The compiler cannot (in general) hoist, because for all it knows it will be called with result == SlowVariabele, and so the value of *SlowVariabele is changing during the loop.
On the other hand:
void foo2(int *result) { int val = 12; int *SlowVariabele = &val; for (int i = 0; i < *SlowVariabele; ++i) { --*result; } } Now at least in principle, the compiler can know that val never changes in the loop, and so it can hoist. Whether it actually does so is a matter of how aggressive the optimizer is and how good its analysis of the function is, but I'd expect any serious compiler to be capable of it.
Similarly, if foo1 was called with pointers that the compiler can determine (at the call site) are non-equal, and if the call is inlined, then the compiler could hoist. That's what restrict is for:
void foo3(int *restrict SlowVariabele, int *restrict result) { for (int i = 0; i < *SlowVariabele; ++i) { --*result; } } restrict (introduced in C99) means "you must not call this function with result == SlowVariabele", and allows the compiler to hoist.
Similarly:
void foo4(int *SlowVariabele, float *result) { for (int i = 0; i < *SlowVariabele; ++i) { --*result; } } The strict aliasing rules mean that SlowVariable and result must not refer to the same location (or the program has undefined behaviour anyway), and so again the compiler can hoist.
I am having issues trying to install eclim for macOS 10.11.6.
Following instructions here, I get to the "validating requirements" screen. However, it is glitched so I cant see the error but the error is next to the "checking eclipse version".
If I continue, I can select my features and get the error
jar:file:/users/myname/Downloads/eclim_2.6.0.jar/installer.xml:321: Replace: source file /Users/myname/eclipse/java-neon/Eclipse.app/Contents/Eclipse/plugins/org.eclim_2.60/bin/eclimd doesn't exist I am sure I am just doing something wrong, but anyone have any help? I would appreciate it a lot.
-19641993 0 Anything related to audio mixers, i.e. hardware or software (virtual) devices used to mix the signals of independent audio sources together in order to produce a single audio signal out of them. Appropriate for questions about the software audio mixing applications commonly found on computers and smartphones. -12786059 0You can set a birthdate to a contact (through the Contacts app) with only a month/day. The year is then set to 1604, it's just not shown. If before you do your ABRecordSetValue(), you set the year to 1604, the birthdate will show as just "May 5" when viewing the contact in the Contacts app. It appears as though this is the way Apple specifies 'no year'. You will have to manually check the date later if you plan on showing it otherwise you will display the 1604 year.
-4565391 0It largely depends on your overall technology stack. If you're already set up with nHibernate and there's no external motivating factor (business reason, etc), then there's no true need to move over to EF4. However, if you're almost exclusively using the MS technology stack, then moving to EF4 will further that effort.
That said, Spring.NET and nHibernate have a great, mature history of interoperability, and it's tough to fix what isn't broken. I'm in the process of building up a Domain Model using POCOs with EF4 and Spring.NET and can attest there are a lot of learning opportunities and instances of "OK, how am I going to do THAT?". But it's certainly doable and while there aren't many resources out there specifically of using EF4 and Spring.NET, there is good guidance in the general realm of EF4 and DDD.
Dunno if that helped at all, but it's my two cents on the topic.
-21981408 0 sas macros for incrementing dateMy codes are:
libname " Cp/mydata" options ; %let yyyymmdd=20050210; %let offset=0; %let startrange=0; %let endrange=0; /* MACRO FOR INCREMENTING THE DATE */ %macro base(yyyymmdd=, offset=); %local date x ds; /* declare macro variables with local scope */ %let date=%sysfunc(mdy(%substr(&yyyymmdd,5,2) ,%substr(&yyyymmdd,7,2) ,%substr(&yyyymmdd,1,4))); /* convert yyyymmdd to SAS date */ %let loopout=100;/* hardcoded - number of times to check whether ds exists */ %do x=&offset %to &loopout; /* begin loop */ /* convert &date to yyyymmdd format */ %let ds=AQ.CO_%sysfunc(intnx(day,&date,&offset),yymmddn8.); %if %sysfunc(exist( &ds )) %then %do; %put &ds exists!; &ds /* write out the dataset, if it exists */ %let x=&loopout; /* exit loop */ %end; %else %do; %put &ds does not exist - checking subsequent day; %let date=&date+1; %end; %end; %mend; %macro loop(yyyymmdd=, startrange=, endrange=); %local date x ds; %let date=%sysfunc(mdy(%substr(&yyyymmdd,5,2) ,%substr(&yyyymmdd,7,2) ,%substr(&yyyymmdd,1,4))); data x; set set %base(yyyymmdd=&yyyymmdd, offset=0) /* loop through each specific dataset, checking first whether it exists.. */ %do x=&startrange %to &endrange; %let ds=AQ.CO_%sysfunc(intnx(day,&date,&x),yymmddn8.); %if %sysfunc(exist( &ds )) %then %do; &ds %end; %end; ; run; %mend; This was the error generated when I tried to run this macro.
data temp;
58 set %loop(yyyymmdd=&yyyymmdd, startrange=&startrange, 58 ! endrange=&endrange);
ERROR: File WORK.DATA.DATA does not exist.
ERROR: File WORK.X.DATA does not exist.
AQ.CO_20050210 does not exist - checking subsequent day
AQ.CO_20050211 does not exist - checking subsequent day
AQ.CO_20050212 exists!
NOTE: The system stopped processing this step because of errors.
I want help on two things:
1) Here, I'm trying to increment my date by 1 or 2 or so on if that date is not there in my original dataset. Please help to make this macro work fine.
2)I would like to have another column ie work.date in my data that will have 0 or 1(1 if the specified date yyyymmdd exist in our original data and 0 if I'm incrementing). Please make the specified changes in my macro. Thanks in advance!!
-39883988 0SPOOL is a SQLPlus command, so you can not use it in a PlSQL block dynamically.
One way could be creating at runtime a second script, dynamically built based on your query, and then run it to do the job. For example:
conn ... set serveroutput on set feedback off variable fullpath varchar2(20); variable filename varchar2(10); variable extension varchar2(5); variable sep varchar2(1); /* spool to a fixed file, that will contain your dynamic script */ spool d:\secondScript.sql begin select 'filename', 'd:\', 'txt', '|' into :filename, :fullpath, :extension, :sep from dual; /* write the second script */ dbms_output.put_line('set colsep ' || :sep); dbms_output.put_line('spool ' || :fullpath || :filename || '.' || :extension); dbms_output.put_line('select 1, 2, 3 from dual;'); dbms_output.put_line('spool off'); end; / spool off /* run the second script */ @d:\secondscript.sql This gives:
SQL> sta C:\firstScript.sql Connected. set colsep | spool d:\filename.txt select 1, 2, 3 from dual; 1| 2| 3 ----------|----------|---------- 1| 2| 3 d:\filename.txt:
1| 2| 3 ----------|----------|---------- 1| 2| 3
-1487275 0 Programmatically switch the ID generator in NH mapping file So I'm currently attempting to do a promotion of objects from one database to another in my app. Basically I want to allow the user to click a button and promote changes from staging to production, as it were.
To do this, I really want to keep the IDs the same in order to help with debugging. So for example if the object has an ID of 6 in the staging db, I want it to have that same ID on production. To do this, we turned off identity on our production db and just made those primary key columns with non-null integers.
In my staging mapping file, my IDs are mapped using the "identity" generator, but for production I want them to be "assigned". Is it possible to programmatically change this, perhaps using an interceptor or something similar?
Thanks in advance!
-16819408 0You are not referencing the $id variable, but rather a string text id which breaks the query statement. Add a dollar sign to reference the variable, and if it's anything but an integer, wrap it in single quotes, too.
$query = "UPDATE utilizatori SET username = '$username', {...}, ip = '$ip' where id= '$id' ";
If you know the name of the menu inside drupal you can render it this way:
Example of page.tpl.php:
<div id="menu"> <?php if (isset($secondary_menu)) { ?><?php print theme('links', $secondary_menu, array('class' => 'links', 'id' => 'subnavlist')); ?><?php } ?> <?php if (isset($main_menu)) { ?><?php print theme('links', $main_menu, array('class' => 'links', 'id' => 'navlist')) ?><?php } ?> </div> For more information on how to convert a drupal 6 theme to drupal 7 I would recommend going through this tutorial:
https://drupal.org/node/254940#menus
-16608976 0I use it this way:
So it is not necessary to wait the specific time to end.
public void run(){ try { //do something try{Thread.sleep(3000);}catch(Exception e){} //do something }catch(Exception e){} }
-19117076 0 Animate control with respecting parents/container I have a control that I move with help of animation from the bottom to the final position. My problem is now that I want to change the behaviour of the animation, so that it respects the outer container (DarkGray).
The orange Ractangle should only be visible on the white background and not on the darkgray Grid!
Code:
MainWindow.xaml:
<Grid Background="DarkGray"> <Grid Margin="50" Background="White"> <Rectangle x:Name="objectToMove" VerticalAlignment="Bottom" Fill="Orange" Height="50" Width="50"/> <Button Height="20" Width="40" Margin="20" Content="Move" Click="Button_Click" VerticalAlignment="Top"/> </Grid> </Grid> MainWindow.xaml.cs:
private void Button_Click(object sender, RoutedEventArgs e) { var target = objectToMove; var heightOfControl = target.ActualHeight; var trans = new TranslateTransform(); target.RenderTransform = trans; var myAnimation = new DoubleAnimation(heightOfControl, 0, TimeSpan.FromMilliseconds(600)); trans.BeginAnimation(TranslateTransform.YProperty, myAnimation); } Current:

Desired solution:

You can try this XPath to get text node after <a> element :
nodeValue = hd.DocumentNode .SelectSingleNode("//div[@class='resum_card']/p/a/following-sibling::text()"); Note: simply use single slash (/) instead of double (//) to select element that is direct child of current element. It is better performance wise.
I have a very large (950GB) binary file in which I store 1billion of sequences of float points.
A small example of the type of file I have with sequences of length 3 could be:
-3.456 -2.981 1.244 2.453 1.234 0.11 3.45 13.452 1.245 -0.234 -1.983 -2.453 Now, I want to read a particular sequence (let's say the sequence with index=2, therefore the 3rd sequence in my file) so I use the following code:
#include <iostream> #include <fstream> #include <stdlib.h> using namespace std; int main (int argc, char** argv){ if(argc < 4){ cout << "usage: " << argv[0] << " <input_file> <length> <ts_index>" << endl; exit(EXIT_FAILURE); } ifstream in (argv[1], ios::binary); int length = atoi(argv[2]); int index = atoi(argv[3]); float* ts = new float [length]; in.clear(); **in.seekg(index*length*sizeof(float), in.beg);** if(in.bad()) cout << "Errore\n"; **// for(int i=0; i<index+1; i++){** in.read(reinterpret_cast<char*> (ts), sizeof(float)*length); **// }** for(int i=0; i<length; i++){ cout << ts[i] << " "; } cout << endl; in.close(); delete [] ts; return 0; } The problem is that when I use seekg this read fails for some indexes and I get a wrong result. If I read the file in a sequential manner (without using seekg) and print out the wanted sequence instead, I always get the correct result.
At the beginning I thought about an overflow in seekg (since the number of bytes can be very big), but I saw seekg takes in input a streamoff type which is huge (billions of billions).
-5789787 0Two simple options would be to either provide your user with some dictionary where they can register type mappings, or alternatively just provide them with a container interface that provides all of the services you think you're likely to require and allow users to supply their own wrapped containers. Apologies if these don't quite fit your scenario, I primarily use Unity, so I don't know if Ninject, etc. do fancy things Unity doesn't.
-7640083 0Possibly not the most relevant answer to your original question but since I got redirected to this page while looking for a way to control the formatting of DateTime properties in the serialisation someone else might find it useful.
I found that by adding the following to your app.config/web.config instructs the .NET serialisation to format DateTime properties consistently:
<system.xml.serialization> <dateTimeSerialization mode="Local" /> </system.xml.serialization> Ref: http://msdn.microsoft.com/en-us/library/ms229751(v=VS.85).aspx
-25787024 0If you're testing for a property to be in an array, you can use the Contains extension method on IEnumerable, which is probably preferable to building a string. Try this:
Dim query = From element In dtImitate.Where(function (el) teamsArray.Contains(el.Team))
-24673698 0 unexpected EOF while looking for matching `'' while using sed Yes this question has been asked many times, and in the answer it is said to us \ escape character before the single quote.
In the below code it isn't working:
LIST="(96634,IV14075295,TR14075685')" LIST=`echo $LIST | sed 's/,/AAA/g' ` echo $LIST # Output: (96634AAAIV14075295AAATR14075685') # Now i want to quote the list elements LIST=`echo $LIST | sed 's/,/\',\'/g' ` # Giving error # exit 0 Error :
line 7: unexpected EOF while looking for matching `'' line 8: syntax error: unexpected end of file
-17863081 0 remove character columns from a numeric data frame I have a data frame like the one you see here.
DRSi TP DOC DN date Turbidity Anions 158 5.9 3371 264 14/8/06 5.83 2246.02 217 4.7 2060 428 16/8/06 6.04 1632.29 181 10.6 1828 219 16/8/06 6.11 1005.00 397 5.3 1027 439 16/8/06 5.74 314.19 2204 81.2 11770 1827 15/8/06 9.64 2635.39 307 2.9 1954 589 15/8/06 6.12 2762.02 136 7.1 2712 157 14/8/06 5.83 2049.86 1502 15.3 4123 959 15/8/06 6.48 2648.12 1113 1.5 819 195 17/8/06 5.83 804.42 329 4.1 2264 434 16/8/06 6.19 2214.89 193 3.5 5691 251 17/8/06 5.64 1299.25 1152 3.5 2865 1075 15/8/06 5.66 2573.78 357 4.1 5664 509 16/8/06 6.06 1982.08 513 7.1 2485 586 15/8/06 6.24 2608.35 1645 6.5 4878 208 17/8/06 5.96 969.32 Before I got here i used the following code to remove those columns that had no values at all or some NA's.
rem = NULL for(col.nr in 1:dim(E.3)[2]){ if(sum(is.na(E.3[, col.nr]) > 0 | all(is.na(E.3[,col.nr])))){ rem = c(rem, col.nr) } } E.4 <- E.3[, -rem] Now I need to remove the "date" column but not based on its column name, rather based on the fact that it's a character string.
I've seen here (remove an entire column from a data.frame in R) already how to simply set it to NULL and other options but I want to use a different argument.
-40537843 0i did like that and it worked: (it wont start to download, and it will open in a new tab (target _blank) if same tab, thenit is (target _self)
<a href="<c:url value='resources/pdfs/your pdf(already in the project).pdf' />" target="_blank"> show pdf in a new tab</a>
My question is the following: Can relations have key attributes like shown in the following figure? 
For me it doesn't make sense, however I have found them like in 1. If it is possilbe, how should I "resolve" them in the relational schema?
I found a similar the question on [2] but it seems to focus on how to handle attributes during the transformation of the ERM to the relational schema.
1 https://www.wu.ac.at/fileadmin/wu/processed/csm_erm_cardinalities2_84a65dbc2b.png
[2] relationship attributes in ER diagrams
-37800052 0Bear in mind that audiences only begin accumulating members after you define them. So, after you define this audience, once at least 10 LOGIN events are logged with a sign_up_method which includes "CEO", you will see your results in Firebase Analytics. More on audiences in the Firebase Help Center.
-6122070 0 How to get tasklist information from cmd, without using "tasklist" commandAnyone knows how to extract the tasklist information using cmd, but without using "tasklist /svc" command?
-21745915 0 cassandra performance and speed with multiple insertion?I am new to cassandra and migrating my application from Mysql to cassandra.As i read of cassandra it says it reduces the read and write time compared to Mysql.when i tried a simple example with single node using hector, reading operation is quite faster compared to Mysql,and if i tried to insert a single column it is very fast compared to mysql.But when i tried to insert a single row with multiple columns its taking long time compared to mysql. Is there anyway to improve Write performance or please let me know if i am wrong with my way of coding.
My sql code is INSERT into energy_usage(meter_id,reading_datetime,reading_date,reading_time,asset_id,assetid) VALUES('164','2012-12-07 00:30:00','2012-12-07','00:00:00','1','1') " my cassandra code is
Mutator<String> mutator = HFactory.createMutator(keyspaceOperator, StringSerializer.get()); mutator.addInsertion("888999", DYN_CF, HFactory.createStringColumn("assetid","1")). addInsertion("888999", DYN_CF, HFactory.createStringColumn("meterid", "164")). addInsertion("888999", DYN_CF, HFactory.createStringColumn("energyusage","10")). addInsertion("888999", DYN_CF, HFactory.createStringColumn("readdate","2012-12-07")). addInsertion("888999", DYN_CF, HFactory.createStringColumn("readdatetime","2012-12-07 00:30:00")); mutator.execute();
-36009322 0 I do not know which packages and data I need to reproduce your example but you can use a sequence of daily dates, the merge function and the NA filler in the zoo package to create the daily data frame:
library(zoo) # Date range sd = as.Date("1970-01-01") ed = Sys.Date() # Create daily and monthly data frame daily.df = data.frame(date = seq(sd, ed, "days")) monthly.df = data.frame(date = seq(sd, ed, "months")) # Add some variable to the monthly data frame monthly.df$v = rnorm(nrow(monthly.df)) # Merge df = merge(daily.df, monthly.df, by = "date", all = TRUE) # Fill up NA's df = transform(df, v = na.locf(v)) This might not be the fastest way to obtain the data frame but it should work.
-4731669 0 which files are need to create .ipa for my application which is done in xcodeI am creating a simple application in xcode
Now i need to create ipa for that file.
By google i found some info regarding this.
create a folder named Payload and copy the app file,Zip the fine and rename zip to .ipa.
But i have a doubt in the this path users/username/library/application support/iphone simulator/4.1/Applications
i found a folder named with random alphabets and numbers.
In that i found documents,library,tmp folders along with my application.app.
is i need to copy all the 3 folders into payload or just my application.app is enough.
And i did n't get my icon in over the .ipa.
How can i get it.
can any one pls help me.
Thank u in advance.
-22851901 0 Route specific page to controller in ASP.NET MVCIf I have a page on my site (extension could be ".html", whatever:
I want this page to invoke a specific web api controller and action. Can anyone help with configuring this in the route mapping? Thanks.
-38752559 0Alright so it's nothing related to the CardView. Just buttons on Android 5.1 (Lollipop)+ Try these two rules with your class and it will work. You won't need border-color: transparent with this either.
border-width: 0.1; background-color: transparent;
It's because you use http://underscorejs.org/#without, which creates a copy of the array instead of just removing the item. When you remove an item a new array will be linked to the scope, and the new array is not linked with array in the isolate scope.
To solve this problem you can use splice instead, which removes the item from the original array:
$scope.removeSkill = function() { $scope.profile.skills.splice(_.indexOf($scope.profile.skills, this.skill),1); }; ...
$scope.removeItem = function() { $scope.list.splice(_.indexOf($scope.list, this.item),1); }; Updated plunker: http://jsfiddle.net/jtjf2/
-40517681 0 Howto set Outlook MailItem Property CategoryI am trying to set the category of the currently selected outlook mail item to a value.
The following seems to be setting it but it isnt updating the GUI of Outlook.
Option Explicit Public Sub SaveMessageAsMsg() Dim oMail As Outlook.MailItem Dim objItem As Object Dim sPath As String Dim dtDate As Date Dim sName As String Dim enviro As String Dim oPA As PropertyAccessor Dim arrErrors As Variant Dim i As Integer enviro = CStr(Environ("USERPROFILE")) For Each objItem In Application.ActiveExplorer.Selection If objItem.MessageClass = "IPM.Note" Then Set oMail = objItem Debug.Print oMail.Categories oMail.Categories = "99 - Archive" Debug.Print oMail.Categories End If Next End Sub
-24859414 0 Customize Gii Code Generator For Internal UseI am new to yii.I want to use Gii Code Generator in my application for generate model and CRUD dynamically.Like i am giving rights to choose field for their form.They enter details for fields and click button for generate form at that time in back hand i want to generate table for that all field, model and crude for that.I can generate table in back hand but when i want to generate model and crude i have show interface of gii. I can't hide it from User so please help me out if any one knew how to generate all in back hand.please.
-11482582 0It's not clear what you want do do, but if you're using POST to send it to PHP then you can check if the value is empty like this
<?php if(empty($_POST['value_name'])) { echo 'value is required'; } else { // OK }
-21153087 0 check that you have all js files on your
MAGETOAPP/desing/fontend/theme/template/checkout/onepage.phtml
script type="text/javascript" src="getJsUrl('varien/accordion.js') ?>"
script type="text/javascript" src="getSkinUrl('js/opcheckout.js') ?>"
script type="text/javascript">countryRegions = helper('directory')->getRegionJson() ?>
-28616911 0 How to set an ImageView to match_parent and horizontally scale accordingly?I have a RelativeLayout in a section of my activity that includes a button and an ImageView. The size of the RelativeLayout is ListPreferredItemHeight and what I would like to do is have the ImageView span from top to bottom of that layout and be scaled accordingly.
Currently, without implementing any scaling attributes, I have this image:

I achieve this with the following xml code:
<RelativeLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1"> <Button android:id="@+id/newPrescription_Medication" android:gravity="center" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_toLeftOf="@+id/newPrescription_AddMedication" android:layout_toStartOf="@id/newPrescription_AddMedication" android:text="@string/select_medication"/> <ImageView android:id="@+id/newPrescription_AddMedication" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:src="@drawable/add_icon"/> </RelativeLayout> Now, to try and fill the space with the button, I added the following to the ImageView tag:
android:adjustViewBounds="true" android:scaleType="centerInside" 
How can I get the entire image to appear, while maintaining its position on the right side of the layout and filling the rest with the button?
-6489201 0This error means that Rails.application isn't initialized. I didn't actually know that, I cheated.
So that then begs the question: how did you set up this application?
Perhaps this application doesn't contain a config/application.rb file that defines a class that inherits from Rails::Application and therefore is causing this problem. In my application here, I've got this one you could use as an example.
By submitting the form in HTML you basically tell the browser to generate a normal HTTP request, usually POST or GET, for an URL defined in tag with form fields attached according to the specified method either appended to the URL or included in the request data.
There is nothing really special or different from a "normal" HTTP request, in fact you can manually "submit a form" by appending form keys and values to the URL in your browser and navigating to it in case of GET method.
Summarizing:
1) Yes, you are right.
2) From what I've just read (never used REST personally) a REST application is implemented by a servlet mechanism and uses HTTP protocol, so it should be possible to write a REST application for processing HTML forms if the form points to this application's URL.
-39480810 0Technically the copy constructor gets invoked in the following cases:
The assignment operator is implemented to obliterate an exiting instance's old contents with new ones. As you showcase an example:
myClass newInstant; newInstant = oldInstant;//assignment operator Keep in mind that they work differently. Copy-swap involves in the assignment operator.
Regarding your last question, modern compilers apply copy constructor elision to elide unnecessary copy constructor call.
-38923703 0 How to add aurelia-animator-css to a cli-created projectI created a new project using aurelia cli. I npm installed aurelia-animator-css and added aurelia.use.plugin('aurelia-animator-css'); to main.js. However aurelia-animator-css never loads. What else do I need to do? I assume I have to edit aurelia.json, but I'm not sure what to add.
I had this issue recently with another group of plugins recently. One wouldn't allow me to disable it because it dependeded on the other, but the other was disabled and wouldn't allow me to enable it because of the dependency.
All you have to do to fix this is go to your jenkins installation, and under the plugins directory look for the plugin_name.jpi file. For the disabled plugin, you should see a file called plugin_name.jpi.disabled. Just delete the disabled file and then you should be able to enable / disable the plugins through the UI.
Note: you can also manually disable plugins by creating a disabled plugin file using the naming convention above.
-35868533 0Thanks for the heads up about the bug report and fix. I feel the need to give an answer to this question though, just in case you haven't ditched PHP and Slim framework altogether. Hopefully, it will be of help to someone else.
My approach to this would be:
<?php use Slim\Http\Request; use Slim\Http\Response; class AuthenticationMiddleware { public function isAuthenticated($userid, $authorization) { //do data validation here return false; } public function createErrorResponse($code, $msg, Response $response) { return $response->withStatus($code) ->withHeader('Content-Type', 'application/json;charset=utf-8') ->withJson($msg); } public function __invoke(Request $request, Response $response, $next) { $userid = $request->getHeaderLine('userid'); $authorization = $request->getHeaderLine('Authorization'); if(!$this->isAuthenticated($userid, $authorization)) { $msg = 'You are unauthenticated. Please login again'; $code = 400; $this->createErrorResponse($code, $msg, $response); } else { $response = $next($request, $response); } return $response; } } Let me just say this. I would abstract a few stuff here in this code so I don't end up repeating myself. I see you repeating:
public function createErrorResponse($code, $msg, Response $response) { return $response->withStatus($code) ->withHeader('Content-Type', 'application/json;charset=utf-8') ->withJson($msg); } In all your middleware and perhaps, in your routes. Hope this sets someone on the right track.
-7109507 0If all values end up at star0.png, then you are cycling through the list. The fact that the else statement is the only code being executed for each element suggests a logical error -- did you perhaps mean to do something like this?
string serviceCode = ReviewList[i].SERVICE.SERVICE_CODE;
-19178374 0 Two divs in the same row (in a arrow shaped parent div) with text in one div getting clipped based on the width of second div Here is a jsfiddle link of my issue
HTML
<div class="Right green"> <h2> <div class="number colorV"> 8.123456 </div> <div id="text"> huh-fjiuetie</div> </h2> <div class="Right-after green-after"></div> </div> Conditions are:
div's inside the h2 tag have to be on the same line..text div gets clipped based on the content in the number div (widths cannot be fixed as the content in the number div is dynamically generated)Any suggestion would be appreciated.
-2353460 0You can use the ANSI colour codes. Here's an example program:
#include <stdio.h> int main(int argc, char *argv[]) { printf("%c[1;31mHello, world!\n", 27); // red printf("%c[1;32mHello, world!\n", 27); // green printf("%c[1;33mHello, world!\n", 27); // yellow printf("%c[1;34mHello, world!\n", 27); // blue return 0; } The 27 is the escape character. You can use \e if you prefer.
There are lists of all the codes all over the web. Here is one.
-37403768 0The issue is the static variable item is initialized to 0 when the class loads. Once you change it by reading in the user inputted value, you don't allocate properly sized arrays for your static variables. You can fix this by doing so after reading in the value:
public static void addItem() { Console.WriteLine("\nAmount of items to add"); item = Convert.ToInt32(Console.ReadLine()); // initialize static vars to correct size, now that we have #items product = new string[item]; code = new string[item]; price = new string[item]; unit = new string[item]; Console.WriteLine("Insert the items."); for (int i = 0; i < item; i++) { Console.WriteLine("\nItem[" + i + "]: "); Console.Write("Product[" + i + "]: "); product[i] = Console.ReadLine(); Console.Write("Code[" + i + "]: "); code[i] = Console.ReadLine(); Console.Write("Price[" + i + "]: "); price[i] = Console.ReadLine(); Console.Write("Unit[" + i + "]: "); unit[i] = Console.ReadLine(); } } You can see the fixed code in action at https://dotnetfiddle.net/n5lWTQ !
-17698595 0 Razor passing values between domainsI'm new to .NET, and try to work with Razor. I have 100 domains, all about places. My question is: Is it possible to have a page, per domain, which passes Place ID to a Razor Folder containing Default.cshtml, somewhere on the Server. Default.cshtml page regulates all the requests for all domains including DB connection, _Layout, etc etc...? To put it simple: the domain paris.com has only two tags: PlaceID And includeFile/General Domain/Default.aspx Default.aspx sees PlaceID and acts accordingly. But Include doesn't exist by Razor...
-7952983 0rails integration tests should be written so that the on case tests the one single request - response cycle. we can check redirects. but if you have to do something like
get '/something', {:status=>'any_other'}, @header
get '/something', {:status=>'ok'}, @header
You should write two different cases for this.
-4933072 0 Problem of using proxy with wget in UbuntuPlease help me, I want to download file from dev.opennebula.org using command wget but I have a problem with proxy. Now, I have already set the http-proxy value in file /etc/wgetrc and I use command wget --proxy-username=username --proxy-password=password URL but the result is
Connecting to proxy.mmcs:8080 failed: Connection timed out. Retrying.
I am sure that I set the proxy name and port correctly. How can I do and can I use other commands to download that file.
Thank you.
-19165744 0 Access my class returned list collection in code behindI have a list collection in my class library that uses a sql datareader to returns a list of family details
public class Dataops { public List<Details> getFamilyMembers(int id) { some of the database code.. List<Details> fammemdetails = new List<Details>(); Details fammember; while (reader.Read()) { fammemdetails = new Details(( reader.GetString(reader.GetOrdinal("PHOTO"))); fammemdetails.add(fammember); } return fammemdetails; } } So i reference the dll to my project and would like to bind an image to one of my datareader values.
MyProject
DataOps ops = new DataOps(); myimage.ImageUrl = ??? (how do i access the list collections return image value here? I am able to bind a datasource to the entire method like so
dropdownlistFamily.DataSource = mdb.GetFamilyMembers(id); But cant figure out how to just grab a single value from there
-13707523 0 Behaviour of webapplication seems to depend on my datasource?I'm running a JSF-Webapplication on a GlassFish v3.1.2
If I test it locally everything works fine. Now I only change the datasource and I get some strange bevavior:
For example I have a command button which invokes some action to receive data from a database and I want to display this data in a datatable on the same page. With my local database this works fine, but if I use the other database (which is running on a different server in the local intranet), the action is fired (I have checked this with some System.out's) but the ajax-update of my datatable does not work. If I reload the page after clicking my ajax-button the correct data is displayed, also if I use a non-ajax-button.
I do not even know what I should look for .. any ideas?
Im using
Please let me know if you need more information.
Thanks in advance, Fant
Http-response-header: HTTP/1.1 200 OK X-Powered-By: Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 3.1.2 Java/Oracle Corporation/1.7), JSF/2.0 Server: GlassFish Server Open Source Edition 3.1.2 Cache-Control: no-cache Content-Type: text/xml;charset=UTF-8 Content-Length: 5610 Date: Sat, 08 Dec 2012 02:05:08 GMT
I also tried to write a PhaseListener to give me some feedback, but this was not very helpful either. Every phase is finished succesful and after my action is performed, an response is send to the client (and the client receives the response as I can see in the Firefox-Addon) Even the Getter-method of the List that I want to display in my dataTable is called before the htpp-response is send, so I think there is everything fine with the response itself. But the dataTable that I want to rerender is still showing the old data.
-13802625 0The problem seems to lie in that all your "content-pad" classes doesnt have the width of the page.
As soon as i give it a width it works fine.
-20543929 0Finally am able to find the actual cause of above issue.
I am using the gem postmark-rails, previously postmark was not supporting the email-attachments, so recently they had enhanced gem to support attachments and unfortunately i was using the old version of it, so i need to update gem version to latest as they have mentioned in one of their issues: attachment-issue
also i was trying to send url of file saved on S3, so instead of that i need to read that file from url and then send it as attachment
require "open-uri" def send_refer_pt_request(params, attachment) if attachment.present? mime_type = MIME::Types.type_for(attachment).first url_data = open(attachment).read() attachments["#{attachment.split('/').last}"] = { mime_type: mime_type, content: url_data } end mail( to: <some_email>, subject: "Refer Request", tag: "refer_request") end
-34716945 0 First, you should not use find('list') since it returns key/value pairs, you want to use (e.g.):
$types = $this->Types->find()->select(['id','name','color'])->toArray(); Then in your view, you want to be able to store the color attributes, so e.g.:
// Convert your $types array to something we can send to `select` $options = array_map(function ($e) { return [ 'value' => $e->id, 'text' => $e->name, 'templateVars' => [ 'color' => $e->color ] ]; }, $types); // Use a custom template for the `option` element to store the color as a data- attribute $this->Form->templates([ 'option' => '<option value="{{value}}" data-color="{{color}}"{{attrs}}>{{text}}</option>' ]); // Create the select element echo $this->Form->select('type', $options, [ 'empty'=>'Types', 'class' => 'form-control', 'id' => 'types' ]); See the cookbook if you don' t know what are additional template variables (templateVars ) - You need CakePHP 3.1+ to use templateVars.
You will get something like:
<select name="type" class="form-control form-control" id="types"> <option value="" data-color="">Types</option> <option value="1" data-color="ff0000">Red</option> <option value="2" data-color="0000ff">Blue</option> <option value="3" data-color="00ff00">Green</option> </select> For the following, I am assuming you have an element with id="color-preview" in which you want to set the background color, e.g.:
<div id="color-preview"></div> Here is what the javascript code would look like (with jQuery):
$('#types').on('change', function () { var opt = $(this).find(':selected'); var col = ''; if (opt.data('color')) { col = '#' + opt.data('color'); } $('#color-preview').css({background: col}); }); Without jQuery (modern browser only):
var previewDiv = document.getElementById('color-preview'); document.getElementById('types').addEventListener('change', function () { var opt = this.options[this.selectedIndex]; var col = ''; if (opt.dataset.color) { col = '#' + opt.dataset.color; } previewDiv.style.background = col; });
-17276580 0 looping through XML file using VB.NET I am having a problem processing an XMl file. I want to loop through (using VB.NET) the file and extract all the values of the OrderID element.
<?xml version="1.0"?> <ListOrdersResponse xmlns="https://xxx.xxxxxx.com/Orders/999uuu777"> <ListOrdersResult> <NextToken>XXXXXXXXXX</NextToken> <Orders> <Order> <ShipmentServiceLevelCategory>Standard</ShipmentServiceLevelCategory> <OrderId>ooooooooo</OrderId> </Order> <Order> <ShipmentServiceLevelCategory>Standard</ShipmentServiceLevelCategory> <OrderId>ujuujujuj</OrderId> </Order> </Orders> <CreatedBefore>2013-06-19T09:10:47Z</CreatedBefore> </ListOrdersResult> <ResponseMetadata> <RequestId>8e34f7d9-3af7-4490-801b-cccc7777yu</RequestId> </ResponseMetadata> </ListOrdersResponse> Here is the code I am trying but it does not loop through each order
Dim doc As New XmlDocument() doc.Load(file) Dim nodelist As XmlNodeList = doc.SelectNodes(".//Orders/Order") For Each node As XmlElement In nodelist console.writeline(node.SelectSingleNode("OrderID").InnerText) Next Any help would be gratefully appreciated.
-17634286 0 Detect which layout is in use in an activity with two layoutsI have an activity called MainActivity that has two layouts.The previous activity has two buttons to choose which layout to be set.I need the button in MainActivity to act differently according to the layout in use, This is my code:
public class MainActivity extends Activity implements OnClickListener { Button shoot; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle extras = getIntent().getExtras(); if (extras != null) { int btnNumber = extras.getInt("button"); switch(btnNumber) { case 1 : setContentView(R.layout.first_layout); break; case 2 : setContentView(R.layout.second_layout); break; } } shoot=(Button)findViewById(R.id.button1); shoot.setOnClickListener(this); public void onClick(View arg0) { // TODO Auto-generated method stub switch(arg0.getId()) { case R.id.button1: // WHAT SHOULD THE CODE BE HERE break; } }
-3894791 0 jQueryUI extends the animate class for this reason specifically. You can leave off the original parameter to append a new class to your object.
$(".class1").switchClass("", "class2", 1000);
-17396528 0 Warning: Attempt to dismiss from view controller while a presentation or dismiss is in progress I almost broke my brain on this one
Here is the error: Trying to show status page at the login page 2013-06-30 20:47:53.422 MyProgram[489:907] Warning: Attempt to dismiss from view controller while a presentation or dismiss is in progress!
I have the following code in SCAppDelegate.m
- (void)showStatusViewController { MLStatusViewController* statusViewController = [[MLStatusViewController alloc] initWithNibName:@"MLStatusViewController" bundle:nil]; UIViewController *topViewCntrller = [self.navController topViewController]; [topViewCntrller presentModalViewController:statusViewController animated:NO]; } Then I have another view controller where when a user saves data I want to move to another (status) view controller. I don't see how I can add another controller on top so my understanding is if I disband the current one and go back to SCAppDelegate method above that it should show that status page.
This is the code in that view controller that is trying to disband/show status view controller.enter code here
[self dismissViewControllerAnimated:YES completion:^{ SCAppDelegate* appDelegate = [UIApplication sharedApplication].delegate; [appDelegate showStatusViewController]; }]; I know this comes from the lack of understanding how view controllers work and I read the guide, but still can't seem to figure this out.
I am using Facebook API to login into the app, which is adding some complexity in how to manage view controllers.
Any ideas will be super welcome :D
Thank you!
-5388506 0How are you hosting your service?
If your service is hosted in IIS, it is possible that the application was recycled between the 2 calls. In this case the app domain is recreated and the static members loose their values.
-3642269 0 Reusable Page_PreRender function in asp.netI have a function which sets my linkbutton as the default button for a panel.
protected void Page_PreRender(object sender, EventArgs e) { string addClickFunctionScript = @"function addClickFunction(id) { var b = document.getElementById(id); if (b && typeof(b.click) == 'undefined') b.click = function() { var result = true; if (b.onclick) result = b.onclick(); if (typeof(result) == 'undefined' || result) eval(b.getAttribute('href')); } };"; string clickScript = String.Format("addClickFunction('{0}');", lbHello.ClientID); Page.ClientScript.RegisterStartupScript(this.GetType(), "addClickFunctionScript", addClickFunctionScript, true); Page.ClientScript.RegisterStartupScript(this.GetType(), "click_" + lbHello.ClientID, clickScript, true); } This works fine. How to make this reusable to all my pages of my application. One page can have multiple linkbuttons and multiple panels.... Any suggestion...
-8772229 0Fixed, here's the solution http://stackoverflow.com/a/8550870/106616
-1651679 0I'm going to hazard a guess that your statement that the code is "slightly modified to work" means that this code:
newlistitem.Value = options[j][valuefield].ToString() + ((options[j]["pdprice"].ToString().Length > 0 ) ? "/" + options[j]["pdprice"].ToString() : "" ); actually looked like this:
newlistitem.Value = options[j][valuefield].ToString() + options[j]["pdprice"].ToString().Length > 0 ? "/" + options[j]["pdprice"].ToString() : ""; (note the missing parenthesis)
The reason that this code will produce this error is that due to operator precedence, what will get evaluated is this:
String a = options[j][valuefield].ToString(); Int32 b = options[j]["pdprice"].ToString().Length; String c = a + b; Boolean d = c > 0; String e = "/" + options[j]["pdprice"].ToString(); String f = ""; newlistitem.value = d ? e : f; With this way of looking at it, a+b will produce a new string, since adding something to a string will convert that something to a string for concatenation. Basically, "xyz" + 3 gives "xyz3".
By adding the parenthesis, your "slight modification", you've essentially rewritten the code to do this:
String a = options[j][valuefield].ToString(); String b = options[j]["pdprice"].ToString().Length; Boolean c = b > 0; <-- this is different String d = "/" + options[j]["pdprice"].ToString(); String e = ""; String f = c ? d : e; String g = a + f; <-- and this newlistitem.value = g; Notice the difference between d in the first code and c in the second code. You've moved the concatenation of the string out where it belongs, together with the other strings.
So your slight modification works since it is the correct way of doing it, if you want to keep those expressions.
The accepted answer is a much better alternative. My goal was to give you an explanation as to the reason of the exception.
-27722636 0 node.js mongodb projection ignored when there is a criterionI am writing a node.js application using express, mongodb, and monk.
When I do a find with criteria only or with projections only, I get the expected result, but when I do a find with both, the full documents are returned, i.e., the projection is not performed. My code looks like this:
var collection = db.get('myDB'); collection.find({field1: "value"},{field2: 1, _id: 0},function(e,docs) { ...do stuff with docs... }); It returns not just field2 but all fields of all the docs matching the criterion on field1. I can get field2 from this, but I don't like the inefficiency of it.
Is there a way to use both criteria and projections?
-8764327 0This is in addition to my comments:
Check out the SDK listed in the link I gave with the comments. They have a sample RoR app laid out which should tell you pretty much exactly how to do each kind of adaptive payment with Rails. Just beware that there are many errors in this application. Look at James' answer on this question to fix them:
Is anyone using Paypal's Adaptive Payments API with Ruby?
Also, thanks for the heads up on the paypal_adaptive gem.
EDIT: Here's the SDK link just in case. https://www.x.com/developers/paypal/documentation-tools/sdk
-3130941 0 j2me code for blackberry application to display battery levelHow can I make a Blackberry application display the battery level using J2ME?
-2483795 0The Canvas element is essentially a drawing canvas that can be painted on programmatically; a sort of scriptable bitmap drawing tool for the web.
I suppose the "amazing" thing about it, apart from the fact that we can now all create web-based MS Paint clones with ease, is that you have a much richer, completely free-form area for creating complex graphics client-side and on-the-fly. You can draw pretty graphs, or do things with photos. Allegedly, you can also do animation!
Mozilla's Developer Center has a reasonable tutorial if you want to try it out.
-1965618 0You should take it as more of a symptom than part of the actual problem when you are stuck in system all the time.
Memory fragmentation and paging out is the usual suspect, but it could be a myriad of things.
In my experience performance problems are seldom something obvious like you are calling something specifically. Optimizing like commonly suggested is usually useless at a really low level. It catches things that amount to bugs that are correct but usually unintended like allocating something and deleting it over and over but for things like this you often need to have a deep understanding of everything happening to figure out exactly where the issue is (but like I said, surprisingly often it's memory management related if you are stuck in system calls a lot).
-16685617 0$ cat test.txt abc def ghi jkl mno $ cat test.txt | tr '\n' ',' abc,def,ghi,jkl,mno, $ cat test.txt | awk '{print "\x27" $1 "\x27"}' | tr '\n' ',' 'abc','def','ghi','jkl','mno', $ cat test.txt | awk '{print "\x27" $1 "\x27"}' | tr '\n' ',' | sed 's/,$//' 'abc','def','ghi','jkl','mno' The last command can be shortened to avoid UUOC:
$ awk '{print "\x27" $1 "\x27"}' test.txt | tr '\n' ',' | sed 's/,$//' 'abc','def','ghi','jkl','mno'
-26850634 0 Applying multiple IF functions to every row I need to apply the following IF functions to every row in columns J, L, and S so that the correct date value is printed in the corresponding cell in row T. For example, cell T2 will have a date printed in it based on the outcome of running these IF functions on J2, L2, and S2; cell T3 will have a date printed in it based on the outcome of running these IF functions on J3, L3, and S3; and so on. Here's what I have got:
Sub Test1() Set firstDate = Range("S2") If Range("J2") = "GS/CA/SL/GW" Then If Range("L2") = "1" Or "2" Or "3" Then Range("T2") = DateAdd("ww", 52, firstDate) End If If Range("L2") = "4" Or "5" Or "6" Then Range("T2") = DateAdd("ww", 104, firstDate) End If If Range("L2") = "7" Or "8" Or "9" Then Range("T2") = DateAdd("ww", 156, firstDate) End If End If End Sub It works on one set of cells at a time if I just redefine all the ranges, but I thought there must be an easier way than pasting and editing the code ~3500 times for all the rows I have to run it on. Any help would be appreciated!
-18919079 0As an additional idea, the problem of GarethD's method is, that it requires more or an equal number of rows in the second table as in the first table.
So you can just do a cross join of the second table with the first one, and limit the results to the number of rows in the first table.
WITH PatientCTE AS ( SELECT PatientID ,pat_FirstName ,pat_LastName ,pat_StreetName ,pat_PostalCode ,pat_City ,pat_DateOfBirth ,rn = ROW_NUMBER() OVER(ORDER BY NEWID()) FROM Patients ) , SampleData AS ( SELECT TOP (SELECT COUNT(*) FROM PatientCTE ) GivenName ,SurName ,StreetAddress ,ZipCode ,City ,Birthday ,rn = ROW_NUMBER() OVER(ORDER BY NEWID()) FROM FakeNameGenerator CROSS JOIN PatientCTE ) UPDATE p SET p.pat_FirstName = fn.GivenName ,p.pat_LastName = fn.SurName ,p.pat_StreetName = fn.StreetAddress ,p.pat_PostalCode = fn.ZipCode ,p.pat_City = fn.City ,p.pat_DateOfBirth = fn.BirthDay FROM PatientCTE AS p INNER JOIN SampleData AS fn ON fn.rn = p.rn
-29270122 0 This function could probably be improved upon. Tip of the hat to @thelatemail.
lm.3Trans = function(y, x1, x2, transformations = c(log,sqrt,pwer)){ pwer = function(x, p = 2) poly(x,p) res = lapply(transformations, function(f) lm(y ~ f(x1) + x2)) res } This will output your models into a list to which you could then do something like:
lapply(lm.3Trans(y,x,x1), summary) To get more detailed summaries
It might be worth expanding this function to take a formula, and perhaps another arguement to identify which predictor should be transformed. Please let me know if that is useful.
-25494742 0I experienced the same problem.
Downloaded and installed SQL Server 2012 SP2 and that seemed to have fixed the problem.
Hope this helps!!
-26367658 0Ultimately, to get around this, I had to use request.ServerVariables["HTTP_URL"] and some manual parsing, with a bunch of error-handling fallbacks (additionally compensating for some related glitches in Uri). Not great, but only affects a tiny minority of awkward requests.
Two things makes this Class very useful:
Context brings a host of resources for us: we can figure out some device properties, load some resources, initiate a SQLite database etc, etc.
All of this happens before any Activity loads, and all of this is globally available to the Activities.
Simple example of what I mean:
public class App extends Application{ private static Resources sResources; //--I want to load strings resources from anywhere-- public static String loadStringResource(int resID) { return sResources.getString(resID); } @Override public void onCreate() { super.onCreate(); sResources = getResources(); //---I want to load all preferences when my app starts--- PreferenceManager.setDefaultValues(this,R.xml.prefs,false); } }
-9357253 0 How to set placeholder with JS Please take a look at this fiddle:
JQ-UI sets first option as default. I don't want it to be happened: instead I want to set HTML5 placeholder.
How can I set HTML 5 placeholder (instead of first available <option>) for these JS generated inputs?

I think I see what's going on here. It's actually impossible for the Fragment to be duplicated with only one view container.
I suspect that the items in your ListFragment are getting duplicated due to the call to populateList() in onActivityCreated().
BecauseonActivityCreated() is called every time you click the back button to return to ColorListFragment from SaturationListFragment, it is calling populateList() every time. See documentation here
In order to fix your issue, just move the call to populateList() to onCreate(), which is only called the first time the ListFragment is initialized:
public class ColorListFragment extends ListFragment { private List<ColorGD> mDrawableList = null; private ColorAdapter mAdapter = null; //add the onCreate() override @Override public void onCreate(Bundle savedInstance){ super.onCreate(savedInstance); populateList(); //add this here } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_color_list, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState){ super.onActivityCreated(savedInstanceState); //populateList(); //remove this //..................
-19373415 0 To go back to original app you can use telprompt:// instead of tel:// - The tell prompt will prompt the user first, but when the call is finished it will go back to your app:
NSString *phoneNumber = [@"telprompt://" stringByAppendingString:mymobileNO.titleLabel.text]; [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]]; just an update on above answer.
-15424129 0 Express.io, socket.io.js not foundI got an issue with Express.io, I try to create a simple tchat. But I'm not be able to include the socket.io.js, I got an error...
I just installed Express.io on my new Express project.
My errors :
Index.jade
doctype 5 html head title= title link(rel='stylesheet', href='/stylesheets/style.css') body block content script(src="http://localhost:3000/socket.io/socket.io.js") script(src="/javascripts/user.js") app.js
/** * Module dependencies. */ var express = require('express.io') , index = require('./routes/index.js') , http = require('http') , path = require('path'); var app = express(); app.http().io(); app.configure(function(){ app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); }); app.configure('development', function(){ app.use(express.errorHandler()); }); app.get('/', index.index); app.io.route('ready', function(req) { req.io.emit('talk', { message: 'io event from an io route on the server' }); }); http.createServer(app).listen(app.get('port'), function(){ console.log("Express server listening on port " + app.get('port')); }); index.js (route)
exports.index = function(req, res){ res.render('index', { title: 'TCHAT' }); }; user.js
io = io.connect(); // Emit ready event. io.emit('ready'); // Listen for the talk event. io.on('talk', function(data) { alert(data.message); }); New error
Failed to load resource: the server responded with a status of 404 (Not Found) http://*:3000/socket.io.js Uncaught ReferenceError: io is not defined
-549202 0osascript -e "tell application \"Terminal\" to set background color of window 1 to {0,45000,0,0}"
-10371662 0A generic approach:
:%s/\(<string name="\)\(\u\)\([^" ]\+\) \([^" ]\+\)/\1\l\2\e\3_\4/ This replaces every string @name that
\u) and\([^" ]\+\) \([^" ]\+\)) and \l\2\e). To make everything in @name lower-case, this could be simplified:
:%s/\(<string name="\)\([^" ]\+\) \([^" ]\+\)/\1\l\2_\3_\e/ To get rid of multiple spaces, do two steps. First, make the attribute value lower-case:
:%s/\(<string name="\)\([^"]\+\)/\1\l\2\e/ then, replace every space in the attribute value with an underscore
:%s/\(<string name="[^"]*\)\@<= /_/g Note that the \@<= is vim's way of expressing a positive look-behind assertion.
I'm using C++/CLI .NET 4.5 on Win7. I develop a control with a DataGridView. The cells are not editable by the user neither it is possible to add rows manually.
I need to catch/handle the SelectionChanged event, so I added a handler for it. I also need to catch/handle the CellContentClick event, so I added too the handler for it. If I click on the content of a cell, of course the selection is changed but I would like to catch the event for the click too. The handler for CellContentClick is never called.
If I remove the SelectionChanged handler, the CellContentClick is catched as wanted.
If I put a return as the first line of my SelectionChanged handler, the CellContentClick is never catched neither.
It looks like if the handler for the Selection forbids the event for the click to be fired????
Any idea? Let me know if you need more info about the settings of my DataGridView.
Thanks!
-28209646 0I'm still not sure I understand the question. However, I do know for sure that the C# code you posted won't show anything, because the Rectangle object's width and height are both their default value of 0. An empty rectangle won't draw anything.
When I create a simple window with an empty canvas (using your provided resource):
<Window x:Class="TestSO28203571AddChildCodeBehind.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <VisualBrush x:Key="Alcanc" x:Shared="false" Stretch="Uniform"> <!--Imagem vectorial do Alcance lateral esquerdo--> <VisualBrush.Visual> <Canvas> <Path Data="M120.024,239.976C186.12,239.976 239.976,186.048 239.976,119.952 239.976,53.856 186.12,0 120.024,0 53.928,0 0,53.856 0,119.952 0,186.048 53.928,239.976 120.024,239.976" Fill="White" Height="239.976" Canvas.Left="0" Canvas.Top="0" Width="239.976"/> <Path Data="M84.096,38.304L84.096,138.528 71.784,138.528C66.312,138.528 61.776,134.208 61.416,128.808 61.416,87.912 61.344,119.304 61.344,78.48 59.832,67.608 54.36,59.616 44.424,53.856L3.6,28.512C1.512,27,0.072,24.696,0,22.32L0,22.032C0.072,21.096 0.288,20.16 0.792,19.152 2.736,15.264 8.208,14.832 10.944,16.632L13.68,17.928C29.448,24.696,43.416,30.6,59.184,37.368L59.184,37.44 64.224,38.304 64.944,38.304 65.592,38.304z M84.096,0C75.096,0 67.752,7.416 67.752,16.416 67.752,25.416 75.096,32.76 84.096,32.76z M84.096,138.528L84.096,38.304 104.832,38.304 105.408,38.304C116.568,38.304 125.712,47.376 125.712,58.536 125.712,59.4 125.64,60.192 125.496,61.056L125.496,131.184C125.496,131.256,125.568,131.256,125.568,131.328L125.496,131.4 125.496,131.76C125.28,135.504 122.112,138.528 118.296,138.528 114.48,138.528 111.384,135.504 111.096,131.76L111.096,77.976C110.664,74.448,104.976,74.808,104.832,78.768L104.832,124.704 104.904,124.704 104.904,127.944 104.904,128.088 104.904,128.232 104.904,128.808 104.832,128.808C104.472,134.208,99.936,138.528,94.464,138.528z M84.096,32.76C93.168,32.76 100.512,25.416 100.512,16.416 100.512,7.416 93.168,0 84.096,0z" Fill="#FFCCCCCC" Height="138.528" Canvas.Left="58.464" Canvas.Top="63" Width="125.712"/> <Path Data="M42.017,15.974L3.281,50.246C1.985,51.182 -1.687,56.87 0.905,60.398 3.137,63.638 7.169,63.854 10.409,62.198L51.737,37.646C54.113,36.134 56.921,35.99 60.017,36.782 60.233,37.862 60.449,39.014 60.593,40.166L60.593,87.758C60.449,95.534,64.913,99.206,70.385,99.782L93.929,99.782C100.265,99.638,104.081,93.95,104.081,89.558L104.081,89.414 104.009,40.454C104.225,36.494,109.841,36.134,110.273,39.662L110.273,92.942C110.561,96.686 113.657,99.71 117.473,99.71 121.289,99.71 124.457,96.686 124.673,92.942L124.673,92.582 124.673,92.51 124.673,92.438 124.673,22.814C124.817,21.95 124.817,21.158 124.817,20.294 124.817,9.134 115.745,0.062 104.585,0.062L104.009,0.062 64.841,0.062 64.193,0.062 63.545,0.062C51.593,-1.09,42.521,14.03,42.017,15.974" Fill="#FFCCCCCC" Height="99.783" Canvas.Left="59.215" Canvas.Top="101.818" Width="124.817"/> <Path Data="M6.264,12.6C9.792,12.6 12.6,9.72 12.6,6.264 12.6,2.808 9.792,0 6.264,0 2.808,0 0,2.808 0,6.264 0,9.72 2.808,12.6 6.264,12.6" Fill="#FF3399FF" Height="12.6" Canvas.Left="55.872" Canvas.Top="123.12" Width="12.6"/> <Path Data="F1M0,9.144L9.216,0 9.216,6.912 43.992,6.912 43.992,11.664 9.216,11.664 9.216,18.36z" Fill="#FF3399FF" Height="18.36" Canvas.Left="98.928" Canvas.Top="38.376" Width="43.992"/> <Path Data="M20.165,78.264L20.165,77.904C20.021,74.016,14.549,73.656,14.117,77.112L14.117,131.328 14.045,131.328C13.829,134.928 10.805,137.88 7.061,137.88 3.317,137.88 0.293,134.928 0.077,131.328L0.005,131.328 0.005,130.896 0.005,130.824 0.005,130.752 0.005,60.624C-0.283,49.896,12.461,37.944,22.901,38.232L63.437,38.232 63.509,38.232C63.725,38.16 63.941,38.16 64.157,38.16 75.245,38.16 84.389,47.304 84.389,58.392 84.389,59.256 84.317,60.12 84.173,60.912L84.173,130.608 84.173,130.68 84.173,130.752 84.173,131.112C83.957,134.856 80.789,137.88 76.973,137.88 73.229,137.88 70.061,134.856 69.845,131.112L69.773,131.112 69.773,77.832C69.341,74.304,63.725,74.664,63.581,78.624L63.581,128.088 63.581,127.44 63.581,127.584 63.581,127.728 63.581,128.304C63.221,133.704,58.685,137.88,53.213,137.88L30.605,137.88C25.061,137.88,20.525,133.704,20.165,128.304L20.165,78.336z M42.845,0C33.845,0 26.501,7.344 26.501,16.344 26.501,25.344 33.845,32.688 42.845,32.688 51.845,32.688 59.189,25.344 59.189,16.344 59.189,7.344 51.845,0 42.845,0" Fill="#FF99CC00" Height="137.88" Canvas.Left="99.643" Canvas.Top="63.648" Width="84.389"/> </Canvas> </VisualBrush.Visual> </VisualBrush> </Window.Resources> <Canvas x:Name="canvas1" /> </Window> And then I declare MainWindow like this:
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); Rectangle rect = new Rectangle { VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center, Fill = (Brush)FindResource("Alcanc"), Width = 200, Height = 150 }; canvas1.Children.Add(rect); } } Your graphic is drawn correctly. Well, it's drawn…I don't actually know what size you wanted it. But the key is, you need to specify a size.
-22097029 0 Nested Dictionary in RI'm more used to a python environment. Is there a way to produce a dictionary/list that is fully dynamic. I.e. that I could create flexible data structures say that relate to a particular number such as
[1:["var_a":6, "var_b":3],2:[..]] Where I will not know how may elements in each list. Is there a way to do this?
-22236706 0I figured I'd elaborate on my comment. I'd just have some bitwise fun.
char string[] = "123456" byte1 = ((unsigned char)string[0] << 4) | (unsigned char)string[1]; byte2 = ((unsigned char)string[2] << 4) | (unsigned char)string[3]; byte3 = ((unsigned char)string[4] << 4) | (unsigned char)string[5];
-19342595 0 I was battling this for a few hours as well and came up with a solution. In my project i am using angular to control the actual view switching. so what i did was to define two separate route groups in L4, one that returns actual pages directly from laravel's routing system and another that returns HTML fragments for angulars routing system.
Here is an example of my routing
//Laravel pages and API routes Route::get('/', function() { return View::make('hello'); }); Route::get('/register',function(){ return View::make('registration'); }); //Angular SPA routes(HTML fragments for angulars routing system) Route::get('/getstarted', function(){ return View::make('getStarted'); }); Route::get('/terms',function(){ return View::make('terms'); }); So in this scenario, laravel sends your home page when you call "/", and the ng-view asks for "/getstarted" by ajax which returns your html fragment. Hope this helps :)
-23458780 0I know for sure that the C++ version supports merging two channels, so you can use it. Have you tried passing two input images and NULL for the rest?
-7488838 0 Gradient Backgrounds in internet explorer version <=8I need to have gradient backgrounds on my website for internet explorer. I know there is some kind of proprietry way of doing this:
filter: progid:DXImageTransform.Microsoft.gradient(startColorStr='#20799d', EndColorStr='#5cb9df'); But this doesn't grok with border-radius (supported by IE8, at least), which my site uses all over the place.
How should I solve this? (Other than just not having gradient backgrounds on old versions of IE, I mean.)
-28223574 0 Try to move UIImageView in screen with touchesMovedI try to move 2 UIImageView.
Only one picture is supposed to move when I drag.
What I trying to accomplish is move UIImageView when I touch and drag the UIImageView.
This Is my viewDidLoad :
-(void)viewDidLoad { [super viewDidLoad]; myImageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 200, 100)]; [myImageView setImage:[UIImage imageNamed:@"image1.png"]]; [self.view addSubview:myImageView]; myImageView1 = [[UIImageView alloc]initWithFrame:CGRectMake(100, 200, 200,100)]; [myImageView1 setImage:[UIImage imageNamed:@"image2"]]; [self.view addSubview:myImageView1]; } This Is my touchesMoved method :
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { // get touch event UITouch *touch = [[event allTouches] anyObject]; CGPoint touchLocation = [touch locationInView:self.view]; for (UIImageView *image in [self.view subviews]) { if ([touch view] == image) { // move the image view image.center = touchLocation; } } } In this line I don't get the images view
for (UIImageView *image in [self.view subviews]) It is possible to get the current touched UIIamgeView ?
-21748244 0You might also consider using Packer to create VirtualBox images for developers to use.
Rather than sharing the Vagrantfile which developers each use to build and run their VM, you would have a packer template (json) which is used to create a VM image. Developers download or copy the image and run it locally, directly in VB, without having to build it themselves.
Many of the publicly shared Vagrant base boxes are created with Packer.
-40359412 0I used the (penultimate) code in Robert McKee's solution, however, had to adapt it to get it to compile and display correctly in the view:
public ActionResult Create() { ViewBag.AllSystems = new MultiSelectList(db.dbSystem.Select(x=>new { Name=x.systemName, Value=x.systemId }),"Value","Name"); return View(); } etc....
-26905220 0Create a List<TextBox> for each group:
List<TextBox> list01 = new List<TextBox>() { tbPlay0, tbPlay1, ....}; List<TextBox> list02 = new List<TextBox>() { ..., ... , ....}; // .. } And pass such a group to the function:
private void convertBasetoDrawn(List<TextBox> list, string numBase, string reference) { string[] texts = new string[8] { "000", "500", "050", "005", "550", "505", "055", "555" }; for (int t = 0; t < list.Count; t++) list[t].Text = texts[t]; list[0].ForeColor = Color.Red; list[7].ForeColor = Color.Red; } Assuming the texts will always look like that. If they depend on, maybe numbase you can construct them dynamically as well, as long as you know the rules.. Maybe even a simple replacement will do the job?
You didn't use reference, btw..
Now, I'm just guessig here, but maybe this is the pattern for your texts..:
string[] texts = new string[8] { "nnn", "dnn", "ndn", "nnd", "ddn", "dnd", "ndd", "ddd" }; for (int s = 0; s < texts.Length; s++) texts[s] = texts[s].Replace("d", numBase).Replace("n", reference); Now you can call it like this:
convertBasetoDrawn(list01, "0","5"); Update: For the rules as I understand them now you could do:
string newText = ""; for (int s = 0; s < texts.Length; s++) { newText = ""; for (int i = 0; i < 3; i++) { if (texts[s][i] == 'n') newText += numBase[i]; else newText += (Convert.ToByte(numBase[i].ToString()) + Convert.ToByte(reference[0].ToString()) ).ToString("0"); } texts[s] = newText; } and call it like this:
convertBasetoDrawn(list01, "001", "5"); or
convertBasetoDrawn(list02, "000", "1"); Note: no carry over here.. You'd have to define rules for that and code it yourself..